github.com/toolvox/utilgo@v0.0.5/pkg/cli/cmds/flag_set.go (about)

     1  package cmds
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/toolvox/utilgo/pkg/cli/lexer"
     8  	"github.com/toolvox/utilgo/pkg/errs"
     9  	"github.com/toolvox/utilgo/pkg/sliceutil"
    10  )
    11  
    12  // FlagSet is a collection of [Flag]s.
    13  type FlagSet []Flag
    14  
    15  // Flag adds configured [Flag] to the set.
    16  func (fs *FlagSet) Flag(flag Flag) FlagValue {
    17  	*fs = append(*fs, flag)
    18  	return flag
    19  }
    20  
    21  // Var creates a new [Flag] and adds it to the set.
    22  func (fs *FlagSet) Var(value FlagValue, name string, usage string) FlagValue {
    23  	flag := NewFlag(value, name, usage)
    24  	*fs = append(*fs, flag)
    25  	return flag
    26  }
    27  
    28  // BoolFlags returns the name of all the [Flag](s) which are boolean flags.
    29  func (fs *FlagSet) BoolFlags() []string {
    30  	return sliceutil.SelectNonZeroFunc(*fs,
    31  		func(flag Flag) string {
    32  			if boolFlag, ok := flag.(isBoolFlag); ok && boolFlag.IsBoolFlag() {
    33  				return flag.FlagName()
    34  			}
    35  			return ""
    36  		},
    37  	)
    38  }
    39  
    40  // Parse parses the [Flag]s and actions in the [FlagSet], leaving the actions in [pkg/os.Args].
    41  func (fs FlagSet) Parse(args []string) error {
    42  	lex := lexer.NewFlagTokenizer(fs.BoolFlags()...)
    43  	lex.TokenizeFlags(args)
    44  
    45  	var errors errs.Errors
    46  	for _, flag := range fs {
    47  		if value, ok := lex.Tokenized[flag.FlagName()]; ok {
    48  			if err := flag.Set(value); err != nil {
    49  				errors.WithErrorf("flag '%s' set, error: %w", flag.FlagName(), err)
    50  			}
    51  		}
    52  	}
    53  
    54  	if err := errors.OrNil(); err != nil {
    55  		return fmt.Errorf("flags for command: %w", err)
    56  	}
    57  
    58  	os.Args = lex.Actions
    59  	return nil
    60  }