Skip to content

Commit

Permalink
Document suggested layout for subcommands
Browse files Browse the repository at this point in the history
Signed-off-by: Luiz Carvalho <lucarval@redhat.com>
  • Loading branch information
lcarva committed Mar 10, 2023
1 parent 9e6b58a commit f0f52ec
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions user_guide.md
Expand Up @@ -188,6 +188,37 @@ var versionCmd = &cobra.Command{
}
```

### Organizing subcommands

A command may have subcommands which in turn may have other subcommands. This is achieved by using
`AddCommand`. In some cases, especially in larger applications, each subcommand may be defined in
its own go package.

The suggested approach is for the parent command to use `AddCommand` to add its most immediate
subcommands. For example, consider the following directory structured:

```text
├── cmd
│   ├── root.go
│   └── sub1
│   ├── sub1.go
│   └── sub2
│   ├── leafA.go
│   ├── leafB.go
│   └── sub2.go
└── main.go
```

In this case:

* The `init` function of `root.go` adds the command defined in `sub1.go` to the root command.
* The `init` function of `sub1.go` adds the command defined in `sub2.go` to the sub1 command.
* The `init` function of `sub2.go` adds the commands defined in `leafA.go` and `leafB.go` to the
sub2 command.

This approach ensures the subcommands are always included at compile time while avoiding cyclic
references.

### Returning and handling errors

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

0 comments on commit f0f52ec

Please sign in to comment.