Skip to content

Commit

Permalink
Document suggested layout for subcommands (#1930)
Browse files Browse the repository at this point in the history
Signed-off-by: Luiz Carvalho <lucarval@redhat.com>
  • Loading branch information
lcarva authored Mar 17, 2023
1 parent b197a24 commit c8a20a1
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions user_guide.md
Original file line number Diff line number Diff line change
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 structure:

```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 c8a20a1

Please sign in to comment.