Skip to content

Commit 3343dff

Browse files
committed
feat: impl GetOrFunc to allow fallback code in closure
1 parent 4b0bd8d commit 3343dff

2 files changed

Lines changed: 32 additions & 1 deletion

File tree

cli.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ func Get[T any](c *Command, id string) T {
188188

189189
// GetOr looks for a parsed input value with the given id in the given Command and
190190
// converts the value to the given type T through an untested type assertion (so this
191-
// will panic if the value is found and can't be converted to type T). If the value
191+
// will panic if the value is found but can't be converted to type T). If the value
192192
// isn't found, the given fallback value will be returned. To check whether the value
193193
// is found instead of using a fallback value, see [Lookup].
194194
func GetOr[T any](c *Command, id string, fallback T) T {
@@ -198,6 +198,19 @@ func GetOr[T any](c *Command, id string, fallback T) T {
198198
return fallback
199199
}
200200

201+
// GetOrFunc is like [GetOr] in that it looks for a parsed input value with the given id
202+
// in the given Command and converts the value to the given type T through an untested
203+
// type assertion (so this will panic if the value is found but can't be converted to
204+
// type T). However, if the value isn't found, it will run the provided function fn in
205+
// order to create and return the fallback value. To check whether the value is found
206+
// instead of using a fallback, see [Lookup].
207+
func GetOrFunc[T any](c *Command, id string, fn func() T) T {
208+
if v, ok := Lookup[T](c, id); ok {
209+
return v
210+
}
211+
return fn()
212+
}
213+
201214
// ParseOrExit will parse input based on this CommandInfo. If help was requested, it
202215
// will print the help message and exit the program successfully (status code 0). If
203216
// there is any other error, it will print the error and exit the program with failure

examples_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,24 @@ func ExampleGetOr_positionlArgs() {
439439
// b: "world"
440440
}
441441

442+
func ExampleGetOrFunc() {
443+
c := cli.NewCmd("example").
444+
Opt(cli.NewOpt("a")).
445+
Opt(cli.NewOpt("b")).
446+
ParseOrExit("-a", "hello")
447+
448+
a := cli.GetOr(c, "a", "")
449+
b := cli.GetOrFunc(c, "b", func() string {
450+
return "world"
451+
})
452+
453+
fmt.Printf("a: %q\n", a)
454+
fmt.Printf("b: %q\n", b)
455+
// Output:
456+
// a: "hello"
457+
// b: "world"
458+
}
459+
442460
func ExampleLookup_positionalArgs() {
443461
c := cli.NewCmd("example").
444462
Arg(cli.NewArg("a")).

0 commit comments

Comments
 (0)