Skip to content

Instantly share code, notes, and snippets.

@andreimerlescu
Created June 10, 2023 14:10
Show Gist options
  • Save andreimerlescu/3b546d8763661bc486139946b8c04c3b to your computer and use it in GitHub Desktop.
Save andreimerlescu/3b546d8763661bc486139946b8c04c3b to your computer and use it in GitHub Desktop.
Format Go Flag Into Human Readable Output
flag.Usage = func() {
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintf(w, "%v [FLAGS]\n", os.Args[0])
fmt.Fprintln(w, "Flag\tDefault\tDescription")
nl, dl, ul := 4, 7, 11
out := ""
flag.VisitAll(func(f *flag.Flag) {
out += fmt.Sprintf("-%s\t%s\t%s\n", f.Name, f.DefValue, f.Usage)
if len(f.Name)+1 > nl {
nl = len(f.Name) + 1
}
if len(f.DefValue) > dl {
dl = len(f.DefValue)
}
if len(f.Usage) > ul {
ul = len(f.Usage)
}
})
fmt.Fprintf(w, "%v\t%v\t%v\n", strings.Repeat("-", nl), strings.Repeat("-", dl), strings.Repeat("-", ul))
fmt.Fprintln(w, out)
w.Flush()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment