...

Source file src/golang.conradwood.net/go-easyops/utils/multiline.go

Documentation: golang.conradwood.net/go-easyops/utils

     1  package utils
     2  
     3  import (
     4  	"slices"
     5  	"strings"
     6  )
     7  
     8  /*
     9  Adds a prefix to each line of a multi-line string.
    10  it hounours existing line breaks (\n)
    11  if line is longer than linelen it will add a linebreak
    12  empty trailing lines will be trimmed
    13  a single trailing \n will be retained.
    14  */
    15  func MultiLinePrefix(input, prefix string, linelen int) string {
    16  	lines := strings.Split(input, "\n")
    17  	if len(lines) == 0 {
    18  		return ""
    19  	}
    20  
    21  	// remove trailing empty lines
    22  	for lines[len(lines)-1] == "" {
    23  		lines = lines[:len(lines)-1]
    24  		if len(lines) == 0 {
    25  			return ""
    26  		}
    27  	}
    28  
    29  	// word wrap
    30  	repeat := true
    31  	for repeat {
    32  		repeat = false
    33  		for i, line := range lines {
    34  			if len(line) <= linelen {
    35  				continue
    36  			}
    37  			oline := line[:linelen]
    38  			rline := line[linelen:]
    39  
    40  			lines[i] = rline
    41  			lines = slices.Insert(lines, i, oline)
    42  			repeat = true
    43  		}
    44  	}
    45  
    46  	for i, line := range lines {
    47  		lines[i] = prefix + line
    48  	}
    49  	res := strings.Join(lines, "\n")
    50  	if input[len(input)-1] == '\n' {
    51  		res = res + "\n"
    52  	}
    53  	return res
    54  }
    55  

View as plain text