interact

package
v0.5.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 27 Imported by: 4

Documentation

Overview

Package interact collect some interactive methods for CLI

Index

Constants

View Source
const (
	// OK success exit code
	OK = 0
	// ERR error exit code
	ERR = 2
)

Variables

View Source
var (
	// ErrQuit is returned when the user chooses to quit an interaction.
	ErrQuit = errors.New("interact: user quit")
	// ErrMaxAttempts is returned when the max input attempts is exceeded.
	ErrMaxAttempts = errors.New("interact: max attempts exceeded")
)
View Source
var (
	// ErrUIAborted reports that the current interaction was aborted.
	ErrUIAborted = ui.ErrAborted
	// ErrUINoTTY reports that a strict terminal backend requires a TTY.
	ErrUINoTTY = ui.ErrNoTTY
	// ErrUIInvalidState reports invalid ui component state.
	ErrUIInvalidState = ui.ErrInvalidState
	// ErrUINotImplemented reports a missing backend implementation.
	ErrUINotImplemented = ui.ErrNotImplemented
)

Functions

func AnswerIsYes

func AnswerIsYes(defVal ...bool) bool

AnswerIsYes check user inputted answer is right. it is a shortcut of AnswerIsYesE(), and returns false on read error.

Usage:

fmt.Print("are you OK?")
ok := AnswerIsYes()
ok := AnswerIsYes(true)

func AnswerIsYesE added in v0.5.2

func AnswerIsYesE(defVal ...bool) (bool, error)

AnswerIsYesE check user inputted answer is right. it returns an error when reading the user input fails.

Usage:

fmt.Print("are you OK?")
ok, err := AnswerIsYesE()
ok, err := AnswerIsYesE(true)

func Ask

func Ask(question, defVal string, fn func(ans string) error, maxTimes ...int) string

Ask a question and return the result of the input. it is a shortcut of AskE(), and returns an empty string on error.

Usage:

answer := Ask("Your name?", "tom", nil)

func AskE added in v0.5.3

func AskE(question, defVal string, fn func(ans string) error, maxTimes ...int) (string, error)

AskE a question and return the result of the input, together with any read error.

Usage:

answer, err := AskE("Your name?", "", nil)
answer, err := AskE("Your name?", "tom", nil)
answer, err := AskE("Your name?", "", nil, 3)

func Checkbox

func Checkbox(title string, options any, defOpts []string, allowQuit ...bool) []string

Checkbox select multi of the options. is alias of method MultiSelect()

func CheckboxE added in v0.5.3

func CheckboxE(title string, options any, defOpts []string, allowQuit ...bool) ([]string, error)

CheckboxE is alias of method MultiSelectE()

func Choice

func Choice(title string, options any, defOpt string, allowQuit ...bool) string

Choice is alias of method SelectOne()

func ChoiceE added in v0.5.3

func ChoiceE(title string, options any, defOpt string, allowQuit ...bool) (string, error)

ChoiceE is alias of method SelectOneE()

func Confirm

func Confirm(message string, defVal ...bool) bool

Confirm a question, returns bool. it is a shortcut of ConfirmE(), and returns false on read error.

func ConfirmE added in v0.5.2

func ConfirmE(message string, defVal ...bool) (bool, error)

ConfirmE a question, returns the answer and any read error.

func GetHiddenInput

func GetHiddenInput(message string, trimmed bool) (string, error)

GetHiddenInput interactively prompts for input without echoing to the terminal.

Usage:

// askPassword
pwd := GetHiddenInput("Enter Password:")

func MultiSelect

func MultiSelect(title string, options any, defOpts []string, allowQuit ...bool) []string

MultiSelect select multi of the options, returns selected option values. it is a shortcut of MultiSelectE(), and returns nil on error.

like SingleSelect(), but allow select multi option

func MultiSelectE added in v0.5.3

func MultiSelectE(title string, options any, defOpts []string, allowQuit ...bool) ([]string, error)

MultiSelectE select multi of the options, returns selected option values and any error.

like SingleSelectE(), but allow select multi option

func NewUIConfirm

func NewUIConfirm(prompt string, def bool) *ui.Confirm

NewUIConfirm creates a ui.Confirm component.

func NewUIFakeBackend

func NewUIFakeBackend(events ...backend.Event) backend.Backend

NewUIFakeBackend creates an in-memory backend for tests or scripted event flows.

func NewUIInput

func NewUIInput(prompt string) *ui.Input

NewUIInput creates a ui.Input component.

func NewUIMultiSelect

func NewUIMultiSelect(prompt string, items []ui.Item) *ui.MultiSelect

NewUIMultiSelect creates a ui.MultiSelect component.

func NewUIPlainBackend

func NewUIPlainBackend() backend.Backend

NewUIPlainBackend creates a line-based backend for ui components.

func NewUIReadlineBackend

func NewUIReadlineBackend() backend.Backend

NewUIReadlineBackend creates a raw-terminal backend that falls back to plain mode on non-TTY input.

func NewUISelect

func NewUISelect(prompt string, items []ui.Item) *ui.Select

NewUISelect creates a ui.Select component.

func NewUIStrictReadlineBackend

func NewUIStrictReadlineBackend() backend.Backend

NewUIStrictReadlineBackend creates a strict raw-terminal backend that requires a TTY.

func Prompt

func Prompt(ctx context.Context, query, defaultAnswer string) (string, error)

Prompt query and read user answer.

Usage:

answer, err := Prompt(context.Background(), "your name?", "")

from package golang.org/x/tools/cmd/getgo

func Query

func Query(question, defVal string, fn func(ans string) error, maxTimes ...int) string

Query is alias of method Ask()

func QueryE added in v0.5.3

func QueryE(question, defVal string, fn func(ans string) error, maxTimes ...int) (string, error)

QueryE is alias of method AskE()

func ReadFirst

func ReadFirst(question string) (string, error)

ReadFirst read first char

func ReadInput

func ReadInput(question string) (string, error)

ReadInput read user input form Stdin

func ReadLine

func ReadLine(question string) (string, error)

ReadLine read one line from user input.

Usage:

in := ReadLine("")
ans, _ := ReadLine("your name?")

func ReadPassword

func ReadPassword(question ...string) string

ReadPassword from terminal

func SelectOne

func SelectOne(title string, options any, defOpt string, allowQuit ...bool) string

SelectOne select one of the options, returns selected option value. it is a shortcut of SelectOneE(), and returns an empty string on error.

func SelectOneE added in v0.5.3

func SelectOneE(title string, options any, defOpt string, allowQuit ...bool) (string, error)

SelectOneE select one of the options, returns selected option value and any error.

Map options:

{
   	// option key => option value
   	'a' => 'chengdu',
   	'b' => 'beijing'
}

Array options:

{
   // only value, key will use index
   'chengdu',
   'beijing'
}

func SelectOneKey added in v0.4.0

func SelectOneKey(title string, options any, defOpt string, opFns ...func(*Select)) string

SelectOneKey select one of the options, returns selected option key. it is a shortcut of SelectOneKeyE(), and returns an empty string on error.

func SelectOneKeyE added in v0.5.3

func SelectOneKeyE(title string, options any, defOpt string, opFns ...func(*Select)) (string, error)

SelectOneKeyE select one of the options, returns selected option key and any error.

func SingleSelect

func SingleSelect(title string, options any, defOpt string, allowQuit ...bool) string

SingleSelect is alias of method SelectOne()

func SingleSelectE added in v0.5.3

func SingleSelectE(title string, options any, defOpt string, allowQuit ...bool) (string, error)

SingleSelectE is alias of method SelectOneE()

func Unconfirmed

func Unconfirmed(message string, defVal ...bool) bool

Unconfirmed a question, returns whether the user did NOT confirm. it is a shortcut of UnconfirmedE(), and returns true on read error.

func UnconfirmedE added in v0.5.2

func UnconfirmedE(message string, defVal ...bool) (bool, error)

UnconfirmedE a question, returns whether the user did NOT confirm, and any read error.

Types

type Collector

type Collector struct {
	// contains filtered or unexported fields
}

Collector information collector 信息收集者 cli input values collector

func NewCollector

func NewCollector() *Collector

NewCollector instance

func (*Collector) AddParam

func (c *Collector) AddParam(p InputParameter) error

AddParam to collector

func (*Collector) AddParams

func (c *Collector) AddParams(ps ...InputParameter) error

AddParams definitions at once.

func (*Collector) MustParam

func (c *Collector) MustParam(name string) InputParameter

MustParam get from collector

func (*Collector) Param

func (c *Collector) Param(name string) (InputParameter, bool)

Param get from collector

func (*Collector) Results

func (c *Collector) Results() maputil.Data

Results for collector

func (*Collector) Run

func (c *Collector) Run() error

Run collector

type InputParameter

type InputParameter interface {
	Type() string
	Name() string
	Desc() string
	Value() structs.Value
	Set(v string) error
	Run() error
}

InputParameter interface

type Question

type Question struct {
	// Out output writer. default is cutypes.Output
	Out io.Writer
	// Q the question message
	Q string
	// Func validate user input answer is right.
	// if not set, will only check the answer is empty.
	Func func(ans string) error
	// DefVal default value
	DefVal string
	// MaxTimes maximum allowed number of errors, 0 is don't limited
	MaxTimes int
	// contains filtered or unexported fields
}

Question definition

func NewQuestion

func NewQuestion(q string, defVal ...string) *Question

NewQuestion instance.

Usage:

q := NewQuestion("Please input your name?")
ans := q.Run().String()

func (*Question) Run

func (q *Question) Run() *Value

Run and returns value. it is a shortcut of RunE(), and returns an empty value on error.

func (*Question) RunE added in v0.5.3

func (q *Question) RunE() (*Value, error)

RunE and returns value, together with any read error.

type Select

type Select struct {
	// Out output writer. default is cutypes.Output
	Out io.Writer
	// Title message for select. e.g "Your city?"
	Title string
	// Options the items data for select. allow: []int, []string, map[string]string
	Options any
	// DefOpt default option when not input answer
	DefOpt string
	// DefOpts use for `MultiSelect` is true
	DefOpts []string
	// DisableQuit option. if is false, will display "quit" option. default False
	DisableQuit bool
	// MultiSelect allow multi select. default False
	MultiSelect bool
	// contains filtered or unexported fields
}

Select definition

func NewSelect

func NewSelect(title string, items any, fns ...func(*Select)) *Select

NewSelect instance.

- items allow: []int, []string, map[string]string

Usage:

s := NewSelect("Your city?", []string{"chengdu", "beijing"})
r := s.Run()
key := r.KeyString() // "1"
val := r.String() // "beijing"

func (*Select) EnableMulti

func (s *Select) EnableMulti() *Select

EnableMulti select

func (*Select) Run

func (s *Select) Run() *SelectResult

Run select and receive use input answer. it is a shortcut of RunE(), and returns an empty result on error.

func (*Select) RunE added in v0.5.3

func (s *Select) RunE() (*SelectResult, error)

RunE select and receive use input answer, and returns any read error.

func (*Select) With added in v0.4.0

func (s *Select) With(fns ...func(*Select)) *Select

With apply option funcs

type SelectResult

type SelectResult struct {
	Value // V the select value(s)
	// K the select key(s)
	K Value
}

SelectResult data store

func (*SelectResult) Key

func (sv *SelectResult) Key() any

Key value get

func (*SelectResult) KeyString

func (sv *SelectResult) KeyString() string

KeyString get

func (*SelectResult) KeyStrings

func (sv *SelectResult) KeyStrings() []string

KeyStrings get

func (*SelectResult) WithKey

func (sv *SelectResult) WithKey(key any) *SelectResult

WithKey value

type StepHandler

type StepHandler func(ctx context.Context) error

StepHandler for steps run

type StepsRun

type StepsRun struct {

	// Steps step name and handler define.
	// {
	// 	// step 1
	// 	func(ctx context.Context) { do something.}
	// 	// step 2
	// 	func(ctx context.Context) { do something.}
	// }
	Steps []StepHandler
	// contains filtered or unexported fields
}

StepsRun follow the steps to run

func (*StepsRun) Err

func (s *StepsRun) Err() error

Err get error

func (*StepsRun) Run

func (s *StepsRun) Run()

Run all steps with a background context.

func (*StepsRun) RunContext added in v0.5.0

func (s *StepsRun) RunContext(ctx context.Context)

RunContext runs all steps, stopping early when ctx is cancelled.

func (*StepsRun) Stop

func (s *StepsRun) Stop()

Stop set stop run

type UIBackend

type UIBackend = backend.Backend

UIBackend aliases the new backend abstraction.

type UIConfirm

type UIConfirm = ui.Confirm

UIConfirm aliases the new confirm component.

type UIInput

type UIInput = ui.Input

UIInput aliases the new input component.

type UIItem

type UIItem = ui.Item

UIItem aliases the new ui item type.

type UIMultiSelect

type UIMultiSelect = ui.MultiSelect

UIMultiSelect aliases the new multi select component.

type UIResult

type UIResult = ui.Result

UIResult aliases the new ui result type.

type UISelect

type UISelect = ui.Select

UISelect aliases the new select component.

type Value

type Value = structs.Value

Value alias of structs.Value

Directories

Path Synopsis
Package backend defines the runtime abstraction used by interact/ui.
Package backend defines the runtime abstraction used by interact/ui.
fake
Package fake provides an in-memory backend for interaction tests.
Package fake provides an in-memory backend for interaction tests.
plain
Package plain provides a line-based backend for interact/ui.
Package plain provides a line-based backend for interact/ui.
readline
Package readline provides a minimal raw-terminal event backend for interact/ui.
Package readline provides a minimal raw-terminal event backend for interact/ui.
Package ui defines interactive component models built on top of a backend.
Package ui defines interactive component models built on top of a backend.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL