github.com/graywolf-at-work-2/terraform-vendor@v1.4.5/internal/command/format/trivia.go (about) 1 package format 2 3 import ( 4 "strings" 5 6 "github.com/mitchellh/colorstring" 7 wordwrap "github.com/mitchellh/go-wordwrap" 8 ) 9 10 // HorizontalRule returns a newline character followed by a number of 11 // horizontal line characters to fill the given width. 12 // 13 // If the given colorize has colors enabled, the rule will also be given a 14 // dark grey color to attempt to visually de-emphasize it for sighted users. 15 // 16 // This is intended for printing to the UI via mitchellh/cli.UI.Output, or 17 // similar, which will automatically append a trailing newline too. 18 func HorizontalRule(color *colorstring.Colorize, width int) string { 19 if width <= 1 { 20 return "\n" 21 } 22 rule := strings.Repeat("─", width-1) 23 if color == nil { // sometimes unit tests don't populate this properly 24 return "\n" + rule 25 } 26 return color.Color("[dark_gray]\n" + rule) 27 } 28 29 // WordWrap takes a string containing unbroken lines of text and inserts 30 // newline characters to try to make the text fit within the given width. 31 // 32 // The string can already contain newline characters, for example if you are 33 // trying to render multiple paragraphs of text. (In that case, our usual 34 // style would be to have _two_ newline characters as the paragraph separator.) 35 // 36 // As a special case, any line that begins with at least one space will be left 37 // unbroken. This allows including literal segments in the output, such as 38 // code snippets or filenames, where word wrapping would be confusing. 39 func WordWrap(str string, width int) string { 40 if width <= 1 { 41 // Silly edge case. We'll just return the original string to avoid 42 // panicking or doing other weird stuff. 43 return str 44 } 45 46 var buf strings.Builder 47 lines := strings.Split(str, "\n") 48 for i, line := range lines { 49 if !strings.HasPrefix(line, " ") { 50 line = wordwrap.WrapString(line, uint(width-1)) 51 } 52 if i > 0 { 53 buf.WriteByte('\n') // reintroduce the newlines we skipped in Scan 54 } 55 buf.WriteString(line) 56 } 57 return buf.String() 58 }