Skip to content

Commit db42183

Browse files
authored
feat: allow explicitly set path with default to an empty string to clear it (#592)
1 parent a2df5f5 commit db42183

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

mapper.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -584,6 +584,7 @@ func pathMapper(r *Registry) MapperFunc {
584584
if target.Kind() == reflect.Slice {
585585
return sliceDecoder(r)(ctx, target)
586586
}
587+
originalTarget := target
587588
if target.Kind() == reflect.Ptr && target.Elem().Kind() == reflect.String {
588589
if target.IsNil() {
589590
return nil
@@ -598,6 +599,13 @@ func pathMapper(r *Registry) MapperFunc {
598599
if err != nil {
599600
return err
600601
}
602+
// Skip if path with default is explicitly set to "". For the current directory use ".".
603+
if ctx.Value.HasDefault && path == "" {
604+
if originalTarget.Kind() == reflect.Ptr {
605+
originalTarget.Set(reflect.Zero(originalTarget.Type()))
606+
}
607+
return nil
608+
}
601609
if path != "-" {
602610
path = ExpandPath(path)
603611
}

mapper_test.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -555,6 +555,42 @@ func TestPathMapperUsingStringPointer(t *testing.T) {
555555
})
556556
}
557557

558+
func TestPathMapperWithDefaultUsingStringPointer(t *testing.T) {
559+
type CLI struct {
560+
Path *string `type:"path" default:"foobar"`
561+
}
562+
var cli CLI
563+
564+
t.Run("With value", func(t *testing.T) {
565+
pwd, err := os.Getwd()
566+
assert.NoError(t, err)
567+
p := mustNew(t, &cli)
568+
_, err = p.Parse([]string{"--path", "."})
569+
assert.NoError(t, err)
570+
assert.NotZero(t, cli.Path)
571+
assert.Equal(t, pwd, *cli.Path)
572+
})
573+
574+
t.Run("Zero value", func(t *testing.T) {
575+
p := mustNew(t, &cli)
576+
_, err := p.Parse([]string{"--path", ""})
577+
assert.NoError(t, err)
578+
assert.Equal(t, nil, cli.Path)
579+
})
580+
581+
t.Run("Without value", func(t *testing.T) {
582+
pwd, err := os.Getwd()
583+
assert.NoError(t, err)
584+
pwd = filepath.Join(pwd, "foobar")
585+
pwd, err = filepath.Abs(pwd)
586+
assert.NoError(t, err)
587+
p := mustNew(t, &cli)
588+
_, err = p.Parse([]string{"--"})
589+
assert.NoError(t, err)
590+
assert.Equal(t, pwd, *cli.Path)
591+
})
592+
}
593+
558594
//nolint:dupl
559595
func TestExistingFileMapper(t *testing.T) {
560596
type CLI struct {

0 commit comments

Comments
 (0)