mirror of
https://github.com/charmbracelet/gum
synced 2026-03-14 21:55:45 +01:00
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:
parent
6d405c49b1
commit
2e321f57e2
3 changed files with 22 additions and 3 deletions
|
|
@ -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))
|
||||
|
|
|
|||
|
|
@ -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
2
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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue