File: list.go

package info (click to toggle)
golang-github-liamg-clinch 1.5.6-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 5,576 kB
  • sloc: makefile: 2
file content (54 lines) | stat: -rw-r--r-- 1,359 bytes parent folder | download
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
46
47
48
49
50
51
52
53
54
package prompt

import (
	"fmt"
	"strconv"

	"github.com/liamg/tml"
)

// ErrUserCancelled means the user cancelled the current action
var ErrUserCancelled = fmt.Errorf("User cancelled")

// ErrUserChoiceInvalid means the user chose an option which was not valid
var ErrUserChoiceInvalid = fmt.Errorf("User choice invalid")

// ChooseFromList prompts the user to select an item from a list. It return the chosen list index, the chosen list item value, or an error
func ChooseFromList(message string, options []string) (int, string, error) {
	fmt.Printf("\n %s\n\n", message)
	colours := []string{"lightblue", "lightgreen", "lightyellow", "white"}

	for i, option := range options {
		col := colours[i%len(colours)]
		pad := ""
		if i+1 < 10 { // ocd padding
			pad = " "
		}
		tml.Printf(
			fmt.Sprintf(" %%s<darkgrey>[</darkgrey><%s>%%d<darkgrey>]</darkgrey> <%s>%%s\n", col, col),
			pad,
			i+1,
			option,
		)
	}
	fmt.Println("")
	choice := EnterInput("Enter choice (blank to cancel): ")
	fmt.Println("")

	if choice == "" {
		return -1, "", ErrUserCancelled
	}

	for i, opt := range options {
		if opt == choice {
			return i, opt, nil
		}
	}

	choiceIndex, err := strconv.Atoi(choice)
	if err != nil || choiceIndex-1 >= len(options) || choiceIndex <= 0 {
		return -1, "", ErrUserChoiceInvalid
	}

	return choiceIndex - 1, options[choiceIndex-1], nil
}