MCPcopy Create free account
hub / github.com/cli/cli / FormatSlice

Function FormatSlice

internal/text/text.go:122–176  ·  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

120// brackets). If the lineLength argument is non-positive, no line length limit
121// will be applied.
122func FormatSlice(values []string, lineLength uint, indent uint, prependWith string, appendWith string, sort bool) string {
123 if lineLength <= 0 {
124 lineLength = math.MaxInt
125 }
126
127 sortedValues := values
128 if sort {
129 sortedValues = slices.Clone(values)
130 slices.Sort(sortedValues)
131 }
132
133 pre := strings.Repeat(" ", int(indent))
134 if len(sortedValues) == 0 {
135 return pre
136 } else if len(sortedValues) == 1 {
137 return pre + sortedValues[0]
138 }
139
140 builder := strings.Builder{}
141 currentLineLength := 0
142 sep := ","
143 ws := " "
144
145 for i := 0; i < len(sortedValues); i++ {
146 v := prependWith + sortedValues[i] + appendWith
147 isLast := i == -1+len(sortedValues)
148
149 if currentLineLength == 0 {
150 builder.WriteString(pre)
151 builder.WriteString(v)
152 currentLineLength += len(v)
153 if !isLast {
154 builder.WriteString(sep)
155 currentLineLength += len(sep)
156 }
157 } else {
158 if !isLast && currentLineLength+len(ws)+len(v)+len(sep) > int(lineLength) ||
159 isLast && currentLineLength+len(ws)+len(v) > int(lineLength) {
160 currentLineLength = 0
161 builder.WriteString("\n")
162 i--
163 continue
164 }
165
166 builder.WriteString(ws)
167 builder.WriteString(v)
168 currentLineLength += len(ws) + len(v)
169 if !isLast {
170 builder.WriteString(sep)
171 currentLineLength += len(sep)
172 }
173 }
174 }
175 return builder.String()
176}
177
178// FormatSize formats a byte count using binary units (B, KB, MB, GB, TB, PB).
179// Values below a kilobyte are shown as whole bytes; larger values are shown with

Callers 5

WriteHelpFunction · 0.92
printJSONFieldsFunction · 0.92
printAliasesFunction · 0.92
manPrintJSONFieldsFunction · 0.92
TestFormatSliceFunction · 0.85

Calls 2

CloneMethod · 0.65
StringMethod · 0.65

Tested by 1

TestFormatSliceFunction · 0.68