From 76485e77089760a5f1288657c329d1a06a7e1b9c Mon Sep 17 00:00:00 2001 From: Yonah Date: Thu, 19 Mar 2026 00:36:46 +0900 Subject: [PATCH] cmd/streamdata: additional prompt helpers These wrap existing helpers to implement certain retry behaviour. Signed-off-by: Yonah --- cmd/streamdata/prompt.go | 52 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/cmd/streamdata/prompt.go b/cmd/streamdata/prompt.go index 40cf31b..9d9bb16 100644 --- a/cmd/streamdata/prompt.go +++ b/cmd/streamdata/prompt.go @@ -7,6 +7,7 @@ import ( "math" "os" "strconv" + "strings" "syscall" "hakurei.app/ext" @@ -50,6 +51,23 @@ func prompt(br *bufio.Reader, p string) (string, bool) { return s[:len(s)-1], true } +// promptTrimNoEmpty prompts the user until EOF or a non-empty and +// non-whitespace-only response is read. It returns read response with leading +// and trailing whitespaces trimmed. +func promptTrimNoEmpty(br *bufio.Reader, p string) (string, bool) { +invalid: + s, ok := prompt(br, p) + if !ok { + return "", false + } + + s = strings.TrimSpace(s) + if s == "" { + goto invalid + } + return s, true +} + // noResponseUint is returned by promptUint when the user responds with a single // newline character. const noResponseUint = math.MaxUint64 @@ -74,6 +92,40 @@ invalid: return v, true } +// promptUintFallback is like promptUint, but returns fallback if the user +// responds with a single newline character. +func promptUintFallback( + br *bufio.Reader, + p string, + fallback uint64, +) (uint64, bool) { + v, ok := promptUint(br, p+ + "["+strconv.FormatUint(fallback, 10)+"] ") + if !ok && v == noResponseUint { + v, ok = fallback, true + } + return v, ok +} + +// promptUintFallbackBounds is like promptUint, but checks input bounds and +// returns fallback if the user responds with a single newline character. +func promptUintFallbackBounds( + br *bufio.Reader, + p string, + lb, ub uint64, + fallback uint64, +) (uint64, bool) { +invalid: + v, ok := promptUintFallback(br, p, fallback) + if !ok { + return 0, false + } + if v < lb || v > ub { + goto invalid + } + return v, true +} + // require panics with an error if ok is false, and returns v otherwise. func require[T any](v T, ok bool) T { if !ok {