fix: slices/maps of existingfile would fail to work

This commit is contained in:
Alec Thomas
2024-03-08 17:20:45 +11:00
parent 8e675d6130
commit a41b2e8f4e
2 changed files with 17 additions and 3 deletions
+3 -3
View File
@@ -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)
}
@@ -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).
@@ -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).
+14
View File
@@ -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"`