Documentation
¶
Overview ¶
Package console provides terminal output, styled markup, interactive prompts, and live progress displays for console commands.
Write command results to standard output with Console.Line, Console.Table, and Console.Markup. Status messages written with helpers such as Console.Info, Console.Success, Console.Warn, and Console.Error go to standard error, so scripts piping stdout get only the command's results:
func (p *PrunePosts) Run(ctx context.Context, c *console.Console) error {
c.Info("Deleting stale drafts...")
deleted, err := pruneDrafts(ctx, p.days)
if err != nil {
return err
}
c.Successf("Deleted %d drafts.", deleted)
return nil
}
For interactive commands, ask questions with Console.Ask, Console.Confirm, Console.Choice, and [Select], and track long-running work with Console.Progress, Console.Spinner, and [Spin]. Return Exit to terminate a command with a specific status code.
Index ¶
- Constants
- func Escape(text string) string
- func Exit(code int) error
- func ShutdownSignals() []os.Signal
- func Usagef(format string, args ...any) error
- type Console
- func (c *Console) Ask(ctx context.Context, question string, options ...Option) (string, error)
- func (c *Console) Choice(ctx context.Context, question string, choices []string, options ...Option) (string, error)
- func (c *Console) Confirm(ctx context.Context, question string, fallback bool) (bool, error)
- func (c *Console) Debug(message string)
- func (c *Console) Debugf(format string, args ...any)
- func (c *Console) Error(message string)
- func (c *Console) Errorf(format string, args ...any)
- func (c *Console) Info(message string)
- func (c *Console) Infof(format string, args ...any)
- func (c *Console) Line(text string)
- func (c *Console) Linef(format string, args ...any)
- func (c *Console) Markup(text string)
- func (c *Console) MultiChoice(ctx context.Context, question string, choices []string, options ...Option) ([]string, error)
- func (c *Console) MultiSelect[T comparable](ctx context.Context, question string, items []Item[T], options ...Option) ([]T, error)
- func (c *Console) NewLine()
- func (c *Console) Note(title, body string)
- func (c *Console) Paint(tone Tone, text string) string
- func (c *Console) Progress(total int, message string) *Progress
- func (c *Console) ProgressEach[T any](message string, items []T, work func(item T, bar *Progress) error) error
- func (c *Console) ProgressGroup(message string) *ProgressGroup
- func (c *Console) Secret(ctx context.Context, question string, options ...Option) (string, error)
- func (c *Console) Select[T comparable](ctx context.Context, question string, items []Item[T], options ...Option) (T, error)
- func (c *Console) Spin[T any](message string, work func() (T, error)) (T, error)
- func (c *Console) Spinner(message string) *Progress
- func (c *Console) Stderr() io.Writer
- func (c *Console) Stdout() io.Writer
- func (c *Console) Step(message string)
- func (c *Console) Stepf(format string, args ...any)
- func (c *Console) Success(message string)
- func (c *Console) Successf(format string, args ...any)
- func (c *Console) Table(headers []string, rows [][]string)
- func (c *Console) Verbose(message string)
- func (c *Console) Verbosef(format string, args ...any)
- func (c *Console) VeryVerbose(message string)
- func (c *Console) VeryVerbosef(format string, args ...any)
- func (c *Console) Warn(message string)
- func (c *Console) Warnf(format string, args ...any)
- type ExitError
- type Item
- type Option
- func Default(answer any) Option
- func Defaults(choices ...any) Option
- func Hint(text string) Option
- func Multiline() Option
- func Placeholder(text string) Option
- func Required() Option
- func Searchable() Option
- func Suggest(suggestions ...string) Option
- func SuggestFunc(suggest func(input string) []string) Option
- func Validate[T any](check func(answer T) error) Option
- type Progress
- type ProgressGroup
- type Tone
- type UsageError
- type Verbosity
Constants ¶
const ( // Info represents neutral status, matching the marker color of // [Console.Info]. Info = terminal.Info // Success represents completed work, matching the marker color of // [Console.Success]. Success = terminal.Success // Warning represents conditions that need attention, matching the marker // color of [Console.Warn]. Warning = terminal.Warning // Error represents failures, matching the marker color of [Console.Error]. Error = terminal.Error // Accent highlights actionable text such as command names and flags. Accent = terminal.Accent // Muted dims supporting details such as table headers and durations. Muted = terminal.Muted )
Variables ¶
This section is empty.
Functions ¶
func Escape ¶
Escape prepares dynamic text for safe inclusion in Console.Markup by escaping < and \ characters and stripping raw ANSI escape sequences and control characters other than newlines and tabs:
c.Markup("<fg=sky-400>Hello, " + console.Escape(name) + ".</>")
func Exit ¶
Exit returns an *ExitError that terminates a command with the given status code without printing an error message:
if len(problems) > 0 {
return console.Exit(3)
}
func ShutdownSignals ¶
ShutdownSignals returns the operating-system signals that request a graceful shutdown (os.Interrupt and syscall.SIGTERM on Unix, os.Interrupt on Windows). Return it from a command's Signals method so long-running commands can finish their current unit of work before exiting without importing syscall directly:
func (*ImportFeed) Signals() []os.Signal {
return console.ShutdownSignals()
}
func Usagef ¶
Usagef returns a *UsageError whose message it formats with fmt.Sprintf. Write the message as an error, in lowercase without a final period:
if v.visibility != "public" && v.visibility != "private" {
return console.Usagef("`--visibility` must be `public` or `private`, not `%s`", v.visibility)
}
Types ¶
type Console ¶
type Console struct {
// Args holds the positional arguments passed to the command after flags.
Args []string
// Verbosity is the active output level. Check it before computing expensive
// diagnostic details:
//
// if c.Verbosity >= console.Verbose {
// c.Verbosef("%d users before the import", count(ctx))
// }
Verbosity Verbosity
// Signals receives operating-system signals trapped by the command's
// Signals method instead of canceling its context. It is nil when the
// command traps no signals.
Signals <-chan os.Signal
// Input is the reader used by interactive prompts. When nil (such as with
// -n or non-terminal standard input), prompts fall back to their configured
// defaults or return an error.
Input io.Reader
// contains filtered or unexported fields
}
Console represents a command's terminal interface. Laravel passes a configured Console to each command after applying the standard verbosity and interactivity flags (-q, -v, -vv, -vvv, and -n).
func New ¶
New creates a Console that writes results to stdout, writes status messages, prompts, and progress displays to stderr, and reads prompt answers from stdin.
If stdin is an *os.File that is not an interactive terminal (such as a pipe or redirected file), New leaves Input nil so prompts do not block waiting for input. If stdin implements Answer(question string) (string, error), such as scripted test input from laraveltest, prompts read answers from that method instead of scanning lines.
func (*Console) Ask ¶
Ask prompts the user with question and returns their trimmed text answer:
name, err := c.Ask(ctx, "What is the user's name?", console.Required())
When Console.Input is nil, Ask returns the value set with Default or an error if no default was provided. If ctx is canceled before an answer is submitted, Ask returns ctx.Err().
func (*Console) Choice ¶
func (c *Console) Choice(ctx context.Context, question string, choices []string, options ...Option) (string, error)
Choice prompts the user to pick one string from choices. On an interactive terminal, choices appear as an arrow-key menu; otherwise the user enters a choice name or its 1-based number. To separate display labels from returned values or show per-choice hints, use [Select].
func (*Console) Confirm ¶
Confirm asks a yes-or-no question and returns the boolean result. An empty submission or non-interactive execution returns fallback.
func (*Console) Debug ¶
Debug writes a plain detail line to standard error when Verbosity is Debug (-vvv).
func (*Console) Debugf ¶
Debugf formats a detail line with fmt.Sprintf and writes it with Console.Debug.
func (*Console) Error ¶
Error writes an error message to standard error prefixed with ■. Unlike other output methods, Error still writes when Verbosity is Quiet.
func (*Console) Errorf ¶
Errorf formats a message with fmt.Sprintf and writes it with Console.Error.
func (*Console) Infof ¶
Infof formats a message with fmt.Sprintf and writes it with Console.Info:
c.Infof("Importing %d users.", len(users))
func (*Console) Linef ¶
Linef formats text with fmt.Sprintf and writes it followed by a newline to standard output.
func (*Console) Markup ¶
Markup renders inline style tags in text and writes the result followed by a newline to standard output. Opening tags combine semicolon-separated attributes (fg, bg, and comma-separated options) and close with </>:
c.Markup("<fg=black;bg=cyan> Notice </> <fg=emerald-400;options=bold>Ready</>")
Colors accept ANSI names (such as "red" or "bright-blue"), Tailwind CSS shades (such as "emerald-400"), or hex values (such as "#ff8800"). Supported options are bold, underscore, blink, reverse, and conceal. On terminals without 24-bit color support, colors fall back to the nearest available palette entry.
Nested tags inherit and extend outer styles until their closing </>. Invalid tags and unmatched </> tokens remain literal text. Use \< and \\ for literal < and \ characters. Raw ANSI escape sequences and control characters other than newlines and tabs are stripped. When standard output is not a terminal or NO_COLOR is set, tags are removed and plain text is written; Quiet (-q) suppresses output like Console.Line.
Pass untrusted or dynamic text through Escape before interpolating it into markup so literal < characters are not parsed as tags.
func (*Console) MultiChoice ¶
func (c *Console) MultiChoice(ctx context.Context, question string, choices []string, options ...Option) ([]string, error)
MultiChoice prompts the user to select zero or more strings from choices and returns them in the order they appear in choices. On an interactive terminal, Space toggles items and Enter submits; otherwise the user enters comma-separated names or 1-based numbers:
roles, err := c.MultiChoice(ctx, "Which roles?", []string{"admin", "editor", "viewer"}, console.Defaults("editor"))
Use Defaults to preselect choices, Required to reject an empty selection, and Validate to validate each selected choice. For custom labels, hints, or non-string values, use Console.MultiSelect.
func (*Console) MultiSelect ¶
func (c *Console) MultiSelect[T comparable](ctx context.Context, question string, items []Item[T], options ...Option) ([]T, error)
MultiSelect prompts the user to select zero or more options from items and returns their values in item order, displaying each item's Label and Hint.
Pass values of type T to Defaults and Validate. Off a terminal or in scripted tests, answers are comma-separated labels or 1-based numbers. MultiSelect returns an error if a configured default is not among items, if no input is available without defaults, or if ctx is canceled.
func (*Console) NewLine ¶
func (c *Console) NewLine()
NewLine writes a blank line to standard output.
func (*Console) Note ¶
Note writes a titled message to standard error prefixed with ● like Console.Info, placing body on the line beneath title.
func (*Console) Paint ¶
Paint styles text with tone when standard output supports color, and returns text unchanged otherwise. Pass the result to Console.Line or Console.Table to highlight individual values.
func (*Console) Progress ¶
Progress starts a progress bar tracking total units of work under the label message. Call Progress.Advance as units complete, and end the bar with Progress.Finish, Progress.Cancel, or Progress.Fail:
bar := c.Progress(len(drafts), "Deleting drafts...")
for _, draft := range drafts {
if err := model.Delete(ctx, &draft); err != nil {
bar.Fail("Couldn't delete the drafts.")
return err
}
bar.Advance(1)
}
bar.Finish("Drafts deleted.")
Only one top-level progress display should run at a time. To show several concurrent tasks, use Console.ProgressGroup.
func (*Console) ProgressEach ¶
func (c *Console) ProgressEach[T any](message string, items []T, work func(item T, bar *Progress) error) error
ProgressEach iterates over items while updating a progress bar labeled with message, advancing by 1 after each item and finishing the bar when all items succeed:
err := c.ProgressEach("Deleting drafts...", drafts, func(draft models.Post, bar *console.Progress) error {
bar.Message("Deleting " + draft.Title + "...")
return model.Delete(ctx, &draft)
})
The callback may update the bar's label or hint. On the first error, ProgressEach stops immediately, ends the bar with its current label (as canceled for context.Canceled or context.DeadlineExceeded, or as failed otherwise), and returns that error.
func (*Console) ProgressGroup ¶
func (c *Console) ProgressGroup(message string) *ProgressGroup
ProgressGroup starts a ProgressGroup displaying multiple bars and spinners beneath the heading message:
group := c.ProgressGroup("Preparing the application...")
assets := group.Spinner("Building assets...")
records := group.Progress(len(rows), "Importing records...")
// Advance and end each display from any goroutine...
group.Finish("Application ready.")
func (*Console) Secret ¶
Secret prompts the user with question while hiding typed characters on an interactive terminal, such as for passwords or API tokens.
func (*Console) Select ¶
func (c *Console) Select[T comparable](ctx context.Context, question string, items []Item[T], options ...Option) (T, error)
Select prompts the user to choose one option from items and returns its Value, displaying each item's Label and Hint:
env, err := c.Select(ctx, "Which environment?", []console.Item[Environment]{
{Value: Production, Label: "Production", Hint: "Live customer traffic"},
{Value: Staging, Label: "Staging", Hint: "Testing environment"},
}, console.Default(Staging))
Pass values of type T to Default and Validate. Off a terminal or in scripted tests, answers match an item's label or 1-based number. Select returns an error if a configured default is not among items, if no input is available without a default, or if ctx is canceled.
func (*Console) Spin ¶
Spin runs work while showing an animated spinner labeled with message, then finishes the spinner with message on success or fails it with message when work returns an error:
users, err := c.Spin("Loading users...", func() ([]models.User, error) {
return model.Query[models.User]().Get(ctx)
})
func (*Console) Spinner ¶
Spinner starts an animated spinner for work of unknown length under the label message. End it with Progress.Finish, Progress.Cancel, or Progress.Fail, or use [Spin] to manage the lifecycle around a callback.
func (*Console) Stderr ¶
Stderr returns the standard error io.Writer. When Verbosity is Quiet, Stderr returns io.Discard.
func (*Console) Stdout ¶
Stdout returns the standard output io.Writer for libraries that stream directly to a writer, such as encoding/csv. When Verbosity is Quiet, Stdout returns io.Discard.
func (*Console) Stepf ¶
Stepf formats a message with fmt.Sprintf and writes it with Console.Step.
func (*Console) Successf ¶
Successf formats a message with fmt.Sprintf and writes it with Console.Success.
func (*Console) Table ¶
Table writes rows to standard output in a bordered table under headers. Each row should contain one cell per header, and a cell may hold several lines. On a terminal, the table wraps to the terminal's width. Cells styled with Console.Paint align according to their visible text width:
c.Table([]string{"Invoice", "Status"}, [][]string{
{"1024", c.Paint(console.Success, "Paid")},
{"1025", c.Paint(console.Warning, "Overdue")},
})
func (*Console) Verbose ¶
Verbose writes a plain detail line to standard error when Verbosity is Verbose (-v) or higher.
func (*Console) Verbosef ¶
Verbosef formats a detail line with fmt.Sprintf and writes it with Console.Verbose.
func (*Console) VeryVerbose ¶
VeryVerbose writes a plain detail line to standard error when Verbosity is VeryVerbose (-vv) or higher.
func (*Console) VeryVerbosef ¶
VeryVerbosef formats a detail line with fmt.Sprintf and writes it with Console.VeryVerbose.
func (*Console) Warnf ¶
Warnf formats a message with fmt.Sprintf and writes it with Console.Warn.
type ExitError ¶
ExitError signals that a command should exit with a specific status code other than 1. When a command returns an ExitError, Laravel prints Err (if non-nil) and exits with Code.
func (*ExitError) Error ¶
Error returns the wrapped error's message, or "exit status N" when Err is nil.
func (*ExitError) TraceSummary ¶
TraceSummary describes an exit without an error by its status. One with an error is described by its error.
type Item ¶
type Item[T comparable] struct { Value T Label string Hint string }
Item describes one option in a [Select] or [MultiSelect] menu. Value is returned when the item is chosen, Label is displayed (defaulting to fmt.Sprint(Value) when empty), and Hint is shown dimmed beside Label.
type Option ¶
type Option func(*prompt)
Option configures the behavior, default value, presentation, or validation of an interactive prompt.
func Default ¶
Default sets the answer used when the user submits an empty response or when the command runs non-interactively (such as with -n). Pass a value matching the prompt's answer type: string for Console.Ask and Console.Choice, or type T for [Select].
func Defaults ¶
Defaults sets the initial selections for Console.MultiChoice and [MultiSelect] when the user submits without changes or when running non-interactively. Calling Defaults() with no arguments selects nothing.
func Hint ¶
Hint displays supporting guidance alongside the prompt question, shown beneath the question on a terminal and above it on non-terminal output.
func Multiline ¶
func Multiline() Option
Multiline allows multi-line answers in Console.Ask. On an interactive terminal, Enter inserts a newline, Escape toggles review mode, and Enter in review mode submits. On non-terminal input, an empty line terminates the answer.
func Placeholder ¶
Placeholder displays dimmed example text inside an empty prompt on an interactive terminal. Unlike Default, placeholder text is not submitted as an answer.
func Required ¶
func Required() Option
Required rejects an empty text answer or a Console.MultiChoice / [MultiSelect] submission with no items selected.
func Searchable ¶
func Searchable() Option
Searchable enables type-to-filter searching on interactive terminal menus for Console.Choice, Console.MultiChoice, [Select], and [MultiSelect]. On non-terminal input, users still answer by label or option number.
func Suggest ¶
Suggest displays case-insensitive prefix completions from suggestions as the user types on an interactive terminal. Users navigate matches with the arrow keys and accept one with Tab. Suggestions do not restrict free-form input; combine with Validate to enforce a fixed set of values.
func SuggestFunc ¶
SuggestFunc displays dynamic completions returned by suggest for the current input text, following Suggest. Because suggest runs on every keystroke, keep it fast.
type Progress ¶
type Progress struct {
// contains filtered or unexported fields
}
Progress displays a live progress bar for bounded work or an animated spinner for work of unknown length. Start one with Console.Progress or Console.Spinner, update it with Progress.Advance, Progress.Message, or Progress.Hint, and close it with Progress.Finish, Progress.Cancel, or Progress.Fail.
On an interactive terminal, the display redraws in place on standard error while command output written with Console.Line, Console.Warn, or other methods scrolls above it. On non-terminal output, such as a log file or test buffer, only the final message is written.
func (*Progress) Advance ¶
Advance increments the completed count by n. It is safe to call concurrently from multiple goroutines.
func (*Progress) Cancel ¶
Cancel closes the display and writes message with a ▲ marker like Console.Warn.
func (*Progress) Fail ¶
Fail closes the display and writes message with a ■ marker like Console.Error. To exit the command with a non-zero status, also return an error from the command.
func (*Progress) Finish ¶
Finish closes the display and writes message with a ◆ marker like Console.Success.
type ProgressGroup ¶
type ProgressGroup struct {
// contains filtered or unexported fields
}
ProgressGroup renders multiple concurrent Progress bars and spinners under a single heading. Start one with Console.ProgressGroup, create child displays with ProgressGroup.Progress and ProgressGroup.Spinner, end each child, and finish the group with ProgressGroup.Finish, ProgressGroup.Cancel, or ProgressGroup.Fail.
When a child ends, it leaves the group and prints its final message above the group. If any child was canceled or failed, ending the group reflects the worst child outcome even when ProgressGroup.Finish is called.
func (*ProgressGroup) Cancel ¶
func (g *ProgressGroup) Cancel(message string)
Cancel closes the group and writes message with a ▲ warning marker, unless a child bar or spinner failed.
func (*ProgressGroup) Fail ¶
func (g *ProgressGroup) Fail(message string)
Fail closes the group and writes message with a ■ error marker. To exit the command with a non-zero status, also return an error from the command.
func (*ProgressGroup) Finish ¶
func (g *ProgressGroup) Finish(message string)
Finish closes the group and writes message with a ◆ completion marker, unless a child bar or spinner was canceled or failed.
func (*ProgressGroup) Progress ¶
func (g *ProgressGroup) Progress(total int, message string) *Progress
Progress adds a progress bar for total units of work to the group, following Console.Progress.
func (*ProgressGroup) Spinner ¶
func (g *ProgressGroup) Spinner(message string) *Progress
Spinner adds a spinner to the group, following Console.Spinner.
type Tone ¶
Tone identifies a semantic color role shared with Laravel's built-in commands, such as Success for completed migrations.
type UsageError ¶
type UsageError struct {
// contains filtered or unexported fields
}
UsageError is a mistake on the command line that a command finds itself, such as an option's value it doesn't accept. Laravel prints the message with the command's usage and exits with status 2, as it does for an option the command doesn't have.
func (*UsageError) Error ¶
func (e *UsageError) Error() string
Error returns the message, without the usage.
type Verbosity ¶
type Verbosity int
Verbosity controls which output levels a Console writes.
const ( // Quiet suppresses all output except errors written with [Console.Error]. // Selected by the -q flag. Quiet Verbosity = iota - 1 // Normal writes standard results and status messages. This is the default. Normal // Verbose also writes messages from [Console.Verbose]. Selected by the -v // flag. Verbose // VeryVerbose also writes messages from [Console.VeryVerbose]. Selected by // the -vv flag. VeryVerbose // Debug also writes messages from [Console.Debug]. Selected by the -vvv // flag. Debug )