feat(choose): label delimiters (#783)

I'm not sure if I like this impl, but it does work.

closes #406
This commit is contained in:
Carlos Alexandro Becker 2024-12-17 09:47:31 -03:00 committed by GitHub
commit 2e321f57e2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 22 additions and 3 deletions

View file

@ -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))

View file

@ -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_"`

2
go.mod
View file

@ -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