MCPcopy
hub / github.com/cli/cli / FormatSlice

Function FormatSlice

internal/text/text.go:97–151  ·  view source on GitHub ↗

FormatSlice concatenates elements of the given string slice into a well-formatted, possibly multiline, string with specific line length limit. Elements can be optionally surrounded by custom strings (e.g., quotes or brackets). If the lineLength argument is non-positive, no line length limit will be

(values []string, lineLength uint, indent uint, prependWith string, appendWith string, sort bool)

Source from the content-addressed store, hash-verified

95// brackets). If the lineLength argument is non-positive, no line length limit
96// will be applied.
97func FormatSlice(values []string, lineLength uint, indent uint, prependWith string, appendWith string, sort bool) string {
98 if lineLength <= 0 {
99 lineLength = math.MaxInt
100 }
101
102 sortedValues := values
103 if sort {
104 sortedValues = slices.Clone(values)
105 slices.Sort(sortedValues)
106 }
107
108 pre := strings.Repeat(" ", int(indent))
109 if len(sortedValues) == 0 {
110 return pre
111 } else if len(sortedValues) == 1 {
112 return pre + sortedValues[0]
113 }
114
115 builder := strings.Builder{}
116 currentLineLength := 0
117 sep := ","
118 ws := " "
119
120 for i := 0; i < len(sortedValues); i++ {
121 v := prependWith + sortedValues[i] + appendWith
122 isLast := i == -1+len(sortedValues)
123
124 if currentLineLength == 0 {
125 builder.WriteString(pre)
126 builder.WriteString(v)
127 currentLineLength += len(v)
128 if !isLast {
129 builder.WriteString(sep)
130 currentLineLength += len(sep)
131 }
132 } else {
133 if !isLast && currentLineLength+len(ws)+len(v)+len(sep) > int(lineLength) ||
134 isLast && currentLineLength+len(ws)+len(v) > int(lineLength) {
135 currentLineLength = 0
136 builder.WriteString("\n")
137 i--
138 continue
139 }
140
141 builder.WriteString(ws)
142 builder.WriteString(v)
143 currentLineLength += len(ws) + len(v)
144 if !isLast {
145 builder.WriteString(sep)
146 currentLineLength += len(sep)
147 }
148 }
149 }
150 return builder.String()
151}
152
153// FormatSize formats a byte count using binary units (B, KB, MB, GB, TB, PB).
154// Values below a kilobyte are shown as whole bytes; larger values are shown with

Callers 5

rootHelpFuncFunction · 0.92
printJSONFieldsFunction · 0.92
printAliasesFunction · 0.92
manPrintJSONFieldsFunction · 0.92
TestFormatSliceFunction · 0.85

Calls 2

CloneMethod · 0.65
StringMethod · 0.45

Tested by 1

TestFormatSliceFunction · 0.68