Skip to content
Myr

Document suggested layout for subcommands (#1930)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Luiz Carvalho · committed by GitHub · parent b197a24 · Browse files · 1 file+31 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Signed-off-by: Luiz Carvalho <lucarval@redhat.com>

Diff stats

1 file+31 added−0 removed

  • other:+31 added−0 removed

1 file+31 added−0 removed

modified:user_guide.md+31 added
186 unmodified lines
187 },188}189```190191### Organizing subcommands192193A command may have subcommands which in turn may have other subcommands. This is achieved by using194`AddCommand`. In some cases, especially in larger applications, each subcommand may be defined in195its own go package.196197The suggested approach is for the parent command to use `AddCommand` to add its most immediate198subcommands. For example, consider the following directory structure:199200```text201├── cmd202│   ├── root.go203│   └── sub1204│   ├── sub1.go205│   └── sub2206│   ├── leafA.go207│   ├── leafB.go208│   └── sub2.go209└── main.go210```211212In this case:213214* The `init` function of `root.go` adds the command defined in `sub1.go` to the root command.215* The `init` function of `sub1.go` adds the command defined in `sub2.go` to the sub1 command.216* The `init` function of `sub2.go` adds the commands defined in `leafA.go` and `leafB.go` to the217 sub2 command.218219This approach ensures the subcommands are always included at compile time while avoiding cyclic220references.221222### Returning and handling errors223224If you wish to return an error to the caller of a command, `RunE` can be used.225
501 unmodified lines