Skip to content

Commit

Permalink
fix: indent flags descriptions based on the terminal width (#103)
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinKolarik authored Jun 17, 2024
1 parent a64f850 commit ad2db29
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cmd

import (
"github.com/spf13/pflag"
"golang.org/x/term"
"os"
"os/signal"
"syscall"
Expand Down Expand Up @@ -75,6 +77,11 @@ The CLI tool allows you to interact with the API in a simple and human-friendly

root.Cmd.SetOut(printer.OutWriter)
root.Cmd.SetErr(printer.ErrWriter)

cobra.AddTemplateFunc("wrappedFlagUsages", wrappedFlagUsages)
root.Cmd.SetUsageTemplate(usageTemplate)
root.Cmd.SetHelpTemplate(helpTemplate)

// Global flags
flags := root.Cmd.PersistentFlags()
flags.StringVarP(&ctx.From, "from", "F", ctx.From, `Comma-separated list of location values to match against or a measurement ID
Expand All @@ -99,3 +106,48 @@ The CLI tool allows you to interact with the API in a simple and human-friendly

return root
}

// Uses the users terminal size or width of 80 if cannot determine users width
// Based on https://github.com/spf13/cobra/issues/1805#issuecomment-1246192724
func wrappedFlagUsages(cmd *pflag.FlagSet) string {
fd := int(os.Stdout.Fd())
width := 80

// Get the terminal width and dynamically set
termWidth, _, err := term.GetSize(fd)
if err == nil {
width = termWidth
}

return cmd.FlagUsagesWrapped(width - 1)
}

// Identical to the default cobra usage template,
// but utilizes wrappedFlagUsages to ensure flag usages don't wrap around
var usageTemplate = `Usage:{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
Aliases:
{{.NameAndAliases}}{{end}}{{if .HasExample}}
Examples:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{wrappedFlagUsages .LocalFlags | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
Global Flags:
{{wrappedFlagUsages .InheritedFlags | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`

var helpTemplate = `
{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`

0 comments on commit ad2db29

Please sign in to comment.