package rags_test import ( "flag" "fmt" "os" "strconv" "strings" "edge-infra.dev/pkg/lib/cli/rags" ) // Person is a struct we want to bind to a flag as a [flag.Getter]. type Person struct { age int name string } // String implements [flag.Value] func (p *Person) String() string { if p.age == 0 || p.name == "" { return "" } return fmt.Sprintf("%s is %d years old", p.name, p.age) } // Set implements [flag.Value] func (p *Person) Set(s string) error { v := strings.Split(s, ":") age, err := strconv.Atoi(v[1]) if err != nil { return err } *p = Person{ name: v[0], age: age, } return nil } // Get implements [flag.Getter] func (p *Person) Get() any { return p } // Type implements [rags.TypedValue] and exposes the descriptor for our custom // flag value. func (p *Person) Type() string { return "person" } func Example_valueImplementation() { p := &Person{100, "tom"} rs := rags.New("example-custom-value", flag.ContinueOnError) // Equivalent to flag.FlagSet.Var(...) rs.Var(p, "person", "describe person in the format 'name:age'") rs.SetOutput(os.Stdout) rs.Usage() } func Example_valueImplementationDeclarative() { var dst Person rs := rags.New("example-custom-value-declarative", flag.ContinueOnError) rs.Add(&rags.Rag{ Name: "person", Usage: "describe person in the format 'name:age'", Value: &rags.Value[Person]{ Var: &dst, Default: Person{100, "tom"}, Parse: func(s string) (Person, error) { v := strings.Split(s, ":") age, err := strconv.Atoi(v[1]) if err != nil { return Person{}, err } return Person{name: v[0], age: age}, nil }, }, }) rs.SetOutput(os.Stdout) rs.Usage() } func Example_declarativeValue() { var dst bool rs := rags.New("example-built-in-value-declarative", flag.ContinueOnError) // Create a flag bound to a built-in value type declaratively rs.Add(&rags.Rag{ Name: "enabled", Value: &rags.Bool{Var: &dst}, }) rs.SetOutput(os.Stdout) rs.Usage() } func Example_imperativeValue() { var dst bool rs := rags.New("example-built-in-value-helpers", flag.ContinueOnError) // Create a flag bound to a built-in value type using the generic helper // function that supports all primitives supported by this package. rs.Add(&rags.Rag{ Name: "enabled", Value: rags.NewValue(&dst), }) rs.SetOutput(os.Stdout) rs.Usage() } func Example_collectionValues() { var ( targets []string platform string ) rs := rags.New("example-built-in-collection-values", flag.ContinueOnError) rs.Add( &rags.Rag{ Name: "targets", Usage: "clusters to target for operations", Value: &rags.StringSet{Var: &targets}, }, &rags.Rag{ Name: "platform", Usage: "platform for targeted clusters", Value: &rags.StringEnum{Var: &platform, Valid: []string{"gke", "aws"}}, }) rs.SetOutput(os.Stdout) rs.Usage() }