Skip to content

Commit 4a9fe05

Browse files
Support string pointers for path mapper (#360)
1 parent 088cd78 commit 4a9fe05

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

mapper.go

+6
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,12 @@ func pathMapper(r *Registry) MapperFunc {
580580
if target.Kind() == reflect.Slice {
581581
return sliceDecoder(r)(ctx, target)
582582
}
583+
if target.Kind() == reflect.Ptr && target.Elem().Kind() == reflect.String {
584+
if target.IsNil() {
585+
return nil
586+
}
587+
target = target.Elem()
588+
}
583589
if target.Kind() != reflect.String {
584590
return fmt.Errorf("\"path\" type must be applied to a string not %s", target.Type())
585591
}

mapper_test.go

+43
Original file line numberDiff line numberDiff line change
@@ -487,6 +487,49 @@ func TestFileContentMapper(t *testing.T) {
487487
assert.Contains(t, err.Error(), "is a directory")
488488
}
489489

490+
func TestPathMapperUsingStringPointer(t *testing.T) {
491+
type CLI struct {
492+
Path *string `type:"path"`
493+
}
494+
var cli CLI
495+
496+
t.Run("With value", func(t *testing.T) {
497+
p := mustNew(t, &cli)
498+
_, err := p.Parse([]string{"--path", "/foo/bar"})
499+
assert.NoError(t, err)
500+
assert.NotZero(t, cli.Path)
501+
assert.Equal(t, "/foo/bar", *cli.Path)
502+
})
503+
504+
t.Run("Zero value", func(t *testing.T) {
505+
p := mustNew(t, &cli)
506+
_, err := p.Parse([]string{"--path", ""})
507+
assert.NoError(t, err)
508+
assert.NotZero(t, cli.Path)
509+
wd, err := os.Getwd()
510+
assert.NoError(t, err)
511+
assert.Equal(t, wd, *cli.Path)
512+
})
513+
514+
t.Run("Without value", func(t *testing.T) {
515+
p := mustNew(t, &cli)
516+
_, err := p.Parse([]string{"--"})
517+
assert.NoError(t, err)
518+
assert.Equal(t, nil, cli.Path)
519+
})
520+
521+
t.Run("Non-string pointer", func(t *testing.T) {
522+
type CLI struct {
523+
Path *any `type:"path"`
524+
}
525+
var cli CLI
526+
p := mustNew(t, &cli)
527+
_, err := p.Parse([]string{"--path", ""})
528+
assert.Error(t, err)
529+
assert.Contains(t, err.Error(), `"path" type must be applied to a string`)
530+
})
531+
}
532+
490533
//nolint:dupl
491534
func TestExistingFileMapper(t *testing.T) {
492535
type CLI struct {

0 commit comments

Comments
 (0)