Go Subcommand (gosubc) is a command-line code generation tool that creates subcommand code for command-line interfaces (CLIs) in Go from source code comments. It is designed to be installed and run as a standalone executable during your build process (e.g., via go generate), not imported as a library dependency in your Go code.
By leveraging specially formatted code comments, it automatically generates a dependency-less subcommand system, allowing you to focus on your application's core logic instead of boilerplate code.
Status: Pre-v1. The API and generated code structure may change.
- Convention over Configuration: Define your CLI structure with simple, intuitive code comments.
- Zero Dependencies: The generated code is self-contained and doesn't require any external libraries.
- Automatic Code Generation:
gosubcparses your Go files and generates a complete, ready-to-use CLI. - Parameter Auto-Mapping: Automatically maps CLI flags, positional arguments, and variadic arguments to function parameters.
- Rich Syntax Support: Supports custom flag names, default values, and description overrides via comments.
- Man Page Generation: Automatically generate Unix man pages for your CLI.
To install gosubc, use go install:
go install github.com/arran4/go-subcommand/cmd/gosubc@latestCreate a Go file and define a function that will serve as your command. Add a comment above the function in the format // FunctionName is a subcommand 'root-command sub-command...'.
Example main.go:
package main
import "fmt"
// PrintHelloWorld is a subcommand `my-app hello`
// This command prints "Hello, World!" to the console.
func PrintHelloWorld() {
fmt.Println("Hello, World!")
}Create a file named generate.go in the same directory (package main). This robust version checks if gosubc is installed; if not, it uses go run to fetch and run it. This ensures it works for everyone without manual installation steps.
package main
//go:generate sh -c "command -v gosubc >/dev/null 2>&1 && gosubc generate || go run github.com/arran4/go-subcommand/cmd/gosubc generate"Run go generate in your terminal:
go generateThis will create a cmd/my-app directory containing the generated CLI code.
You can now run your newly generated CLI:
go run ./cmd/my-app helloOutput:
Hello, World!
go-subcommand uses a specific comment syntax to configure your CLI.
The primary directive defines where the command lives in the CLI hierarchy:
// FuncName is a subcommand `root-cmd parent child`go-subcommand provides expressive alias and routing capabilities across child commands, nested hierarchies, and the application root.
You can define aliases for a subcommand using the Aliases: or Alias: directive, or inline (alias: ...) / (aka: ...):
// SvcAction is a subcommand `app svc` Manage services.
// Aliases: service, s
func SvcAction() error { ... }
// SvcListAction is a subcommand `app svc list` List active services.
// (aka: ls)
func SvcListAction(all bool) error { ... }Aliases resolve at intermediate and leaf positions across execution and help traversal:
$ app svc list --all
$ app service ls --all
$ app s ls --all
$ app help s lsAn application root action can be made reachable through both bare invocation and an explicit nested command path several levels deep without duplicating the action implementation:
// RunProg is a subcommand `prog` Root application action.
// Aliases: tools docs simple, tools docs s
//
// Flags:
// config: --config (default: "default.cfg") Configuration path
func RunProg(config string) error { ... }
// ToolsAction is a subcommand `prog tools` Developer tools.
// Aliases: t
func ToolsAction() error { ... }
// DocsAction is a subcommand `prog tools docs` Documentation tools.
// Aliases: d
func DocsAction() error { ... }Both bare invocation and the canonical or aliased nested path select the exact same underlying action:
$ prog --config custom.cfg
# Executes RunProg(config="custom.cfg")
$ prog tools docs simple --config custom.cfg
# Executes RunProg(config="custom.cfg")
$ prog t d s --config custom.cfg
# Executes RunProg(config="custom.cfg")
$ prog help tools docs simple
# Displays help for the nested path without executing RunProg or providersA bare invocation can be explicitly configured to forward to an existing help route using the Default route: directive (or inline (default route: ...)):
// SimpleAction is a subcommand `prog simple` Simple demonstration command.
// Default route: help simple
//
// Flags:
// name: -n --name (default: "world") Target name
func SimpleAction(name string) error { ... }
// OtherAction is a subcommand `prog other` Other command.
func OtherAction() error { ... }In this configuration, bare invocation and ./prog help simple produce identical output and exit status 0, while guaranteeing zero business action or provider execution:
$ prog
Usage: prog simple [flags...]
Simple demonstration command.
Flags:
-n, --name string (default: "world") Target name
$ prog help simple
Usage: prog simple [flags...]
Simple demonstration command.
Flags:
-n, --name string (default: "world") Target name
$ prog help
Usage: prog <subcommand>
Subcommands:
other Other command.
simple Simple demonstration command.Built-in commands (help, usage, version) remain side-effect-free and reserved, distinct from user actions.
An application root and an ordinary subcommand literally named root can coexist cleanly:
// Downloadsd is a subcommand `downloadsd` Manage downloads and services.
func Downloadsd(config string) error { ... }
// Root is a subcommand `downloadsd root` Run the optional privileged supervisor.
// (aka: supervisor, r)
func Root(config string, serve bool) error { ... }downloadsd: Executes the application-levelDownloadsdaction.downloadsd root(ordownloadsd supervisor,downloadsd r): Dispatches only to the explicit supervisorRootaction.downloadsd helpordownloadsd -h: Shows application help without starting the supervisor or executing actions.downloadsd root --helpordownloadsd help root: Shows supervisor child help.
- Short Description: The text immediately following the subcommand definition (or prefixed with
thator--) becomes the short description used in usage lists. - Extended Help: Any subsequent lines that do not look like parameter definitions are treated as extended help text, displayed when the user requests help for that specific command.
// MyFunc is a subcommand `app cmd` -- Does something cool
//
// This is the extended help text. It can span multiple lines
// and provide detailed usage examples or explanations.Function parameters are automatically mapped to CLI flags. You can customize them using comments. go-subcommand looks for configuration in three places, in this priority order (highest to lowest):
Flags:Block: A dedicated block in the main function documentation.- Inline Comments: Comments on the same line as the parameter definition.
- Preceding Comments: Comments on the line immediately before the parameter.
This is the cleanest way to define multiple parameters. It must be an indented block following a line containing just Flags:.
// MyFunc is a subcommand `app cmd`
//
// Flags:
//
// username: --username -u (default: "guest") The user to greet
// count: --count -c (default: 1) Number of times
func MyFunc(username string, count int) { ... }Inside a Flags: block or inline/preceding comments, you can use the following syntax tokens to configure a parameter:
- Flags:
-f,--flag. One or more flag aliases. - Default Value:
default: valueordefault: "value". - Required:
required. Marks a flag as required; generated execution returns an error if it is omitted. - Optional:
optional. Explicitly marks a positional argument as optional (e.g.@1 (optional)), allowing bare invocation to pass zero-values without requiring default-value annotations. - From Parent:
from parent. Maps a child parameter to a flag declared on an ancestor command. - Custom Parser:
parser: Funcorparser: "import/path".Func. Uses a custom string parser for the parameter. - Generator:
generator: Funcorgenerator: "import/path".Func. Populates the parameter from code instead of exposing it as a CLI flag. Providers may name parameter dependencies, for examplegenerator: BuildClient(endpoint, token). Dependencies are bound first, providers run once per command execution in deterministic dependency order, and unknown dependencies or cycles fail generation with diagnostics. - Positional Argument:
@N(e.g.,@1,@2). Maps the Nth positional argument (1-based) to this parameter. - Variadic Arguments:
min...max(e.g.,1...3) or.... Maps remaining arguments to a slice. - Description: Any remaining text is treated as the parameter description.
Multiple parenthesized attributes can be combined with semicolons, for example (required; parser: ParseThing).
(optional value) is an explicit flag contract supporting ordinary Go
primitive types, pointers and slices. It distinguishes flag presence from value
assignment:
| Type | Omitted | Bare flag | Explicit value |
|---|---|---|---|
T |
Zero / default | Best-effort bare/default value | Parsed T |
*T |
nil | Pointer to bare/default value | Pointer to parsed T |
**T |
nil | Pointer to nil (*p == nil) |
Pointer to pointer to parsed T |
[]T |
Empty/nil | Append bare/default value | Append parsed T |
[]*T |
Empty/nil | Append nil | Append pointer to parsed T |
- For scalar
T, omission, a bare flag, and an explicit zero value merge into the same Go value. - For
*T, omission evaluates tonil, while a bare flag points to the bare/default value. - For
**T, all three states are distinguishable for a single occurrence:nil(omitted), non-nil pointing tonil(bare), and non-nil pointing to*T(explicit value). - For
[]*T, each occurrence is preserved losslessly: an omitted flag produces an empty/nil slice,--flagappendsnil, and--flag=valueappends&value(including&""for--flag=). - Scalar and single-pointer flags follow conventional last-occurrence-wins; slices accumulate in order.
For the GNU parser, --name supplies the bare flag; --name=value supplies an
explicit value; and --name= supplies an explicit empty string. Short forms
-n, -nvalue, -n=value, and -n= are also supported. A following positional
token is never consumed as the optional value. This keeps -- and positional
parsing unambiguous. The Go-flag backend rejects optional-value parameters
because its native callback cannot distinguish a bare flag from an explicit
boolean-looking value. Richer consumer-owned types (such as sql.NullString)
can be constructed by using a generator: provider depending on the parsed
optional flag parameter.
(optional value) applies only to named flags, not positional arguments:
an @1 positional can instead be made omittable with (optional) or (default: "."), and a
variadic ... tail can accept zero or more values. These are distinct from a
flag that accepts --name and --name=value.
(optional value) and (generator: ...) cannot populate the same
parameter: one reads argv and the other obtains its value from a function.
Generators can consume parsed optional flags as named dependencies:
// Flags:
// raw: (optional value) --raw
// dest: (generator: ToNullString(raw))
func Convert(raw []*string, dest *NullString) {}Here raw preserves omitted, bare and explicit assigned occurrences; the
consumer-owned ToNullString(raw) converts them into the dest type. A
runnable version is included in testdata/optional_value.go and the compiled
templates/testdata/runtime/issue401_optional_value.txtar scenarios.
Providers can depend on (flag presence) parameters, just like other bound
command values. Presence maps bind before any effectful provider, regardless of
parameter declaration order, and are never acquired or closed as providers.
The map describes flags consumed by that command's parser; inherited ordinary
values remain available through (from parent).
templates/testdata/runtime/issue403_presence.txtar shows complete source,
generated root/nested code and compiled GNU/Go-flag invocations. For example,
app --enabled=false -n 0 --label= passes false/zero/empty values and
seen={"count":true,"enabled":true,"label":true} to a local provider followed
by an imported dependent provider. Output records open:first, open:second,
the action, then close:second and close:first, once each. Nested commands also
exercise inherited flags and a positional provider input. Partial acquisition
failure closes only acquired resources; action errors retain precedence over
cleanup errors. Help, usage, version and a sibling without providers acquire none.
Generated files plan import identifiers for the complete file before rendering. Source import aliases and qualified default expressions are therefore preserved when possible and deterministically renamed when they collide with generated dependencies such as flag, fmt, or os.
Commands can declare shared typed providers and lifecycle initializers:
- Initializers (
Initializer: Func): Mandatory guards declared on a command node (or in functionless metadata) that run in root-to-leaf order before any selected descendant action. If an initializer returns an error, execution stops immediately and cleanups run. Initializers do not run during help, usage, or version requests. - Shared Providers (
Shared provider: name = Func): Lazy memoized typed providers hoisted to the lowest safe common ancestor or declared explicitly on an ancestor node. Descendant commands can receive the provider directly as a typed parameter (e.g.session *AdminSession) or as an opt-in lazy callable (e.g.session func() (*AdminSession, error)). When an action receives a lazy callable and never invokes it (for example in dry-run mode), the provider is never acquired. - Resource Cleanup: Providers returning
io.Closerare automatically closed in reverse acquisition order on command completion or failure. In-process reused command executions cleanly reset all memoized instances.
Declarations can be written in Go source comments:
// Admin is a command `app admin` -- Administrative commands.
// Initializer: "example.com/myapp/auth".RequireAdmin
// Shared provider: session = "example.com/myapp/session".OpenAdminSessionor in native .mdc configuration:
```command: app admin
Initializer: "example.com/myapp/auth".RequireAdmin
Shared provider: session = "example.com/myapp/session".OpenAdminSession
```Compiled runtime scenarios are verified in templates/testdata/runtime/issue522_lifecycle.txtar.
Use (root context) on a root-command parameter when the application, rather than argv or a runtime provider, owns a typed value for the command tree. The generated root stores it once and exposes NewRootWithContext; inherited child parameters use the embedded root field without redeclaring it.
Constructor context and (flag presence) are independent inputs. A root or nested
action may receive both inherited typed context and its own map[string]bool
presence parameter. Context is never an argv flag or an execution-time provider;
explicit false, zero and empty flag values still appear in the presence map.
templates/testdata/runtime/issue483_presence.txtar contains the complete annotated source,
generated root/grandchild snapshots and compiled GNU/Go-flag examples. For example,
app child grandchild --enabled=false -n 0 -l "" reports the same supplied context
and seen={"count":true,"enabled":true,"label":true}. The ordinary NewRoot
constructor supplies zero context, while NewRootWithContext accepts imported
typed context without changing flag binding. Help, usage and version execute no
actions, and a reused tree receives a fresh presence map for each invocation.
// Root is a subcommand `app`.
//
// Flags:
//
// buildInfo: (root context) Build metadata created by main
func Root(buildInfo buildinfo.BuildInfo) {}The existing NewRoot(name, version, commit, date) remains available for compatibility and supplies zero values for declared context. Applications that need the context must call the typed NewRootWithContext constructor (or use dispatcher-only generation).
The following Go types are supported for function parameters:
string: (Default)int: Parsed as an integer.bool: Parsed as a boolean flag (no value required, e.g.,--verbose).time.Duration: Parsed usingtime.ParseDuration(e.g.,10s,1h).io.Readerandio.ReadCloser:-borrows standard input; any other value is opened as an input file.io.Writerandio.WriteCloser:-borrows standard output; any other value is opened with create, truncate, and write access.- Pointers such as
*int: preserve the difference between omitted and explicitly provided zero values. - Slices such as
[]string: support repeatable flags. error: (Return value only) Your function can return anerror, which will be propagated to the CLI exit code.
For I/O parameters, the literal values stdin and stdout are ordinary file paths; only - selects a standard stream. Files opened by generated code are closed on every exit path, while borrowed standard streams are never closed. Bare *os.File parameters are rejected for implicit CLI binding because their intended access mode is ambiguous; use the appropriate reader/writer interface or configure an explicit provider.
To accept positional arguments instead of flags, use the @N syntax.
// Greet is a subcommand `app greet`
//
// Flags:
//
// name: @1 The name to greet
func Greet(name string) {
fmt.Printf("Hello, %s!\n", name)
}Usage: app greet John
To accept a variable number of arguments, use a slice parameter and mark it with ....
// ProcessFiles is a subcommand `app process`
//
// Flags:
//
// files: ... List of files to process
func ProcessFiles(files ...string) {
for _, file := range files {
fmt.Println("Processing", file)
}
}Usage: app process file1.txt file2.txt file3.txt
You can define custom short and long flags.
// Serve is a subcommand `app serve`
//
// Flags:
//
// port: -p --port (default: 8080) Port to listen on
func Serve(port int) { ... }The generated custom argument parser natively supports GNU-style single-letter short codes grouped together (e.g., -abc is parsed as -a -b -c). It also correctly handles equals assignment (e.g., -v=123 or --flag="value").
The CLI uses a custom parser generated by gosubc rather than delegating entirely to the standard flag package (which is only used to manage underlying struct bindings). This ensures deterministic and bounded behaviour out-of-the-box.
- Termination Detection: The first standalone
--token encountered halts all flag parsing and subcommand recognition for the current command. - Positional Passthrough: All tokens following
--(including subsequent--tokens, unknown flags, or subcommand names) are treated strictly as positional arguments and passed through untouched. - Command Scope: The termination is contextual to the command level where it is encountered; an
app -- subcommandpassessubcommandas an argument toapp, whileapp subcommand -- childpasseschildas an argument tosubcommand.
To enforce that a specific flag must be provided at runtime, mark the parameter with the required keyword inside parentheses (e.g., (required)). The execution will fail gracefully if a user omits the required parameter. For optional parameters, omitting the flag relies on Go zero-values unless overridden by default:.
For io.Reader and io.ReadCloser parameters, pass - to select standard
input. For io.Writer and io.WriteCloser, pass - to select standard
output. Generated usage repeats this direction-specific meaning, including for
default: -. Names such as stdin and stdout remain ordinary file paths.
Nesting is implicit based on the command path string.
// Root command: `app`
// Child: `app users`
// Grandchild: `app users create`
// CreateUser is a subcommand `app users create`
func CreateUser(...) { ... }
// ListUsers is a subcommand `app users list`
func ListUsers(...) { ... }Each generated command owns a distinct usage resource. Commands with the same
leaf name in different paths (for example, app serve and
app scenario serve) retain separate help text and usage syntax.
Subcommand and flag rows remain inline in each generated *_usage.txt template
and are formatted at runtime with hanging-indent word wrapping to the active
terminal width (COLUMNS). Recursive help displays full command paths while
shallow help displays direct child names, aligning descriptions from each
branch's displayed labels without fixed padding widths.
When an application defines both a root action and subcommands, a recognized
subcommand (including the built-in version, help, and usage commands, or
an explicitly named child command such as app root) is dispatched without
running the application root action. Application-root identity (RootCmd and
NewRoot in root.go) is distinct from command-path subcommands, so an
explicit app root child retains its own generated struct, constructor,
usage resource, and tests without colliding with the application root.
Built-in help and usage commands also traverse nested subcommand paths
(for example, app help services list) without invoking business actions or
initializing generator-backed providers. Help flags (-h, --help) provided
after positional arguments (for example, app extract https://example.com --help)
are recognized and display command usage immediately without executing the action
or evaluating providers. Furthermore, leaf commands do not advertise fictitious
child subcommands, accurately listing supported flags including -h, --help. Unrecognized command tokens on a
non-positional parent fail with an unknown command error rather than falling
through to the parent action. -- preserves positional-argument semantics so a
token after it is not treated as a subcommand.
An error returned by a durable command action is annotated once with the
command name (for example, app failed: ...). The generated wrapper uses %w,
so callers can still use errors.Is and errors.As with the underlying error.
The command path inside backticks determines the generated executable and its
nested command hierarchy. All of the examples below produce one
cmd/gogenmux executable, not a separate executable per function.
Example A — implicit root and implicit intermediate command.
Only the leaf commands are annotated; gogenmux and config are created
automatically as dispatch-only parents:
// Generate is a subcommand `gogenmux generate` -- Generate source.
func Generate() {}
// Inspect is a subcommand `gogenmux inspect` -- Inspect the model.
func Inspect() {}
// Show is a subcommand `gogenmux config show` -- Show configuration.
func Show() {}The generated command tree is:
gogenmux [implicit root: no action function]
├── generate [Generate()]
├── inspect [Inspect()]
└── config [implicit parent: no action function]
└── show [Show()]
Example B — explicit root with a default action and explicit intermediate command.
An annotated application-root function is not merely a structural declaration:
it becomes the default action invoked by bare gogenmux. Likewise, an
explicitly annotated config function handles bare gogenmux config.
The hierarchy still produces one executable:
// Gogenmux is a subcommand `gogenmux` -- Multiplexer tools.
func Gogenmux() {}
// Generate is a subcommand `gogenmux generate` -- Generate source.
func Generate() {}
// Config is a subcommand `gogenmux config` -- Manage configuration.
func Config() {}
// Show is a subcommand `gogenmux config show` -- Show configuration.
func Show() {}gogenmux [explicit root + default action: Gogenmux()]
├── generate [Generate()]
└── config [explicit command action: Config()]
└── show [Show()]
For Example B, invocation selects the corresponding action:
gogenmux → Gogenmux() (default/root action)
gogenmux generate → Generate() (not Gogenmux())
gogenmux config → Config() (intermediate action)
gogenmux config show → Show() (not Config() or Gogenmux())
An explicit root action is optional at definition time, but when declared
it is also the application's default action. There is currently no separate
commentv1 annotation for an explicit, metadata-only root that avoids
registering such a default action. For a dispatch-only root, use the implicit
root form in Example A rather than adding an empty root function solely to
declare the executable name. Similarly, omit the explicit config function
when that intermediate node needs no action.
Durable functions stay in their original source package; gosubc generates
the dispatch wrappers and help resources. A function specifically named
Root is not required. For related distinctions involving a literal child
command named root, see issue #513.
Syntax matters: use backticks around the entire command path:
// Show is a subcommand `gogenmux config show`A comment such as // Show is a subcommand gogenmux config show (without backticks)
is not equivalent in the current commentv1 parser; it can fall back to
the Go function name and create an unintended executable tree. See
issue #478 for
tracking of that ambiguity.
Subcommands can explicitly map a parameter to a flag declared by an ancestor command using (from parent).
// Parent is a subcommand `app parent`
//
// Flags:
//
// verbose: -v --verbose
func Parent(verbose bool) { ... }
// Child is a subcommand `app parent child`
//
// Flags:
//
// verbose: (from parent)
func Child(verbose bool) {
// verbose parameter here maps to Parent's verbose variable
}gosubc supports customizing the generated code and usage text templates using the --replace-template flag.
You can supply template overlays in three formats:
- Alias File Replacement:
--replace-template usage=path/to/myusage.gotmpl(available aliases:usage,man,cmd,root,templates). - Folder Overlay:
--replace-template path/to/templates_diroverlays a directory containing custom.gotmplfiles onto default templates. - txtar Archive Overlay:
--replace-template path/to/templates.txtaroverlays a.txtararchive containing custom template files.
Multiple overlays are applied in command-line order. Later definitions with the same template name replace earlier definitions, while unrelated named definitions from every layer remain available.
To view or export the built-in templates:
gosubc template layout: Displays the directory tree structure of built-in templates.gosubc template export [--output <dir>] [--as-txtar] [--force]: Exports all built-in templates to a directory or a single.txtararchive file. Existing template files and archives are preserved unless--forceis supplied; unrelated files in an existing directory are left untouched.
Generated CLI usage output automatically wraps parameter descriptions based on the terminal width specified by the COLUMNS environment variable (falling back to 80 columns).
To generate man pages, pass the --man-dir flag to gosubc.
gosubc generate --man-dir ./manThis will generate standard Unix man pages in the specified directory, using the descriptions and extended help text from your comments.
When upgrading from a generator version affected by #469, regenerating existing man pages will produce a one-time canonical diff that removes deterministic trailing whitespace. Commit the regenerated output from the fixed generator rather than preserving the old spaces.
Generates the Go code for your CLI.
--dir <path>: Root directory containinggo.mod. Defaults to current directory.--man-dir <path>: Directory to write man pages to.--replace-template <alias>=<file>|<dir>|<txtar>: Overlays custom templates onto built-in generation templates.--emit-go-generate=false: Do not add a nested//go:generatedirective to the generated executable. The default istruefor compatibility; use this when the project owns one canonical, pinned generation command.--regenerate-command <command>: Record the project's pinned canonical regeneration command in generatedcmd/AGENTS.md.--config <path>: Read an optional version-one project configuration (.mdconf,.mdc, or.json). Explicit command-line flags override configuration values, and configuration values override built-in defaults. Unknown keys and unsupported versions fail before generation.
Configuration is opt-in. Both candidate native extensions, .mdconf and .mdc,
accept top-level generator settings, without a # Configuration heading:
format-version: 1
cli-parser: gnu
recursive: true
emit-go-generate: false
paths:
- commands
- internal/actions
Run gosubc generate --config gosubc.mdc. Explicit --recursive=false and
--prov-version= override file values even though they supply zero/empty values.
Native keys ignore case, hyphens and underscores. version: 1 remains an alias
for format-version: 1; declaring both is an error. Supported settings are
dir, man-dir, parser-name, cli-parser, paths, recursive, force,
clean, replace-templates, project-provenance (alias project), timestamp,
emit-go-generate, prov-version, prov-commit, and prov-date.
Lists accept comma-separated strings, JSON string arrays, or Markdown list entries
after an empty list setting. Strings may be quoted; booleans accept true/false,
yes/no, and 1/0. Invalid values, duplicate or conflicting aliases, unknown keys,
and unsupported headings fail with the source filename and line number.
JSON uses lower-camel-case names and a required version field:
{
"version": 1,
"cliParser": "gnu",
"recursive": true,
"emitGoGenerate": false
}The configuration file is only read by gosubc generate --config; generated
applications do not read it at runtime. --config is also safe for pinned
generation scripts because malformed input and unknown keys are rejected.
Native files also support the command/documentation/man appendices described
below. JSON remains a generator-settings compatibility reader. min-gosubc,
typed template variables, multiple generation targets and setup questions remain
tracked in #63. Unsupported sections such as # Variables are rejected; no
placeholder template-variable API is exposed.
Programmatic callers use GenerateCLIConfiguredWithOptions(GenerateCLIOptions{...})
and set ExplicitFlags to preserve supplied options over file values. Keys may be
Go parameter names (for example emitGoGenerate) or documented flag aliases.
GenerateCLIConfiguredCommand retains its original signature and treats its
arguments as fallback values. Neither API inspects process arguments.
For commands that need presence independently of value, annotate a
map[string]bool parameter with (flag presence) in the Flags: block:
// Show is a subcommand `app show` reports explicit overrides.
//
// Flags:
//
// count: --count -n (default: 7) Item count.
// seen: (flag presence) Explicit parameters.
func Show(count int, seen map[string]bool) {
fmt.Printf("count=%d explicit=%t\n", count, seen["count"])
}app show prints count=7 explicit=false; app show --count=0 prints
count=0 explicit=true. GNU and Go-flag parsers supply a fresh map keyed by Go
parameter name, normalizing aliases and recording only flags actually consumed
on that command. Flag-looking values and arguments after -- do not mark flags.
The map is not a CLI flag and does not appear in help. It cannot be positional,
inherited, required, or combined with defaults, aliases, custom parsers or providers.
An ordinary annotated function registers an action. Functionless metadata uses
the distinct is a command declaration on a package or standalone Go comment.
Command paths must be enclosed in backticks; unquoted metadata paths are rejected.
The same declaration describes roots and child commands.
These shared actions are used in the three variants below:
// Generate is a subcommand `app generate` -- Generate jobs.
func Generate() { fmt.Println("generate") }
// Show is a subcommand `app config show` -- Show settings.
func Show() { fmt.Println("show") }With just these functions in package commands, the root is implicit:
app [implicit root: help/usage]
├── generate [Generate()]
└── config [implicit parent]
└── show [Show()]
To give that root explicit metadata, place this comment above the package line:
// App is a command `app` -- Manage jobs.
// More application help.
package commandsapp [explicit metadata: help/usage; no root action]
├── generate [Generate()]
└── config [implicit parent]
└── show [Show()]
To make bare invocation execute an action, declare a real function instead:
// RootAction is a subcommand `app` -- A real root action.
//
// Flags:
//
// name: --name (default: "root") Root label.
func RootAction(name string) { fmt.Println("root:" + name) }app [explicit root action: RootAction(name)]
├── generate [Generate()]
└── config [implicit parent]
└── show [Show()]
The default GNU backend produces these results (help is written to stderr):
| Invocation | Implicit root | Metadata-only root | Action-bearing root |
|---|---|---|---|
app |
Help, status 0 | Described help, status 0 | root:root, status 0 |
app help |
Help, status 0 | Described help, status 0 | Help, status 0 |
app unknown |
Unknown-command error, status 1 | Unknown-command error, status 1 | Unknown-command error, status 1 |
app generate |
generate, status 0 |
generate, status 0 |
generate, status 0 |
Go-flag retains its existing executable-root positional fallback; functionless
roots reject unknown commands on both backends. Built-in help, usage and version
remain available. A literal app root action (and its aliases) is a child; it is
never the application metadata declaration or an implicit default action.
One metadata declaration per canonical command is allowed across Go and config. If a real action also exists, it remains executable: a nonempty metadata short description overrides its short description, long help is appended, aliases are combined and validated, and conflicting parser/default-route declarations fail. Metadata does not create or remove the action. Root aliases still require a real action under the existing routing rules; metadata must address canonical paths.
Metadata-only roots may select an existing Default route: config show or
Default route: help config show; ordinary routing performs the dispatch.
Metadata cannot declare flags, positionals or providers without a typed Go source;
these forms fail during generation. Typed functionless root flags remain follow-up
work under #63/#522. Do not add a dummy root action to attach metadata. The legacy
is a command spelling on function comments remains ignored with a warning;
action functions use is a subcommand.
A native .mdc or .mdconf file can describe the same commands without Go comment
markers. Generator settings come first, followed by optional sections:
format-version: 1
emit-go-generate: false
# Commands
```command: app
Description: Manage jobs.
More application help.
```
```command: app config
Description: Inspect configuration.
Aliases: c
```
# Documentation
```markdown: app file=docs/overview.md
```
```text: app config
Additional configuration help.
```
# Man content
```man: app EXAMPLES
app generate
```
gosubc generate --config gosubc.mdc --man-dir man produces root and child man
pages, including man/app.1. Native and Go declarations use the same normalized
comment parser and generate identical command code and help. Description,
aliases, CLI-Parser and default-route directives keep their command-scoped meaning.
An otherwise empty metadata declaration is valid and does not imply an action.
Documentation targets must already exist as actions, declared metadata or implicit parents. Text/Markdown is appended literally to help and descriptions in man pages; it is not a scripting/template language. Man appendix section names are uppercase, with underscores for spaces; standard sections cannot be replaced. Duplicate sections/declarations and malformed or mismatched fences are errors. Use a longer opening/closing backtick fence when the body contains shorter fences.
External references resolve relative to the config file: markdown accepts
.md/.markdown, and text or man accepts .txt/.text. Quote file paths
containing spaces. Absolute/escaping paths, missing files, invalid UTF-8 and
inline-plus-file combinations are rejected. The filesystem loader constrains
external symlinks to the configuration directory. Referenced text is included
once as literal content; it cannot recursively include other files.
LoadGenerateConfigFS supports hermetic filesystem readers, and
GenerateOptions.CommandDeclarations passes normalized source blocks to
commentv1 without file I/O. Generated applications neither read the config nor
depend on go-subcommand at runtime. Parsing, validation and rendering finish
before --clean removes owned old output, so invalid metadata preserves it.
Manage generation templates.
gosubc template export [--output <path>] [--as-txtar] [--force]: Export built-in templates without replacing existing files by default. Use--forceonly to replace existing exported template files or archives.gosubc template layout: Display template structure layout.
Lists all detected subcommands.
--dir <path>: Root directory.
Validates subcommand definitions for errors or conflicts.
--dir <path>: Root directory.
Generates release configuration.
--dir <path>: Root directory containinggo.mod. Defaults to current directory.--go-releaser-github-workflow: Generate GitHub Action workflow for GoReleaser.
Generated applications expose ErrUsage and UsageError in their own cmd
package, with no go-subcommand runtime dependency. Callers can classify errors
without inspecting their messages:
var usage *cmd.UsageError
if errors.Is(err, cmd.ErrUsage) && errors.As(err, &usage) {
fmt.Printf("%s: kind=%s flag=%s\n", usage.CommandPath, usage.Kind, usage.Flag)
}UsageError.Kind distinguishes no selected command (when requested), unknown commands, unknown flags, missing flag
values, invalid supplied values, invalid positional arguments, and missing
required flags. CommandPath is the canonical command path; Flag is the
supplied name without leading dashes where applicable. Err preserves the
underlying parser cause, and Message controls presentation. Both errors.Is
and errors.As work through ordinary wrapping. Application-supplied usage errors
and explicit exit errors pass through dispatch with their wrappers intact.
Generated main.go delegates to testable helpers in process.go. Only main calls
os.Exit; rendering and status selection are separate. Status precedence is:
- An explicit
cmd.ErrExitCode, detected witherrors.As, including codes 0 and 1 and custom nonzero codes. - The typed usage category's default status 1.
- The historical unclassified-error fallback status 1.
An explicit status takes precedence even when its cause requests help. A nil
inner cause suppresses error output, including through a wrapper; a nonnil inner
cause prints Error: <cause> to stderr even when the explicit status is 0.
Ordinary help and usage keep their existing successful behaviour and do not
acquire business providers. Go-flag retains the standard library's parsing
grammar and value implementations; its adapter classifies failures at their
source and renders a parser diagnostic once.
For example, an ordinary action can return
fmt.Errorf("validation: %w", &cmd.ErrExitCode{Code: 2, Err: err}) to select status
2, while an internal error may select 3. This does not change the default fallback
or install a global policy callback. The standalone source, generated error
contract and exact invocation outputs are in
templates/testdata/issue523.go.txtar.
This supplies gogenmux's typed parser classification and wrapped explicit statuses.
The declarative no-command policy below also covers bare invocation. Removing its
custom main template still requires version/build metadata (including builtBy and propagation), version-output
customization, and its validation/internal default classification and rendering
contract. Those facilities remain separate work under #479/#503.
Add the accepted execution policy to functionless root metadata:
// App is a command `app` -- Run jobs.
// No command: error
package commandsThe equivalent native config block is:
format-version: 1
# Commands
```command: app
Description: Run jobs.
No command: error
```
Bare app and app -- now return cmd.UsageError with kind
cmd.UsageNoCommand, canonical path app, no flag and no inner cause.
The generated process prints Error: no command provided on stderr and exits 1.
errors.Is(err, cmd.ErrUsage) and errors.As work through wrapping; an explicit
cmd.ErrExitCode still overrides the status. Unknown commands retain their own
cmd.UsageUnknownCommand category.
When the declaration is absent, bare invocation keeps existing help/status 0.
This root-only policy conflicts with any real root action or Default route:,
including help routes; generation rejects those combinations. It is independent
of routing. help, usage, --help and version retain normal behavior without
business providers. A bare -- selects no command; -- run remains an unknown
command after the routing terminator. Ordinary nested actions, aliases, inherited
flags and positionals retain parser behavior. Functionless root flags still
require separate typed binding support under #63/#522.
See No-command policy and
templates/testdata/issue524.go.txtar for compiled Go/config examples and exact
stdout/stderr/status snapshots on GNU and Go-flag.
The Go version needed to run gosubc is separate from the version supported by
the generated application. Generated command packages require Go 1.16 or
newer because they use standard-library embedding and io/fs.
The generator reads the target module's go directive and adapts its output:
| Target module version | Generated compatibility form |
|---|---|
| Go 1.16–1.17 | interface{} and local loops (no slices) |
| Go 1.18–1.20 | any and local loops |
| Go 1.21+ | any and slices.Contains |
Generation fails before writing output when a target module declares Go 1.15 or older. The compatibility forms are regression-tested as generated source.
--parser-nameconfigures the source/comment parser behavior used to read your files. (Default:commentv1)--cli-parserconfigures the runtime argv parser behavior generated in your binary. (Default:gnu)- parameter
parser:specifies a custom value parser for reading your types out of flag/positional arguments.
commentv1 selects source files with Go build-constraint semantics. In
particular it excludes _test.go files and honours platform filename suffixes,
//go:build, legacy // +build, and explicit build tags. A generator invoked
through GenerateWithFS can select the intended output target with
parsers.ParseOptions:
parseOptions := &parsers.ParseOptions{
Recursive: true,
GOOS: "windows",
GOARCH: "amd64",
BuildTags: []string{"enterprise"},
}The generated command tree is valid for that selected target, not a universal mixture of mutually exclusive platform implementations. Compile or package the result using the same target values. Empty target fields retain the generator host defaults.
Set --cli-parser plus-minus or use CLI-Parser: plus-minus on a command.
This backend implements a dedicated command-scoped parser with atomic staging and validation (#464):
| Token | Meaning |
|---|---|
-a, +a |
Enable/disable short boolean a. |
-ab, +ab |
Enable/disable short booleans a and b in a cluster. |
--a, ++a |
One-character long option named a, distinct from short namespace. |
--ab, ++ab |
Long options named ab, independent of short clusters. |
-n 5, -n5, -n=5 |
Value-taking short option. |
-abn5, -abn=5 |
Short cluster with trailing attached value. |
--count=3, --count 3 |
Value-taking long option. |
++count, ++count=3 |
Explicitly configured nonboolean plus operation (#531). |
-- |
Delimiter terminating option scanning and routing; remaining tokens are literal. |
Scalar toggles are last-wins, preserve absent defaults, and track explicit
presence for both polarities and all aliases. A long boolean may take an explicit
Go boolean value such as --enabled=false. Short booleans reject = assignments.
When values resemble options, attached assignment is required (--label=--verbose).
Interspersed options after positional arguments are accepted within the same command scope
while preserving positional argument ordering (#534). Subcommand boundaries yield
unconsumed arguments to the child command. Unambiguous parent options can be supplied
before or after child commands; child-declared options shadow parent options without conflict.
Required parent flags are validated across the selected command path: supplying the flag either
before or after child dispatch satisfies the requirement, while omitting it reports typed
cmd.UsageMissingRequiredFlag from the selected leaf command without premature mutation or acquisition.
In mixed parser trees (e.g. plus-minus root with GNU or Go-flag child commands), staged parent option mutations are committed only after child option parsing, required-flag validation, and positional argument validation all succeed. Any child failure or missing child positional argument prevents parent commits and prevents parent I/O side effects.
Nonboolean plus operations have no implicit behavior and require explicit consumer configuration (#531):
(plus: reset)or(plus-bare: reset): resets to declared default.(plus-bare: zero): sets to zero value.(plus: FuncName)or(plus-bare: FuncName): calls consumer functionfunc() (T, error).(plus-value: set): standard value assignment under+/++prefix.(plus-value: FuncName): calls consumer functionfunc(string) (T, error).
Standalone ++ after -- is intentionally undefined in this release (#532).
Generated Go code remains strictly compatible with Go 1.22 (#542).
See the grammar, audit and architecture decision.
templates/testdata/runtime/issue464.txtar records source comments, complete
generated artifacts/help and exact compiled invocations, including mixed-backend
subtrees. GNU and Go-flag keep their existing grammars. Optional values (#511)
remain separate work and are not implied by this backend.
Commands using the plus-minus parser backend can opt in to receiving otherwise-unrecognized command-line arguments (such as signed numeric values -0.1, +0.1, unknown flags, or arbitrary foreign options) directly in a []string action parameter marked with (unmatched) (#550):
// Volume is a subcommand `app volume`
// CLI-Parser: plus-minus
//
// Flags:
//
// player: --player Target player.
// args: (unmatched) Unmatched arguments collected verbatim.
func Volume(player string, args []string) error {
// ...
}- Doc comment syntax variants:
(unmatched),(unmatched argv), and(unmatched-argv). - Backend requirement: Supported exclusively with
CLI-Parser: plus-minus. Non-plus-minusbackends (gnu,go-flag) are rejected at generation time with clear error diagnostics. - Model constraints: The parameter must have Go type
[]string. It cannot be combined with positional parameters (@1), variadic tails (...string),(optional value), defaults, providers, constructors, or flag aliases. At most one unmatched parameter is permitted per command. - Argv semantics:
- Known options, aliases, and recognized short clusters continue to be parsed normally.
- Unmatched arguments are passed verbatim as
[]stringwithout splitting clusters or creating synthetic flags. - Any short cluster containing an unrecognized character (e.g.
-azwherezis unknown) is not partially committed; the whole cluster is preserved inargs. - Once an unmatched argument or unknown token is encountered at a parent command, subcommand routing is frozen: subsequent arguments cannot dispatch child subcommands.
- Trailing arguments after
--are collected verbatim intoargs. - The collector parameter is internal to the action and never appears in usage,
--help, or man pages.
By default, the gnu backend is used, featuring clustered short flags (e.g., -abc is identical to -a -b -c).
You can override the backend applied either across the generator defaults, or individually by inheriting sub-commands to support mixing multiple CLI grammars. The parser backend for any given command resolves in this explicit fallback order:
- The command's explicitly declared
CLI-Parser:metadata. - The nearest explicit ancestor's declared backend.
- The generation-wide default provided by
--cli-parser. - The
gnubackend.
// Legacy is a subcommand `app legacy`
// CLI-Parser: go-flag
func Legacy() {}
// Nested override back to gnu inherits nearest explicit ancestor
// Child is a subcommand `app legacy child`
// CLI-Parser: gnu
func Child() {}Subtree Command Boundaries: A parent parsing its argv according to its own backend scopes the argv entirely per tree level. Once the parent identifies and dispatches a child subcommand, the remaining argv strictly belongs to the child's Execute scope, preventing parent-parsing bleed logic entirely without reinterpreting previously parsed flags from the caller level.
Parser Specific Constraints:
The go-flag backend integrates directly with the Go standard library flag.FlagSet, meaning it strictly ignores GNU-style clustered short options. A flag invoked as -abc evaluates specifically as the exact declared flag named abc if it exists. If abc is undeclared, it strictly returns an unknown flag error rather than being parsed as -a -b -c. It handles single dashes natively (so -in README.md is fully supported), and supports boolean toggles intuitively. Go-flag halts parsing explicitly on its first seen positional argument, exactly as defined by the flag standard library. Both -name=value and --name=value syntaxes are accepted.
All arguments preceding an explicit '--' are correctly resolved and parsed to correctly segregate positional offsets accurately across all backends natively supporting them. Unknown flags will properly log unrecognized syntax per the target backend structure. Standard -h and --help return FlagSet help behavior if undeclared, but explicitly declared h / help are treated as ordinary registered flags.
The optional plus-minus proposal is described above and tracked under #464.
The runtime CLI parser behavior can be fully swapped by overriding the defined templates via the --replace-template option, allowing fallback syntax generation while replacing only targeted parser structures. The built-in backends are mapped exactly to the paths cli-parsers/gnu.gotmpl and cli-parsers/go-flag.gotmpl. Replacing one specific parser fragment entirely leaves the other unreplaced backends completely available and selectable for command generation:
go run github.com/arran4/go-subcommand/cmd/gosubc generate --replace-template "cli-parsers/gnu.gotmpl=my_custom_parser.gotmpl"Contributions are welcome! If you find a bug or have a feature request, please open an issue on our GitHub repository.
This project is licensed under the BSD 3-Clause License. See the LICENSE file for details.