diff --git a/choose/command.go b/choose/command.go index 92a57526d..285eb16d8 100644 --- a/choose/command.go +++ b/choose/command.go @@ -3,6 +3,7 @@ package choose import ( "errors" "fmt" + "maps" "os" "slices" "sort" @@ -33,8 +34,25 @@ func (o Options) Run() error { o.Options = strings.Split(input, o.InputDelimiter) } + // normalize options into a map + options := map[string]string{} + for _, opt := range o.Options { + if o.LabelDelimiter == "" { + options[opt] = opt + continue + } + label, value, ok := strings.Cut(opt, o.LabelDelimiter) + if !ok { + return fmt.Errorf("invalid option format: %q", opt) + } + options[label] = value + } + if o.LabelDelimiter != "" { + o.Options = slices.Collect(maps.Keys(options)) + } + if o.SelectIfOne && len(o.Options) == 1 { - fmt.Println(o.Options[0]) + fmt.Println(options[o.Options[0]]) return nil } @@ -149,7 +167,7 @@ func (o Options) Run() error { var out []string for _, item := range m.items { if item.selected { - out = append(out, item.text) + out = append(out, options[item.text]) } } tty.Println(strings.Join(out, o.OutputDelimiter)) diff --git a/choose/options.go b/choose/options.go index 4777ef0a7..0f21a4352 100644 --- a/choose/options.go +++ b/choose/options.go @@ -24,6 +24,7 @@ type Options struct { SelectIfOne bool `help:"Select the given option if there is only one" group:"Selection"` InputDelimiter string `help:"Option delimiter when reading from STDIN" default:"\n" env:"GUM_CHOOSE_INPUT_DELIMITER"` OutputDelimiter string `help:"Option delimiter when writing to STDOUT" default:"\n" env:"GUM_CHOOSE_OUTPUT_DELIMITER"` + LabelDelimiter string `help:"Allows to set a delimiter, so options can be set as label:value" default:"" env:"GUM_CHOOSE_LABEL_DELIMITER"` CursorStyle style.Styles `embed:"" prefix:"cursor." set:"defaultForeground=212" envprefix:"GUM_CHOOSE_CURSOR_"` HeaderStyle style.Styles `embed:"" prefix:"header." set:"defaultForeground=99" envprefix:"GUM_CHOOSE_HEADER_"` diff --git a/go.mod b/go.mod index dc913fdf8..9614f9379 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/charmbracelet/gum -go 1.21 +go 1.23.0 require ( github.com/Masterminds/semver/v3 v3.3.1