Skip to content

Add capability to restrict flag values to a set of allowed values #236

@ian-howell

Description

@ian-howell

I have a use-case where I need to perform validation on flag values. In other words, I need to check that the value passed in by the user belongs to some set of valid values. I end up writing a lot of code that looks like this:

package main

import (
	"fmt"
	"os"

	flag "github.com/spf13/pflag"
)

var color string

func main() {
	addFlags()
	flag.Parse()
	if err := validateFlags(); err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v", err)
		os.Exit(1)
	}
	fmt.Printf("Selected color is %s\n", color)
}

func addFlags() {
	flag.StringVar(&color, "color", "", "The color for the example")
}

func validateFlags() error {
	validColors := []string{"red", "blue", "yellow"}
	for _, validColor := range validColors {
		if color == validColor {
			// color is valid
			return nil
		}
	}
	// if we're here, color is invalid
	return fmt.Errorf("Value '%s' is invalid for flag 'color'. Valid values "+
		"come from the set %v", color, validColors)
}

I'd like to be able to do something like the following:

	flag.StringVarRestricted(
		&color,                            // pointer to variable
		"color",                           // flag name
		"",                                // default value
		"The color for the example",       // description
		[]string{"red", "blue", "yellow"}) // Allowed values

I wouldn't mind taking a shot at implementing something like this if it sounds acceptable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions