POSIX-Style Usage for Cobra Applications
cobra-posix-usage is a small library to provide POSIX-style usage for Cobra-based applications.
By default, a Cobra application will look something like this
% free --help
free $Revision: 0.3.9 $ by Cursed Bananazon (C) 2023-2026
Usage:
free [flags]
With cobra-posix-usage, you end up with this
% free --help
free $Revision: 0.3.9 $ by Cursed Bananazon (C) 2023-2026
Usage:
free [--bytes] [--kilo] [--mega] [--giga] [--tera] [--peta] [--exa] [--kibi]
[--mebi] [--gibi] [--tebi] [--pebi] [--exbi] [--json] [--yaml] [--si]
[--total] [--seconds=int] [--count=int] [--version] [--help]
Example Usage
package cmd
import (
"fmt"
"os"
"time"
"codeberg.org/bananazon/free/pkg/free"
cobra_posix_usage "codeberg.org/bananazon/cobra-posix-usage"
"github.com/spf13/cobra"
)
var(
rootCmd = &cobra.Command{
Use: "free",
Short: "",
Long: "free $Revision: 0.3.9 $ by Cursed Bananazon (C) 2023-2026",
PreRun: freePreRunCmd,
RunE: freeRunCmd,
}
usage = cobra_posix_usage.New()
usageIndentWidth int = 7
usageMaxWidth int = 80
usageSortFlags bool = false
)
func init() {
usage.IndentWidth = usageIndentWidth
usage.MaxWidth = usageMaxWidth
usage.SortFlags = usageSortFlags
rootCmd.Flags().SortFlags = usage.SortFlags
rootCmd.PersistentFlags().SortFlags = usage.SortFlags
GetPersistentFlags(rootCmd)
cobra.AddTemplateFunc("Indent", usage.Indent)
cobra.AddTemplateFunc("PosixUsage", func(rootCmd *cobra.Command) string {
return usage.GenerateUsage(rootCmd)
})
rootCmd.SetUsageTemplate(usage.UsageTemplate)
}
Other Stuff
Disable --help and --version in the Usage
Having [--help] and [--version] in there is kind of overkill, but some people like it. You can suppress showing them in the usage string like this
usage.HideHelp = true
usage.HideVersion = true
Now you will see this
% free --help
free $Revision: 0.3.7 $ by Cursed Bananazon (C) 2023-2026
Usage:
free [--bytes] [--kilo] [--mega] [--giga] [--tera] [--peta] [--exa] [--kibi]
[--mebi] [--gibi] [--tebi] [--pebi] [--exbi] [--json] [--yaml] [--si]
[--total] [--seconds=int] [--count=int]
Sorted
To sort flags alphabetically you do this
usage.SortFlags = true
and you get this
% free --help
free $Revision: 0.3.9 $ by Cursed Bananazon (C) 2023-2026
Usage:
free [--bytes] [--count=int] [--exa] [--exbi] [--gibi] [--giga] [--help]
[--json] [--kibi] [--kilo] [--mebi] [--mega] [--pebi] [--peta]
[--seconds=int] [--si] [--tebi] [--tera] [--total] [--version] [--yaml]
Unsorted
To sort flags in the order they were defined you do this (this is the default)
usage.SortFlags = false
and you get this
% free --help
free $Revision: 0.3.9 $ by Cursed Bananazon (C) 2023-2026
Usage:
free [--bytes] [--kilo] [--mega] [--giga] [--tera] [--peta] [--exa] [--kibi]
[--mebi] [--gibi] [--tebi] [--pebi] [--exbi] [--json] [--yaml] [--si]
[--total] [--seconds=int] [--count=int] [--version] [--help]