Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion cmd/onecli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,10 @@ func main() {
os.Exit(exitcode.Error)
}

out.SetHint(hintForCommand(kCtx.Command(), config.APIHost()))
cmd := kCtx.Command()
out.SetHintFunc(func() string {
return hintForCommand(cmd, config.APIHost())
})
err = kCtx.Run(out)
if err != nil {
handleError(out, err)
Expand Down
29 changes: 23 additions & 6 deletions pkg/output/output.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ import (
// Writer handles all structured output for the CLI.
// All stdout/stderr writing must go through this. Never use fmt.Print or os.Stdout directly.
type Writer struct {
out io.Writer
err io.Writer
hint string
out io.Writer
err io.Writer
hint string
hintFn func() string
}

// New creates a Writer that writes to stdout and stderr.
Expand All @@ -39,6 +40,21 @@ func (w *Writer) SetHint(msg string) {
w.hint = msg
}

// SetHintFunc sets a function that lazily resolves the hint message at write
// time. This ensures the hint reflects state after the command has executed
// (e.g. after `config set api-host` updates the host).
func (w *Writer) SetHintFunc(fn func() string) {
w.hintFn = fn
}

// resolveHint returns the current hint, preferring hintFn if set.
func (w *Writer) resolveHint() string {
if w.hintFn != nil {
return w.hintFn()
}
return w.hint
}

// Write marshals v as indented JSON and writes it to stdout.
// HTML escaping is disabled because this is a CLI tool, not a web page.
func (w *Writer) Write(v any) error {
Expand Down Expand Up @@ -298,15 +314,16 @@ func (w *Writer) writeToOut(data []byte) error {
// injectHint prepends a "hint" property to JSON objects or wraps arrays
// in a {"hint": ..., "data": [...]} envelope.
func (w *Writer) injectHint(data []byte) []byte {
if w.hint == "" {
hint := w.resolveHint()
if hint == "" {
return data
}
trimmed := bytes.TrimSpace(data)
if len(trimmed) < 2 {
return data
}

hintVal, err := json.Marshal(w.hint)
hintVal, err := json.Marshal(hint)
if err != nil {
return data
}
Expand All @@ -315,7 +332,7 @@ func (w *Writer) injectHint(data []byte) []byte {
case '{':
return injectHintObject(data, hintVal)
case '[':
return injectHintArray(data, w.hint)
return injectHintArray(data, hint)
default:
return data
}
Expand Down
Loading