-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhelp_compact.go
More file actions
419 lines (367 loc) · 10.6 KB
/
help_compact.go
File metadata and controls
419 lines (367 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package warg
import (
"bufio"
"fmt"
"os"
"strings"
"go.bbkane.com/warg/styles"
"go.bbkane.com/warg/value"
)
// compactFlagLine holds the pre-computed parts of a flag line for column alignment.
type compactFlagLine struct {
// leftCol is the flag name/alias/type portion (e.g., " -e, --editor string")
leftCol string
// rightCol is the description + metadata (e.g., "path to editor (default \"vi\") (required) [env: EDITOR]")
rightCol string
}
// compactBuildFlagLine constructs the left and right columns for a single flag.
func compactBuildFlagLine(s *styles.Styles, name string, f *Flag, val value.Value) compactFlagLine {
// Build left column: " -a, --name type" or " --name type"
var left strings.Builder
left.WriteString(" ")
if f.Alias != "" {
left.WriteString(s.FlagAlias(f.Alias))
left.WriteString(", ")
} else {
left.WriteString(" ")
}
left.WriteString(s.FlagName(name))
left.WriteString(" ")
left.WriteString(val.Description())
// Build right column: description + annotations
var right strings.Builder
right.WriteString(f.HelpShort)
// Add default value
if val.HasDefault() {
switch v := val.(type) {
case value.ScalarValue:
fmt.Fprintf(&right, " [default: %q]", v.DefaultString())
case value.SliceValue:
fmt.Fprintf(&right, " [default: %v]", v.DefaultStringSlice())
case value.DictValue:
fmt.Fprintf(&right, " [default: %v]", v.DefaultStringMap())
}
}
// Add required marker
if f.Required {
right.WriteString(" [required]")
}
// Add env vars
if len(f.EnvVars) > 0 {
fmt.Fprintf(&right, " [env: %s]", strings.Join(f.EnvVars, ", "))
}
// Add config path
if f.ConfigPath != "" {
fmt.Fprintf(&right, " [config: %s]", f.ConfigPath)
}
if val.UpdatedBy() != value.UpdatedByUnset {
fmt.Fprintf(&right, " [setby: %s]", string(val.UpdatedBy()))
switch v := val.(type) {
case value.ScalarValue:
fmt.Fprintf(&right, " [current: %q]", v.String())
case value.SliceValue:
fmt.Fprintf(&right, " [current: %v]", v.StringSlice())
case value.DictValue:
fmt.Fprintf(&right, " [current: %v]", v.StringMap())
}
}
return compactFlagLine{
leftCol: left.String(),
rightCol: right.String(),
}
}
// compactVisibleLen returns the visible length of a string, stripping ANSI escape sequences.
func compactVisibleLen(s string) int {
n := 0
inEscape := false
for _, r := range s {
if r == '\033' {
inEscape = true
continue
}
if inEscape {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') {
inEscape = false
}
continue
}
n++
}
return n
}
// compactWrapText wraps text at word boundaries to fit within maxWidth characters.
// Each continuation line is indented by indent spaces.
func compactWrapText(text string, indent int, maxWidth int) string {
if maxWidth <= 0 {
return text
}
words := strings.Fields(text)
if len(words) == 0 {
return ""
}
indentStr := strings.Repeat(" ", indent)
var result strings.Builder
lineLen := 0
for i, word := range words {
wordLen := len(word)
if i == 0 {
result.WriteString(word)
lineLen = wordLen
continue
}
// Check if adding this word would exceed the max width.
if lineLen+1+wordLen > maxWidth {
result.WriteString("\n")
result.WriteString(indentStr)
result.WriteString(word)
lineLen = wordLen
} else {
result.WriteString(" ")
result.WriteString(word)
lineLen += 1 + wordLen
}
}
return result.String()
}
// compactPrintFlags prints a set of flag lines with aligned columns, respecting terminal width.
func compactPrintFlags(p *styles.Printer, lines []compactFlagLine, termWidth int) {
if len(lines) == 0 {
return
}
// Find the maximum left column width for alignment
maxLeftWidth := 0
for _, line := range lines {
w := compactVisibleLen(line.leftCol)
if w > maxLeftWidth {
maxLeftWidth = w
}
}
// Add a gutter of at least 3 spaces between columns
const gutter = 3
descCol := maxLeftWidth + gutter
for _, line := range lines {
leftWidth := compactVisibleLen(line.leftCol)
padding := strings.Repeat(" ", descCol-leftWidth)
if termWidth > 0 {
// Available width for description text
availWidth := termWidth - descCol
if availWidth < 20 {
// If the terminal is very narrow, just print without wrapping
p.Printf("%s%s%s\n", line.leftCol, padding, line.rightCol)
} else {
wrapped := compactWrapText(line.rightCol, descCol, availWidth)
p.Printf("%s%s%s\n", line.leftCol, padding, wrapped)
}
} else {
p.Printf("%s%s%s\n", line.leftCol, padding, line.rightCol)
}
}
}
// compactCmdHelp returns an Action that prints Compact-style help for the current command.
func compactCmdHelp() Action {
return func(cmdCtx CmdContext) error {
file := cmdCtx.Stdout
f := bufio.NewWriter(file)
defer f.Flush()
s, err := conditionallyEnableStyle(false, cmdCtx.Flags, file)
if err != nil {
fmt.Fprintf(os.Stderr, "Error enabling color. Continuing without: %v\n", err)
}
p := styles.NewPrinter(f)
cur := cmdCtx.ParseState.CurrentCmd
termWidth := TermWidth(cmdCtx.Stdout, cmdCtx.Flags)
// Build the usage path: <app> [section...] <cmd>
var usagePath strings.Builder
usagePath.WriteString(string(cmdCtx.App.Name))
for _, sec := range cmdCtx.ParseState.SectionPath {
usagePath.WriteString(" ")
usagePath.WriteString(sec)
}
usagePath.WriteString(" ")
usagePath.WriteString(cmdCtx.ParseState.CurrentCmdName)
// Usage line
p.Printf("%s:\n", s.Header("Usage"))
if cur.AllowForwardedArgs {
p.Printf(" %s [flags] -- [args]\n", usagePath.String())
} else {
p.Printf(" %s [flags]\n", usagePath.String())
}
p.Println()
// Description
if cur.HelpLong != "" {
p.Println(cur.HelpLong)
} else {
p.Println(cur.HelpShort)
}
p.Println()
// Command Flags
cmdFlags := cmdCtx.ParseState.CurrentCmd.Flags
groups := cmdFlags.groupedNames()
hasAnyFlags := false
for _, group := range groups {
var lines []compactFlagLine
for _, name := range group.FlagNames {
fl := cmdFlags[name]
val := cmdCtx.ParseState.FlagValues[name]
lines = append(lines, compactBuildFlagLine(&s, name, &fl, val))
}
if len(lines) > 0 {
if group.Name == "" {
if !hasAnyFlags {
p.Printf("%s:\n", s.Header("Flags"))
}
} else {
if !hasAnyFlags {
p.Printf("%s:\n", s.Header("Flags"))
}
p.Printf("\n %s:\n", s.Header(group.Name))
}
compactPrintFlags(p, lines, termWidth)
hasAnyFlags = true
}
}
if hasAnyFlags {
p.Println()
}
// Global Flags
globalGroups := cmdCtx.App.GlobalFlags.groupedNames()
hasAnyGlobalFlags := false
for _, group := range globalGroups {
var lines []compactFlagLine
for _, name := range group.FlagNames {
fl := cmdCtx.App.GlobalFlags[name]
val := cmdCtx.ParseState.FlagValues[name]
lines = append(lines, compactBuildFlagLine(&s, name, &fl, val))
}
if len(lines) > 0 {
if !hasAnyGlobalFlags {
p.Printf("%s:\n", s.Header("Global Flags"))
}
if group.Name != "" {
p.Printf("\n %s:\n", s.Header(group.Name))
}
compactPrintFlags(p, lines, termWidth)
hasAnyGlobalFlags = true
}
}
if hasAnyGlobalFlags {
p.Println()
}
// Footer
if cur.Footer != "" {
p.Printf("%s:\n", s.Header("Footer"))
p.Println(cur.Footer)
}
return nil
}
}
// compactSectionHelp returns an Action that prints Compact-style help for the current section.
func compactSectionHelp() Action {
return func(cmdCtx CmdContext) error {
file := cmdCtx.Stdout
f := bufio.NewWriter(file)
defer f.Flush()
s, err := conditionallyEnableStyle(false, cmdCtx.Flags, file)
if err != nil {
fmt.Fprintf(os.Stderr, "Error enabling color. Continuing without: %v\n", err)
}
p := styles.NewPrinter(f)
cur := cmdCtx.ParseState.CurrentSection
termWidth := TermWidth(cmdCtx.Stdout, cmdCtx.Flags)
// Build the usage path: <app> [section...]
var usagePath strings.Builder
usagePath.WriteString(string(cmdCtx.App.Name))
for _, sec := range cmdCtx.ParseState.SectionPath {
usagePath.WriteString(" ")
usagePath.WriteString(sec)
}
// Usage line
p.Printf("%s:\n", s.Header("Usage"))
p.Printf(" %s [command]\n", usagePath.String())
p.Println()
// Description
if cur.HelpLong != "" {
p.Println(cur.HelpLong)
} else {
p.Println(cur.HelpShort)
}
p.Println()
// Available Commands
if len(cur.Cmds) > 0 {
p.Printf("%s:\n", s.Header("Available Commands"))
// Compute max command name length for alignment
maxNameLen := 0
for _, k := range cur.Cmds.SortedNames() {
if len(k) > maxNameLen {
maxNameLen = len(k)
}
}
const gutter = 3
descCol := 2 + maxNameLen + gutter // 2 for indent
for _, k := range cur.Cmds.SortedNames() {
name := s.CommandName(k)
nameVisLen := compactVisibleLen(name)
padding := strings.Repeat(" ", descCol-2-nameVisLen+gutter-gutter) // align to descCol from after the indent
// Recalculate: indent(2) + name + padding + desc
pad := strings.Repeat(" ", 2+maxNameLen+gutter-2-nameVisLen)
desc := cur.Cmds[string(k)].HelpShort
if termWidth > 0 {
availWidth := termWidth - descCol
if availWidth >= 20 {
desc = compactWrapText(desc, descCol, availWidth)
}
}
_ = padding
p.Printf(" %s%s%s\n", name, pad, desc)
}
p.Println()
}
// Sections (sub-sections)
if len(cur.Sections) > 0 {
p.Printf("%s:\n", s.Header("Additional Commands"))
maxNameLen := 0
for _, k := range cur.Sections.SortedNames() {
if len(k) > maxNameLen {
maxNameLen = len(k)
}
}
const gutter = 3
descCol := 2 + maxNameLen + gutter
for _, k := range cur.Sections.SortedNames() {
name := s.SectionName(k)
nameVisLen := compactVisibleLen(name)
pad := strings.Repeat(" ", 2+maxNameLen+gutter-2-nameVisLen)
desc := cur.Sections[k].HelpShort
if termWidth > 0 {
availWidth := termWidth - descCol
if availWidth >= 20 {
desc = compactWrapText(desc, descCol, availWidth)
}
}
p.Printf(" %s%s%s\n", name, pad, desc)
}
p.Println()
}
// // Global Flags
// var globalFlagLines []compactFlagLine
// for _, name := range cmdCtx.App.GlobalFlags.SortedNames() {
// fl := cmdCtx.App.GlobalFlags[name]
// val := cmdCtx.ParseState.FlagValues[name]
// globalFlagLines = append(globalFlagLines, compactBuildFlagLine(&s, name, &fl, val))
// }
// if len(globalFlagLines) > 0 {
// p.Printf("%s:\n", s.Header("Global Flags"))
// compactPrintFlags(p, globalFlagLines, termWidth)
// p.Println()
// }
// Footer hint
p.Printf("Use \"%s [command] --help\" for more information about a command.\n", usagePath.String())
// Section footer
if cur.Footer != "" {
p.Println()
p.Printf("%s:\n", s.Header("Footer"))
p.Println(cur.Footer)
}
return nil
}
}