Skip to content

Commit

Permalink
fix: slices/maps of existingfile would fail to work
Browse files Browse the repository at this point in the history
  • Loading branch information
alecthomas committed Mar 8, 2024
1 parent 8e675d6 commit a41b2e8
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
6 changes: 3 additions & 3 deletions mapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,7 @@ func sliceDecoder(r *Registry) MapperFunc {
var childScanner *Scanner
if ctx.Value.Flag != nil {
t := ctx.Scan.Pop()
// If decoding a flag, we need an value.
// If decoding a flag, we need a value.
if t.IsEOL() {
return fmt.Errorf("missing value, expecting \"<arg>%c...\"", sep)
}
Expand Down Expand Up @@ -641,7 +641,7 @@ func existingFileMapper(r *Registry) MapperFunc {
return err
}

if !ctx.Value.Active || ctx.Value.Set {
if !ctx.Value.Active || (ctx.Value.Set && ctx.Value.Target.Type() == target.Type()) {
// early return to avoid checking extra files that may not exist;
// this hack only works because the value provided on the cli is
// checked before the default value is checked (if default is set).
Expand Down Expand Up @@ -677,7 +677,7 @@ func existingDirMapper(r *Registry) MapperFunc {
return err
}

if !ctx.Value.Active || ctx.Value.Set {
if !ctx.Value.Active || (ctx.Value.Set && ctx.Value.Target.Type() == target.Type()) {
// early return to avoid checking extra dirs that may not exist;
// this hack only works because the value provided on the cli is
// checked before the default value is checked (if default is set).
Expand Down
14 changes: 14 additions & 0 deletions mapper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,20 @@ func TestExistingFileMapper(t *testing.T) {
assert.Contains(t, err.Error(), "exists but is a directory")
}

func TestExistingFileMapperSlice(t *testing.T) {
type CLI struct {
Files []string `type:"existingfile"`
}
var cli CLI
p := mustNew(t, &cli)
_, err := p.Parse([]string{"--files", "testdata/file.txt", "--files", "testdata/file.txt"})
assert.NoError(t, err)
assert.NotZero(t, cli.Files)
pwd, err := os.Getwd()
assert.NoError(t, err)
assert.Equal(t, []string{filepath.Join(pwd, "testdata", "file.txt"), filepath.Join(pwd, "testdata", "file.txt")}, cli.Files)
}

func TestExistingFileMapperDefaultMissing(t *testing.T) {
type CLI struct {
File string `type:"existingfile" default:"testdata/missing.txt"`
Expand Down

0 comments on commit a41b2e8

Please sign in to comment.