urfave / cli

A simple, fast, and fun package for building command line apps in Go
https://cli.urfave.org
MIT License
21.9k stars 1.69k forks source link

[v3] `Validator` seems to always receive the empty string #1840

Closed zx8 closed 6 months ago

zx8 commented 6 months ago

Info:

Code

package main

import (
  "context"
  "fmt"
  "log"
  "os"
  "slices"

  "github.com/urfave/cli/v3"
)

func main() {
  cmd := &cli.Command{
    Name: "example",
    Flags: []cli.Flag{
      &cli.StringFlag{
        Name: "foo",
        Validator: func(s string) error {
          allowed := []string{"a", "b", "c"}
          if slices.Contains(allowed, s) {
            return nil
          }
          return fmt.Errorf("foo must be one of %s, not [%s]", allowed, s)
        },
      },
    },
  }

  if err := cmd.Run(context.Background(), os.Args); err != nil {
    log.Fatal(err)
  }
}

Expected

$ go run . --foo=a
<no error>

Actual

$ go run . --foo=a
foo must be one of [a b c], not []
dearchap commented 6 months ago

@zx8 I see the issue. It is trying to validate the "default" value which in your case is "" since nothing is set. Can you set StringFlag.Value to "a"(say) and see what happens ?

zx8 commented 6 months ago

@dearchap You are correct. It seems to be validating the default rather than the supplied value.

dearchap commented 6 months ago

No it valids default value and if that succeeds then does the supplied value.

zx8 commented 6 months ago

Aha, ok. I'll add the default to the validator then! Thanks.