google / subcommands

Go subcommand library.
Apache License 2.0
749 stars 48 forks source link

Groups aliased commands with original in messaging #16

Closed donatj closed 5 years ago

donatj commented 6 years ago

This is an addendum to my previous addition of Aliases modifying the help output to group the aliases with the original command.

I am open to any and all criticism.

Here's a summary of what the changes do:

For the following program

package main

import (
    "context"
    "flag"
    "os"

    "github.com/google/subcommands"
)

type InitCmd struct{}

func (*InitCmd) Name() string             { return "init" }
func (*InitCmd) Synopsis() string         { return "initialize the cli" }
func (*InitCmd) Usage() string            { return `init` }
func (*InitCmd) SetFlags(f *flag.FlagSet) {}
func (*InitCmd) Execute(_ context.Context, _ *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
    return subcommands.ExitSuccess
}

type ListCmd struct{}

func (*ListCmd) Name() string             { return "list" }
func (*ListCmd) Synopsis() string         { return "list the items" }
func (*ListCmd) Usage() string            { return `list` }
func (*ListCmd) SetFlags(f *flag.FlagSet) {}
func (*ListCmd) Execute(_ context.Context, _ *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
    return subcommands.ExitSuccess
}

func main() {
    subcommands.Register(&InitCmd{}, "")
    subcommands.Register(&ListCmd{}, "")
    subcommands.Register(subcommands.Alias("ls", &ListCmd{}), "")

    flag.Parse()
    ctx := context.Background()
    os.Exit(int(subcommands.Execute(ctx)))
}

Changes the output from:

Usage: main <flags> <subcommand> <subcommand args>

Subcommands:
        init             initialize the cli
        list             list the items
        ls               list the items

Use "main flags" for a list of top-level flags
exit status 2

to:

Usage: main <flags> <subcommand> <subcommand args>

Subcommands:
        init             initialize the cli
        list, ls         list the items

Use "main flags" for a list of top-level flags
exit status 2