Skip to content

Commit c8a20a1

Browse files
authored
Document suggested layout for subcommands (#1930)
Signed-off-by: Luiz Carvalho <[email protected]>
1 parent b197a24 commit c8a20a1

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

user_guide.md

+31
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,37 @@ var versionCmd = &cobra.Command{
188188
}
189189
```
190190

191+
### Organizing subcommands
192+
193+
A command may have subcommands which in turn may have other subcommands. This is achieved by using
194+
`AddCommand`. In some cases, especially in larger applications, each subcommand may be defined in
195+
its own go package.
196+
197+
The suggested approach is for the parent command to use `AddCommand` to add its most immediate
198+
subcommands. For example, consider the following directory structure:
199+
200+
```text
201+
├── cmd
202+
│   ├── root.go
203+
│   └── sub1
204+
│   ├── sub1.go
205+
│   └── sub2
206+
│   ├── leafA.go
207+
│   ├── leafB.go
208+
│   └── sub2.go
209+
└── main.go
210+
```
211+
212+
In this case:
213+
214+
* 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 the
217+
sub2 command.
218+
219+
This approach ensures the subcommands are always included at compile time while avoiding cyclic
220+
references.
221+
191222
### Returning and handling errors
192223

193224
If you wish to return an error to the caller of a command, `RunE` can be used.

0 commit comments

Comments
 (0)