Harden core packages and add interactive CLI config builder (rud config/validate/test)

This commit is contained in:
tyuXX 2026-11-19 13:05:26 +00:00
parent d37503c863
commit 99e24be6c9
29 changed files with 6763 additions and 165 deletions

827
internal/builder/ui.go Normal file
View file

@ -0,0 +1,827 @@
package builder
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
"time"
"git.gsdistance.org/tyuXX/RUD/internal/config"
)
// ErrAborted is returned when the user cancels the builder via Ctrl-C or reaches EOF.
var ErrAborted = errors.New("aborted by user")
// Option represents a selectable item in interactive menus.
type Option struct {
Label string
Description string
}
// UI provides interactive terminal prompts with raw arrow-key support on TTYs
// and clean numbered-prompt fallback for plain terminals and tests.
type UI struct {
in io.Reader
reader *bufio.Reader
out io.Writer
inFile *os.File
rawTTY bool
color bool
}
// NewUI constructs a UI bound to in/out. If plain is true or in/out are not TTYs,
// it uses numbered line-based prompts.
func NewUI(in io.Reader, out io.Writer, plain, noColor bool) *UI {
if in == nil {
in = os.Stdin
}
if out == nil {
out = os.Stdout
}
inFile, inIsFile := in.(*os.File)
outFile, outIsFile := out.(*os.File)
inTTY := inIsFile && isTerminal(inFile)
outTTY := outIsFile && isTerminal(outFile)
useColor := !noColor && outTTY && os.Getenv("NO_COLOR") == "" && os.Getenv("TERM") != "dumb"
useRaw := !plain && inTTY && outTTY && os.Getenv("TERM") != "dumb"
return &UI{
in: in,
reader: bufio.NewReader(in),
out: out,
inFile: inFile,
rawTTY: useRaw,
color: useColor,
}
}
func (u *UI) style(code, s string) string {
if !u.color || s == "" {
return s
}
return "\x1b[" + code + "m" + s + "\x1b[0m"
}
func (u *UI) Bold(s string) string { return u.style("1", s) }
func (u *UI) Dim(s string) string { return u.style("2", s) }
func (u *UI) Cyan(s string) string { return u.style("36", s) }
func (u *UI) Green(s string) string { return u.style("32", s) }
func (u *UI) Yellow(s string) string { return u.style("33", s) }
func (u *UI) Red(s string) string { return u.style("31", s) }
func (u *UI) Println(a ...any) {
_, _ = fmt.Fprintln(u.out, a...)
}
func (u *UI) Printf(format string, a ...any) {
_, _ = fmt.Fprintf(u.out, format, a...)
}
func (u *UI) Header(title, subtitle string) {
u.Println()
u.Println(u.Bold(u.Cyan("━━ " + title + " ━━")))
if subtitle != "" {
u.Println(u.Dim(subtitle))
}
}
func (u *UI) Info(msg string) { u.Println(u.Cyan("• ") + msg) }
func (u *UI) Ok(msg string) { u.Println(u.Green("✓ ") + msg) }
func (u *UI) Warn(msg string) { u.Println(u.Yellow("! ") + msg) }
func (u *UI) Error(msg string) { u.Println(u.Red("✗ ") + msg) }
func (u *UI) readLine() (string, error) {
line, err := u.reader.ReadString('\n')
line = strings.TrimRight(line, "\r\n")
if err != nil {
if errors.Is(err, io.EOF) {
if line != "" {
return strings.TrimSpace(line), nil
}
return "", ErrAborted
}
return "", err
}
return strings.TrimSpace(line), nil
}
type keyCode int
const (
keyNone keyCode = iota
keyUp
keyDown
keyEnter
keySpace
keyEsc
keyBack
keyAll
keyAbort
keyDigit
)
func (u *UI) readKey() (keyCode, int, error) {
buf := make([]byte, 8)
var n int
var err error
if u.reader.Buffered() > 0 {
n, err = u.reader.Read(buf)
} else {
n, err = u.inFile.Read(buf)
}
if err != nil {
if errors.Is(err, io.EOF) {
return keyAbort, 0, ErrAborted
}
return keyNone, 0, err
}
if n == 0 {
return keyNone, 0, nil
}
b := buf[:n]
if n >= 3 && b[0] == 0x1b && b[1] == '[' {
switch b[2] {
case 'A':
return keyUp, 0, nil
case 'B':
return keyDown, 0, nil
}
return keyNone, 0, nil
}
if n == 1 {
switch b[0] {
case 0x03: // Ctrl-C
return keyAbort, 0, ErrAborted
case '\r', '\n':
return keyEnter, 0, nil
case ' ':
return keySpace, 0, nil
case 0x1b:
return keyEsc, 0, nil
case 'k', 'K':
return keyUp, 0, nil
case 'j', 'J':
return keyDown, 0, nil
case 'q', 'Q', '0':
return keyBack, 0, nil
case 'a', 'A':
return keyAll, 0, nil
}
if b[0] >= '1' && b[0] <= '9' {
return keyDigit, int(b[0] - '1'), nil
}
}
return keyNone, 0, nil
}
func truncateDesc(s string, maxLen int) string {
s = strings.ReplaceAll(s, "\n", " ")
r := []rune(s)
if len(r) <= maxLen {
return s
}
return string(r[:maxLen-3]) + "..."
}
// Select displays a single-choice menu. Returns (selectedIndex, ok, error).
// ok is false when the user selects Back/Cancel.
func (u *UI) Select(title, subtitle string, opts []Option, defaultIdx int) (int, bool, error) {
if len(opts) == 0 {
return -1, false, nil
}
if u.rawTTY {
return u.selectTTY(title, subtitle, opts, defaultIdx)
}
return u.selectPlain(title, subtitle, opts, defaultIdx)
}
func (u *UI) selectTTY(title, subtitle string, opts []Option, defaultIdx int) (int, bool, error) {
restore, err := enableRawMode(u.inFile)
if err != nil {
return u.selectPlain(title, subtitle, opts, defaultIdx)
}
defer restore()
cursor := 0
if defaultIdx >= 0 && defaultIdx < len(opts) {
cursor = defaultIdx
}
u.Header(title, subtitle)
printedLines := 0
render := func() {
if printedLines > 0 {
u.Printf("\r\x1b[%dA", printedLines)
}
lines := 0
for i, opt := range opts {
prefix := " "
lbl := opt.Label
if i == cursor {
prefix = u.Cyan("❯ ")
lbl = u.Bold(u.Cyan(opt.Label))
}
desc := ""
if opt.Description != "" {
desc = " " + u.Dim(truncateDesc(opt.Description, 56))
}
u.Printf("\x1b[2K%s%2d) %s%s\r\n", prefix, i+1, lbl, desc)
lines++
}
u.Printf("\x1b[2K%s\r\n", u.Dim(" [↑/↓ move • 1-9 select • Enter confirm • Esc/q back]"))
lines++
printedLines = lines
}
render()
for {
k, digit, err := u.readKey()
if err != nil {
return -1, false, err
}
switch k {
case keyAbort:
return -1, false, ErrAborted
case keyUp:
cursor = (cursor - 1 + len(opts)) % len(opts)
render()
case keyDown:
cursor = (cursor + 1) % len(opts)
render()
case keyDigit:
if digit < len(opts) {
cursor = digit
if len(opts) <= 9 {
render()
return cursor, true, nil
}
render()
}
case keyEnter:
return cursor, true, nil
case keyEsc, keyBack:
return -1, false, nil
}
}
}
func (u *UI) selectPlain(title, subtitle string, opts []Option, defaultIdx int) (int, bool, error) {
u.Header(title, subtitle)
for i, opt := range opts {
mark := " "
if i == defaultIdx {
mark = "*"
}
if opt.Description != "" {
u.Printf(" %s%2d) %s — %s\n", mark, i+1, opt.Label, opt.Description)
} else {
u.Printf(" %s%2d) %s\n", mark, i+1, opt.Label)
}
}
u.Println(" 0) Back / Cancel")
for {
if defaultIdx >= 0 && defaultIdx < len(opts) {
u.Printf("Choose [1-%d, 0=back, Enter=%d]: ", len(opts), defaultIdx+1)
} else {
u.Printf("Choose [1-%d, 0=back]: ", len(opts))
}
line, err := u.readLine()
if err != nil {
return -1, false, err
}
if line == "" && defaultIdx >= 0 && defaultIdx < len(opts) {
return defaultIdx, true, nil
}
lower := strings.ToLower(line)
if lower == "0" || lower == "q" || lower == "b" || lower == "back" || lower == "cancel" {
return -1, false, nil
}
n, convErr := strconv.Atoi(line)
if convErr == nil && n >= 1 && n <= len(opts) {
return n - 1, true, nil
}
u.Error(fmt.Sprintf("Please enter a number between 1 and %d (or 0 to go back).", len(opts)))
}
}
// MultiSelect displays a checkbox menu. Returns (sortedSelectedIndices, ok, error).
func (u *UI) MultiSelect(title, subtitle string, opts []Option, preselected map[int]bool) ([]int, bool, error) {
if len(opts) == 0 {
return nil, true, nil
}
selected := make(map[int]bool, len(opts))
for k, v := range preselected {
if k >= 0 && k < len(opts) && v {
selected[k] = true
}
}
if u.rawTTY {
return u.multiSelectTTY(title, subtitle, opts, selected)
}
return u.multiSelectPlain(title, subtitle, opts, selected)
}
func sortedSelectedIndices(selected map[int]bool, n int) []int {
var out []int
for i := 0; i < n; i++ {
if selected[i] {
out = append(out, i)
}
}
return out
}
func (u *UI) multiSelectTTY(title, subtitle string, opts []Option, selected map[int]bool) ([]int, bool, error) {
restore, err := enableRawMode(u.inFile)
if err != nil {
return u.multiSelectPlain(title, subtitle, opts, selected)
}
defer restore()
cursor := 0
u.Header(title, subtitle)
printedLines := 0
render := func() {
if printedLines > 0 {
u.Printf("\r\x1b[%dA", printedLines)
}
lines := 0
for i, opt := range opts {
prefix := " "
if i == cursor {
prefix = u.Cyan("❯ ")
}
box := "[ ]"
if selected[i] {
box = u.Green("[x]")
}
lbl := opt.Label
if i == cursor {
lbl = u.Bold(lbl)
}
desc := ""
if opt.Description != "" {
desc = " " + u.Dim(truncateDesc(opt.Description, 48))
}
u.Printf("\x1b[2K%s%s %2d) %s%s\r\n", prefix, box, i+1, lbl, desc)
lines++
}
u.Printf("\x1b[2K%s\r\n", u.Dim(" [↑/↓ move • Space toggle • a all/none • Enter confirm • Esc/q cancel]"))
lines++
printedLines = lines
}
render()
for {
k, digit, err := u.readKey()
if err != nil {
return nil, false, err
}
switch k {
case keyAbort:
return nil, false, ErrAborted
case keyUp:
cursor = (cursor - 1 + len(opts)) % len(opts)
render()
case keyDown:
cursor = (cursor + 1) % len(opts)
render()
case keySpace:
if selected[cursor] {
delete(selected, cursor)
} else {
selected[cursor] = true
}
render()
case keyDigit:
if digit < len(opts) {
cursor = digit
if selected[digit] {
delete(selected, digit)
} else {
selected[digit] = true
}
render()
}
case keyAll:
allOn := len(sortedSelectedIndices(selected, len(opts))) == len(opts)
if allOn {
for _, k := range sortedSelectedIndices(selected, len(opts)) {
delete(selected, k)
}
} else {
for i := range opts {
selected[i] = true
}
}
render()
case keyEnter:
return sortedSelectedIndices(selected, len(opts)), true, nil
case keyEsc, keyBack:
return nil, false, nil
}
}
}
func (u *UI) multiSelectPlain(title, subtitle string, opts []Option, selected map[int]bool) ([]int, bool, error) {
u.Header(title, subtitle)
for i, opt := range opts {
box := "[ ]"
if selected[i] {
box = "[x]"
}
if opt.Description != "" {
u.Printf(" %2d) %s %s — %s\n", i+1, box, opt.Label, opt.Description)
} else {
u.Printf(" %2d) %s %s\n", i+1, box, opt.Label)
}
}
for {
u.PrintMultiHint()
line, err := u.readLine()
if err != nil {
return nil, false, err
}
lower := strings.ToLower(strings.TrimSpace(line))
switch lower {
case "":
return sortedSelectedIndices(selected, len(opts)), true, nil
case "q", "cancel", "back":
return nil, false, nil
case "all":
out := make([]int, len(opts))
for i := range opts {
out[i] = i
}
return out, true, nil
case "none":
return []int{}, true, nil
}
normalized := strings.ReplaceAll(lower, ",", " ")
parts := strings.Fields(normalized)
if len(parts) == 0 {
continue
}
next := make(map[int]bool, len(parts))
valid := true
for _, p := range parts {
n, convErr := strconv.Atoi(p)
if convErr != nil || n < 1 || n > len(opts) {
valid = false
break
}
next[n-1] = true
}
if !valid {
u.Error(fmt.Sprintf("Invalid selection. Enter numbers 1-%d (e.g. 1,3), 'all', 'none', or 'q'.", len(opts)))
continue
}
return sortedSelectedIndices(next, len(opts)), true, nil
}
}
func (u *UI) PrintMultiHint() {
u.Printf("Enter numbers (e.g. 1,3), 'all', 'none', Enter to keep current, or 'q' to cancel: ")
}
// Confirm prompts a yes/no question.
func (u *UI) Confirm(prompt string, defaultYes bool) (bool, error) {
suffix := "[y/N]"
if defaultYes {
suffix = "[Y/n]"
}
for {
u.Printf("%s %s: ", prompt, suffix)
line, err := u.readLine()
if err != nil {
return false, err
}
lower := strings.ToLower(strings.TrimSpace(line))
if lower == "" {
return defaultYes, nil
}
if lower == "y" || lower == "yes" {
return true, nil
}
if lower == "n" || lower == "no" {
return false, nil
}
u.Error("Please answer 'y' or 'n'.")
}
}
// PromptString prompts for a string value. Pressing Enter keeps current (if valid).
// When allowClear is true, typing "-" clears the value to "".
func (u *UI) PromptString(label, current, hint string, allowClear bool, validate func(string) error) (string, error) {
for {
var meta []string
if current != "" {
meta = append(meta, "current: "+current)
} else {
meta = append(meta, "empty")
}
if hint != "" {
meta = append(meta, hint)
}
if allowClear && current != "" {
meta = append(meta, "'-' to clear")
}
u.Printf("%s [%s]: ", u.Bold(label), strings.Join(meta, "; "))
line, err := u.readLine()
if err != nil {
return "", err
}
val := line
if line == "" {
val = current
} else if allowClear && line == "-" {
val = ""
}
if validate != nil {
if err := validate(val); err != nil {
u.Error(err.Error())
continue
}
}
return val, nil
}
}
// PromptDuration prompts for a Go duration string (e.g. 15s, 5m, 1h).
func (u *UI) PromptDuration(label string, current config.Duration, allowZero bool) (config.Duration, error) {
curStr := current.Std().String()
for {
hint := "e.g. 500ms, 15s, 5m"
if allowZero {
hint += "; '0s' or '-' for 0"
}
u.Printf("%s [current: %s; %s]: ", u.Bold(label), curStr, hint)
line, err := u.readLine()
if err != nil {
return 0, err
}
if line == "" {
if !allowZero && current <= 0 {
u.Error("Duration must be greater than 0.")
continue
}
return current, nil
}
if allowZero && (line == "-" || line == "0") {
return 0, nil
}
d, parseErr := time.ParseDuration(line)
if parseErr != nil {
u.Error(fmt.Sprintf("Invalid duration %q (use Go syntax like 500ms, 10s, 5m, 1h).", line))
continue
}
if d < 0 || (!allowZero && d == 0) {
u.Error("Duration must be positive.")
continue
}
return config.NewDuration(d), nil
}
}
// PromptInt prompts for an integer in [min, max].
func (u *UI) PromptInt(label string, current, min, max int) (int, error) {
for {
u.Printf("%s [current: %d]: ", u.Bold(label), current)
line, err := u.readLine()
if err != nil {
return 0, err
}
val := current
if line != "" {
parsed, convErr := strconv.Atoi(line)
if convErr != nil {
u.Error("Please enter a valid integer.")
continue
}
val = parsed
}
if val < min || val > max {
u.Error(fmt.Sprintf("Value must be between %d and %d.", min, max))
continue
}
return val, nil
}
}
// PromptOptionalInt prompts for an optional *int; '-' clears to nil.
func (u *UI) PromptOptionalInt(label string, current *int, min, max int) (*int, error) {
curDesc := "inherit/unset"
if current != nil {
curDesc = strconv.Itoa(*current)
}
for {
u.Printf("%s [current: %s; '-' to unset]: ", u.Bold(label), curDesc)
line, err := u.readLine()
if err != nil {
return nil, err
}
if line == "" {
return current, nil
}
if line == "-" {
return nil, nil
}
parsed, convErr := strconv.Atoi(line)
if convErr != nil {
u.Error("Please enter a valid integer or '-' to unset.")
continue
}
if parsed < min || parsed > max {
u.Error(fmt.Sprintf("Value must be between %d and %d.", min, max))
continue
}
return config.IntPtr(parsed), nil
}
}
// PromptFloat prompts for a floating-point number.
func (u *UI) PromptFloat(label string, current float64) (float64, error) {
for {
u.Printf("%s [current: %g]: ", u.Bold(label), current)
line, err := u.readLine()
if err != nil {
return 0, err
}
if line == "" {
return current, nil
}
parsed, convErr := strconv.ParseFloat(line, 64)
if convErr != nil {
u.Error("Please enter a valid number.")
continue
}
return parsed, nil
}
}
// EditStringMap provides an interactive editor for key-value string maps.
func (u *UI) EditStringMap(title string, existing map[string]string) (map[string]string, error) {
work := make(map[string]string, len(existing))
for k, v := range existing {
work[k] = v
}
for {
keys := make([]string, 0, len(work))
for k := range work {
keys = append(keys, k)
}
sort.Strings(keys)
var sub string
if len(keys) == 0 {
sub = "Currently empty."
} else {
var parts []string
for _, k := range keys {
parts = append(parts, fmt.Sprintf("%s=%q", k, work[k]))
}
sub = strings.Join(parts, ", ")
}
opts := []Option{
{Label: "Add or update entry", Description: "Set a key=value pair"},
}
if len(keys) > 0 {
opts = append(opts, Option{Label: "Remove entry", Description: "Delete an existing key"})
opts = append(opts, Option{Label: "Clear all entries"})
}
opts = append(opts, Option{Label: "Done"})
idx, ok, err := u.Select(title, sub, opts, len(opts)-1)
if err != nil {
return nil, err
}
if !ok || opts[idx].Label == "Done" {
if len(work) == 0 {
return nil, nil
}
return work, nil
}
switch opts[idx].Label {
case "Add or update entry":
k, err := u.PromptString("Key", "", "non-empty key", false, requireNonEmpty("key"))
if err != nil {
return nil, err
}
v, err := u.PromptString("Value for "+k, work[k], "", false, nil)
if err != nil {
return nil, err
}
work[k] = v
case "Remove entry":
delOpts := make([]Option, len(keys))
for i, k := range keys {
delOpts[i] = Option{Label: k, Description: work[k]}
}
dIdx, dOK, err := u.Select("Remove which key?", "", delOpts, -1)
if err != nil {
return nil, err
}
if dOK {
delete(work, keys[dIdx])
}
case "Clear all entries":
work = map[string]string{}
}
}
}
// EditStringSlice provides an interactive editor for ordered lists of strings.
func (u *UI) EditStringSlice(title, itemLabel string, existing []string) ([]string, error) {
work := append([]string(nil), existing...)
for {
sub := "Currently empty."
if len(work) > 0 {
sub = fmt.Sprintf("%d item(s): %s", len(work), strings.Join(work, ", "))
}
opts := []Option{
{Label: "Add " + itemLabel},
}
if len(work) > 0 {
opts = append(opts,
Option{Label: "Edit " + itemLabel},
Option{Label: "Remove " + itemLabel},
Option{Label: "Clear all"},
)
}
opts = append(opts, Option{Label: "Done"})
idx, ok, err := u.Select(title, sub, opts, len(opts)-1)
if err != nil {
return nil, err
}
if !ok || opts[idx].Label == "Done" {
if len(work) == 0 {
return nil, nil
}
return work, nil
}
switch opts[idx].Label {
case "Add " + itemLabel:
val, err := u.PromptString("New "+itemLabel, "", "", false, requireNonEmpty(itemLabel))
if err != nil {
return nil, err
}
work = append(work, val)
case "Edit " + itemLabel:
itemOpts := make([]Option, len(work))
for i, item := range work {
itemOpts[i] = Option{Label: item}
}
eIdx, eOK, err := u.Select("Edit which "+itemLabel+"?", "", itemOpts, -1)
if err != nil {
return nil, err
}
if eOK {
val, err := u.PromptString(itemLabel, work[eIdx], "", false, requireNonEmpty(itemLabel))
if err != nil {
return nil, err
}
work[eIdx] = val
}
case "Remove " + itemLabel:
itemOpts := make([]Option, len(work))
for i, item := range work {
itemOpts[i] = Option{Label: item}
}
rIdx, rOK, err := u.Select("Remove which "+itemLabel+"?", "", itemOpts, -1)
if err != nil {
return nil, err
}
if rOK {
work = append(work[:rIdx], work[rIdx+1:]...)
}
case "Clear all":
work = nil
}
}
}
func requireNonEmpty(field string) func(string) error {
return func(v string) error {
if strings.TrimSpace(v) == "" {
return fmt.Errorf("%s cannot be empty", field)
}
return nil
}
}