File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff 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 structured:
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
193224If you wish to return an error to the caller of a command, ` RunE ` can be used.
You can’t perform that action at this time.
0 commit comments