-
Notifications
You must be signed in to change notification settings - Fork 64
/
select.go
45 lines (35 loc) · 1.02 KB
/
select.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2022, Unikraft GmbH and The KraftKit Authors.
// Licensed under the BSD-3-Clause License (the "License").
// You may not use this file except in compliance with the License.
package selection
import (
"fmt"
"sort"
"github.com/erikgeiser/promptkit/selection"
"kraftkit.sh/tui"
)
// Select is a utility method used in a CLI context to prompt the user
// given a slice of options based on the generic type.
func Select[T fmt.Stringer](question string, options ...T) (*T, error) {
if len(options) == 1 {
return &options[0], nil
}
strings := make([]string, 0, len(options))
for _, option := range options {
strings = append(strings, option.String())
}
sort.Strings(strings)
sp := selection.New(tui.TextWhiteBgBlue("[?]")+" "+question, strings)
sp.Filter = nil
result, err := sp.RunPrompt()
if err != nil {
return nil, err
}
for _, t := range options {
if t.String() == result {
return &t, nil
}
}
return nil, fmt.Errorf("could not perform selection")
}