aboutsummaryrefslogtreecommitdiffstats
path: root/subcmd.go
blob: 56f778b194edb207cb4b6653f9df4a8e41df7bdf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// Package subcmd provides a simple subcommand framework built on top of
// the standard library's flag package.
package subcmd

import (
	"context"
	"flag"
	"fmt"
	"io"
	"os"
	"os/exec"
	"sort"
	"strings"
)

// ExitStatus represents the exit status of a command.
type ExitStatus int

const (
	// ExitSuccess indicates the command completed successfully.
	ExitSuccess ExitStatus = 0
	// ExitFailure indicates the command failed.
	ExitFailure ExitStatus = 1
)

// Command is the interface that must be implemented by all subcommands.
type Command interface {
	// Name returns the name of the command.
	Name() string

	// Synopsis returns a short one-line description of the command.
	Synopsis() string

	// Usage returns a detailed usage message for the command.
	Usage() string

	// SetFlags sets up command-specific flags on the provided FlagSet.
	SetFlags(f *flag.FlagSet)

	// Execute runs the command with the given context, FlagSet, and optional arguments.
	Execute(ctx context.Context, f *flag.FlagSet, args ...any) ExitStatus
}

// commandGroup holds a command and its associated group.
type commandGroup struct {
	cmd   Command
	group string
}

// Registry manages subcommand registration and execution.
type Registry struct {
	commands map[string]*commandGroup
	output   io.Writer
}

// NewRegistry creates a new command registry.
func NewRegistry() *Registry {
	return &Registry{
		commands: make(map[string]*commandGroup),
		output:   os.Stdout,
	}
}

// SetOutput sets the output writer for the registry.
func (r *Registry) SetOutput(w io.Writer) {
	r.output = w
}

// Register registers a command with an optional group name.
// If a command with the same name already exists, it will be overwritten.
func (r *Registry) Register(cmd Command, group string) {
	r.commands[cmd.Name()] = &commandGroup{
		cmd:   cmd,
		group: group,
	}
}

// Execute executes the subcommand specified in os.Args.
// It expects flag.Parse() to have been called already.
func (r *Registry) Execute(ctx context.Context, args ...any) ExitStatus {
	if flag.NArg() < 1 {
		r.printUsage()
		return ExitFailure
	}

	cmdName := flag.Arg(0)
	cg, ok := r.commands[cmdName]
	if !ok {
		fmt.Fprintf(r.output, "Unknown subcommand: %s\n", cmdName)
		return ExitFailure
	}

	fs := flag.NewFlagSet(cmdName, flag.ExitOnError)
	cg.cmd.SetFlags(fs)
	if err := fs.Parse(flag.Args()[1:]); err != nil {
		return ExitFailure
	}

	return cg.cmd.Execute(ctx, fs, args...)
}

// printUsage prints usage information when no subcommand is specified.
func (r *Registry) printUsage() {
	progName := "program"
	if len(os.Args) > 0 {
		progName = os.Args[0]
	}
	fmt.Fprintf(r.output, "Usage: %s <flags> <subcommand> <subcommand args>\n\n", progName)

	fmt.Fprintf(r.output, "Subcommands:\n")
	names := make([]string, 0, len(r.commands))
	for name := range r.commands {
		names = append(names, name)
	}
	sort.Strings(names)
	for _, name := range names {
		cmd := r.commands[name].cmd
		fmt.Fprintf(r.output, "\t%-16s %s\n", name, cmd.Synopsis())
	}
}

// Commands returns all registered commands grouped by their group name.
func (r *Registry) Commands() map[string][]Command {
	result := make(map[string][]Command)

	for _, cg := range r.commands {
		result[cg.group] = append(result[cg.group], cg.cmd)
	}

	// Sort commands within each group by name
	for group := range result {
		sort.Slice(result[group], func(i, j int) bool {
			return result[group][i].Name() < result[group][j].Name()
		})
	}

	return result
}

// Command returns the command with the given name, or nil if not found.
func (r *Registry) Command(name string) Command {
	if cg, ok := r.commands[name]; ok {
		return cg.cmd
	}
	return nil
}

// Default registry used by package-level functions
var defaultRegistry = NewRegistry()

// Register registers a command with the default registry.
func Register(cmd Command, group string) {
	defaultRegistry.Register(cmd, group)
}

// Execute executes a subcommand using the default registry.
func Execute(ctx context.Context, args ...any) ExitStatus {
	return defaultRegistry.Execute(ctx, args...)
}

// SetOutput sets the output writer for the default registry.
func SetOutput(w io.Writer) {
	defaultRegistry.SetOutput(w)
}

// Commands returns all registered commands from the default registry.
func Commands() map[string][]Command {
	return defaultRegistry.Commands()
}

// helpCommand implements the built-in help command.
type helpCommand struct {
	registry *Registry
}

// HelpCommand returns a command that prints help information.
func HelpCommand() Command {
	return &helpCommand{registry: defaultRegistry}
}

func (h *helpCommand) Name() string     { return "help" }
func (h *helpCommand) Synopsis() string { return "describe subcommands and their syntax" }
func (h *helpCommand) Usage() string {
	return `help [<subcommand>]:
	With an argument, prints detailed information about the specified subcommand.
	Without arguments, prints a list of all available subcommands.
`
}

func (h *helpCommand) SetFlags(f *flag.FlagSet) {}

func (h *helpCommand) Execute(ctx context.Context, f *flag.FlagSet, args ...any) ExitStatus {
	// If a specific command is requested, show its detailed help
	if f.NArg() > 0 {
		cmdName := f.Arg(0)
		cmd := h.registry.Command(cmdName)
		if cmd == nil {
			fmt.Fprintf(h.registry.output, "Unknown command: %s\n", cmdName)
			return ExitFailure
		}

		fmt.Fprintf(h.registry.output, "%s\n", cmd.Usage())
		return ExitSuccess
	}

	// Otherwise, show all commands grouped by group
	fmt.Fprintf(h.registry.output, "Available commands:\n\n")

	grouped := h.registry.Commands()

	// Sort group names for consistent output
	groups := make([]string, 0, len(grouped))
	for group := range grouped {
		groups = append(groups, group)
	}
	sort.Strings(groups)

	for _, group := range groups {
		if group != "" {
			fmt.Fprintf(h.registry.output, "%s:\n", group)
		}

		for _, cmd := range grouped[group] {
			// Format: "  name    synopsis"
			fmt.Fprintf(h.registry.output, "  %-12s %s\n", cmd.Name(), cmd.Synopsis())
		}

		fmt.Fprintf(h.registry.output, "\n")
	}

	fmt.Fprintf(h.registry.output, "Use 'help <subcommand>' for more information about a command.\n")
	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
}

// CommandsCommand returns a command that lists all available commands.
func CommandsCommand() Command {
	return &commandsCommand{registry: defaultRegistry}
}

func (c *commandsCommand) Name() string     { return "commands" }
func (c *commandsCommand) Synopsis() string { return "list all command names" }
func (c *commandsCommand) Usage() string {
	return `commands:
	List all available command names, one per line.
`
}

func (c *commandsCommand) SetFlags(f *flag.FlagSet) {}

func (c *commandsCommand) Execute(ctx context.Context, f *flag.FlagSet, args ...any) ExitStatus {
	// Get all command names and sort them
	names := make([]string, 0, len(c.registry.commands))
	for name := range c.registry.commands {
		names = append(names, name)
	}
	sort.Strings(names)

	for _, name := range names {
		fmt.Fprintf(c.registry.output, "%s\n", name)
	}

	return ExitSuccess
}

// flagsCommand implements the built-in flags command.
type flagsCommand struct {
	registry *Registry
}

// FlagsCommand returns a command that lists global flags.
func FlagsCommand() Command {
	return &flagsCommand{registry: defaultRegistry}
}

func (f *flagsCommand) Name() string     { return "flags" }
func (f *flagsCommand) Synopsis() string { return "describe all known top-level flags" }
func (f *flagsCommand) Usage() string {
	return `flags:
	List all top-level flags with their descriptions.
`
}

func (f *flagsCommand) SetFlags(fs *flag.FlagSet) {}

func (f *flagsCommand) Execute(ctx context.Context, fs *flag.FlagSet, args ...any) ExitStatus {
	var b strings.Builder
	flag.CommandLine.VisitAll(func(f *flag.Flag) {
		fmt.Fprintf(&b, "  -%s", f.Name)
		if f.DefValue != "" {
			fmt.Fprintf(&b, " (default: %s)", f.DefValue)
		}
		fmt.Fprintf(&b, "\n      %s\n", f.Usage)
	})

	if b.Len() == 0 {
		fmt.Fprintf(f.registry.output, "No top-level flags defined.\n")
	} else {
		fmt.Fprintf(f.registry.output, "Top-level flags:\n%s", b.String())
	}

	return ExitSuccess
}