diff options
| author | Eugene Triguba <hello@eugenetriguba.com> | 2025-12-27 05:38:06 -0500 |
|---|---|---|
| committer | Eugene Triguba <hello@eugenetriguba.com> | 2025-12-27 05:38:06 -0500 |
| commit | 6b5ccdf15ac799bc190084d69ded8e38f1e79cb9 (patch) | |
| tree | bfc05e627950ee3d7dbfd847d6c4349a78535bcf /subcmd.go | |
| parent | Refactor tests to reduce duplication (diff) | |
| download | subcmd-6b5ccdf15ac799bc190084d69ded8e38f1e79cb9.zip | |
Add ManHelpCommand to delegate 'help' to opening man pages
Diffstat (limited to 'subcmd.go')
| -rw-r--r-- | subcmd.go | 44 |
1 files changed, 44 insertions, 0 deletions
@@ -8,6 +8,7 @@ import ( "fmt" "io" "os" + "os/exec" "sort" "strings" ) @@ -231,6 +232,49 @@ func (h *helpCommand) Execute(ctx context.Context, f *flag.FlagSet, args ...any) return ExitSuccess } +// manHelpCommand implements a help command that opens man pages. +type manHelpCommand struct { + prefix string +} + +// ManHelpCommand returns a help command that opens man pages. +// +// The prefix is used to construct man page names: "prefix" for +// the main page, "prefix-subcommand" for subcommand pages. This +// is a common convention e.g. git(1), git-commit(1), ... +func ManHelpCommand(prefix string) Command { + return &manHelpCommand{prefix: prefix} +} + +func (m *manHelpCommand) Name() string { return "help" } +func (m *manHelpCommand) Synopsis() string { return "show manual page" } +func (m *manHelpCommand) Usage() string { + return "help [<subcommand>]\n\nOpen the manual page for a subcommand.\n" +} +func (m *manHelpCommand) SetFlags(f *flag.FlagSet) {} +func (m *manHelpCommand) Execute(ctx context.Context, f *flag.FlagSet, args ...any) ExitStatus { + page := m.prefix + if f.NArg() > 0 { + for _, arg := range f.Args() { + page = page + "-" + arg + } + } + + cmd := execCommand("man", page) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { + return ExitFailure + } + return ExitSuccess +} + +// execCommand is a thin wrapper around exec.Command to ease testing. +var execCommand = func(name string, args ...string) *exec.Cmd { + return exec.Command(name, args...) +} + // commandsCommand implements the built-in commands listing command. type commandsCommand struct { registry *Registry |