Skip to content

Commit 1a2f8e8

Browse files
committed
docs: add doc and example for CommandInfo.Arg method
1 parent bccb3d6 commit 1a2f8e8

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

builder.go

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -153,20 +153,25 @@ func (c CommandInfo) Opt(o InputInfo) CommandInfo {
153153
return c
154154
}
155155

156-
func (c CommandInfo) Arg(a InputInfo) CommandInfo {
156+
// Arg adds pa as a positional argument to this CommandInfo. This method will panic if this
157+
// command already has one or more subcommands (because positional arguments and
158+
// subcommands are mutually exclusive), or if pa has any option names set, or if pa is
159+
// required but any previously positional argument is not required (because required
160+
// positional arguments cannot come after optional ones).
161+
func (c CommandInfo) Arg(pa InputInfo) CommandInfo {
157162
if len(c.Subcmds) > 0 {
158163
panic(errMixingPosArgsAndSubcmds)
159164
}
160165
// Assert the given input is not an option.
161-
if a.isOption() {
166+
if pa.isOption() {
162167
panic(errOptAsPosArg)
163168
}
164169
// Ensure a required positional arg isn't coming after an optional one.
165-
if a.IsRequired && len(c.Args) > 0 && !c.Args[len(c.Args)-1].IsRequired {
170+
if pa.IsRequired && len(c.Args) > 0 && !c.Args[len(c.Args)-1].IsRequired {
166171
panic(errReqArgAfterOptional)
167172
}
168173

169-
c.Args = append(c.Args, a)
174+
c.Args = append(c.Args, pa)
170175
return c
171176
}
172177

examples_test.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ func ExampleNewFileParser() {
166166
Opt(cli.NewOpt("i").WithParser(cli.NewFileParser(cli.ParseInt))).
167167
Opt(cli.NewOpt("s").WithParser(cli.NewFileParser(nil)))
168168

169-
c := in.ParseOrExit(
169+
c, _ := in.Parse(
170170
"-i", "testdata/sample_int",
171171
"-s", "testdata/sample_int",
172172
)
@@ -186,6 +186,16 @@ func ExampleNewFileParser() {
186186
// parsing option 'i': open path_that_doesnt_exist: no such file or directory
187187
}
188188

189+
func ExampleCommandInfo_Arg() {
190+
c := cli.New().
191+
Arg(cli.NewArg("name")).
192+
ParseOrExit("alice")
193+
194+
fmt.Println(cli.Get[string](c, "name"))
195+
// Output:
196+
// alice
197+
}
198+
189199
func ExampleCommandInfo_ExtraHelp() {
190200
in := cli.New("example").
191201
Help("an example command").

0 commit comments

Comments
 (0)