Skip to content

Help text does not wrap: pflag is given no width, so every line length is maintained by hand #755

Closed

Description

@David-Noble-at-work

Help text does not wrap. Cobra's default template calls FlagUsages, which is FlagUsagesWrapped(0), and
wrap treats 0 as "re-indent after existing newlines, wrap nothing":

func wrap(i, w int, s string) string {
	if w == 0 {
		return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1)
	}

So every line's width is the author's to manage. --output's usage is hand-wrapped to 88 columns today so
it fits 120 once pflag adds its 32-column indent -- a constant maintained by hand, in one flag, that no test
enforces and that is wrong on any terminal narrower than 120.

What the fix would be

FlagUsagesWrapped(cols) already exists. Register a template function that computes the width and swap it
into the usage template in cli.NewRootCmd, so all four programs inherit it:

cobra.AddTemplateFunc("wrappedFlagUsages", func(f *pflag.FlagSet) string {
    return f.FlagUsagesWrapped(helpWidth())
})

helpWidth takes COLUMNS when set and numeric, else term.GetSize on stdout when it is a TTY, else a
fallback. golang.org/x/term is already a dependency through pkg/sink, so nothing new is required.

The catch, which is why this is an issue and not a one-liner

wrapN re-flows text at word boundaries. That suits a prose paragraph and destroys an aligned table. On
an 80-column terminal the wrap width is 80 - 32 - 5 = 43, so --output's format list becomes:

csv            quoted and parseable; when a
spreadsheet or a data tool reads it

The two-column alignment is what makes that list scannable. There is also a floor: below wrap < 24 pflag
re-indents to 16, and failing that gives up and does not wrap at all.

So wrapping cannot simply be switched on. The shape that gets both properties is to split the two kinds of
text:

  • Flag usage stays one line -- prose, wraps freely, benefits from COLUMNS.
  • The format table moves into the command's Long description, which cobra does not reflow, so its
    alignment survives at any width.

That is a change to how --output is documented, not only to how it is wrapped, which is why it wants its
own review.

Verification

  • COLUMNS=60 writ status --help produces no line over 60.
  • COLUMNS=200 writ status --help produces no line over 200 and does not pad to it.
  • Piped output (no TTY, no COLUMNS) wraps at the fallback rather than at zero.
  • The --output format list keeps its column alignment at every width.
  • A test asserts the longest rendered line against a set COLUMNS, so the constant stops being maintained
    by hand.

Metadata

Metadata

Labels

enhancement

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions