Skip to content

Commit

Permalink
feat(choose): label delimiters (#783)
Browse files Browse the repository at this point in the history
I'm not sure if I like this impl, but it does work.

closes #406
  • Loading branch information
caarlos0 authored Dec 17, 2024
1 parent 6d405c4 commit 2e321f5
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
22 changes: 20 additions & 2 deletions choose/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package choose
import (
"errors"
"fmt"
"maps"
"os"
"slices"
"sort"
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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))
Expand Down
1 change: 1 addition & 0 deletions choose/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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_"`
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -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
Expand Down

0 comments on commit 2e321f5

Please sign in to comment.