Commit c8a20a1 1 parent b197a24 commit c8a20a1 Copy full SHA for c8a20a1
File tree 1 file changed +31
-0
lines changed
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{
188
188
}
189
189
```
190
190
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
+
191
222
### Returning and handling errors
192
223
193
224
If 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