cli

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2026 License: EUPL-1.2 Imports: 31 Imported by: 0

Documentation

Overview

Package cli provides the CLI runtime and utilities.

Package cli provides the CLI runtime and utilities.

Package cli provides the CLI runtime and utilities.

The CLI uses the Core framework for its own runtime. Usage is simple:

cli.Init(cli.Options{AppName: "core"})
defer cli.Shutdown()

cli.Success("Done!")
cli.Error("Failed")
if cli.Confirm("Proceed?") { ... }

// When you need the Core instance
c := cli.Core()

Package cli provides semantic CLI output with zero external dependencies.

Index

Constants

View Source
const (
	// LogLevelQuiet suppresses all output.
	LogLevelQuiet = log.LevelQuiet
	// LogLevelError shows only error messages.
	LogLevelError = log.LevelError
	// LogLevelWarn shows warnings and errors.
	LogLevelWarn = log.LevelWarn
	// LogLevelInfo shows info, warnings, and errors.
	LogLevelInfo = log.LevelInfo
	// LogLevelDebug shows all messages including debug.
	LogLevelDebug = log.LevelDebug
)

Log level constants aliased from the log package.

View Source
const (
	ColourBlue50     = "#eff6ff"
	ColourBlue100    = "#dbeafe"
	ColourBlue200    = "#bfdbfe"
	ColourBlue300    = "#93c5fd"
	ColourBlue400    = "#60a5fa"
	ColourBlue500    = "#3b82f6"
	ColourBlue600    = "#2563eb"
	ColourBlue700    = "#1d4ed8"
	ColourGreen400   = "#4ade80"
	ColourGreen500   = "#22c55e"
	ColourGreen600   = "#16a34a"
	ColourRed400     = "#f87171"
	ColourRed500     = "#ef4444"
	ColourRed600     = "#dc2626"
	ColourAmber400   = "#fbbf24"
	ColourAmber500   = "#f59e0b"
	ColourAmber600   = "#d97706"
	ColourOrange500  = "#f97316"
	ColourYellow500  = "#eab308"
	ColourEmerald500 = "#10b981"
	ColourPurple500  = "#a855f7"
	ColourViolet400  = "#a78bfa"
	ColourViolet500  = "#8b5cf6"
	ColourIndigo500  = "#6366f1"
	ColourCyan500    = "#06b6d4"
	ColourGray50     = "#f9fafb"
	ColourGray100    = "#f3f4f6"
	ColourGray200    = "#e5e7eb"
	ColourGray300    = "#d1d5db"
	ColourGray400    = "#9ca3af"
	ColourGray500    = "#6b7280"
	ColourGray600    = "#4b5563"
	ColourGray700    = "#374151"
	ColourGray800    = "#1f2937"
	ColourGray900    = "#111827"
)

Tailwind colour palette (hex strings)

Variables

View Source
var (
	AppVersion      = "0.0.0"
	BuildCommit     = "unknown"
	BuildDate       = "unknown"
	BuildPreRelease = ""
)

Build-time variables set via ldflags (SemVer 2.0.0):

go build -ldflags="-X forge.lthn.ai/core/cli/pkg/cli.AppVersion=1.2.0 \
  -X forge.lthn.ai/core/cli/pkg/cli.BuildCommit=df94c24 \
  -X forge.lthn.ai/core/cli/pkg/cli.BuildDate=2026-02-06 \
  -X forge.lthn.ai/core/cli/pkg/cli.BuildPreRelease=dev.8"
View Source
var (
	SuccessStyle  = NewStyle().Bold().Foreground(ColourGreen500)
	ErrorStyle    = NewStyle().Bold().Foreground(ColourRed500)
	WarningStyle  = NewStyle().Bold().Foreground(ColourAmber500)
	InfoStyle     = NewStyle().Foreground(ColourBlue400)
	SecurityStyle = NewStyle().Bold().Foreground(ColourPurple500)
	DimStyle      = NewStyle().Dim().Foreground(ColourGray500)
	MutedStyle    = NewStyle().Foreground(ColourGray600)
	BoldStyle     = NewStyle().Bold()
	KeyStyle      = NewStyle().Foreground(ColourGray400)
	ValueStyle    = NewStyle().Foreground(ColourGray200)
	AccentStyle   = NewStyle().Foreground(ColourCyan500)
	LinkStyle     = NewStyle().Foreground(ColourBlue500).Underline()
	HeaderStyle   = NewStyle().Bold().Foreground(ColourGray200)
	TitleStyle    = NewStyle().Bold().Foreground(ColourBlue500)
	CodeStyle     = NewStyle().Foreground(ColourGray300)
	NumberStyle   = NewStyle().Foreground(ColourBlue300)
	RepoStyle     = NewStyle().Bold().Foreground(ColourBlue500)
)

Core styles

View Source
var AppName = "core"

AppName is the default CLI application name. Override with WithAppName before calling Main.

Functions

func ArbitraryArgs

func ArbitraryArgs() cobra.PositionalArgs

ArbitraryArgs returns a PositionalArgs that accepts any arguments.

func As

func As(err error, target any) bool

As finds the first error in err's tree that matches target. This is a re-export of errors.As for convenience.

func Blank

func Blank()

Blank prints an empty line.

func BoolFlag

func BoolFlag(cmd *Command, ptr *bool, name, short string, def bool, usage string)

BoolFlag adds a boolean flag to a command. The value will be stored in the provided pointer.

var verbose bool
cli.BoolFlag(cmd, &verbose, "verbose", "v", false, "Enable verbose output")

func Choose

func Choose[T any](prompt string, items []T, opts ...ChooseOption[T]) T

Choose prompts the user to select from a list of items. Returns the selected item. Uses simple numbered selection for terminal compatibility.

choice := Choose("Select a file:", files)
choice := Choose("Select a file:", files, WithDisplay(func(f File) string { return f.Name }))

func ChooseAction

func ChooseAction[T any](verb, subject string, items []T, opts ...ChooseOption[T]) T

ChooseAction prompts for selection using grammar composition.

file := ChooseAction("select", "file", files)

func ChooseMulti

func ChooseMulti[T any](prompt string, items []T, opts ...ChooseOption[T]) []T

ChooseMulti prompts the user to select multiple items from a list. Returns the selected items. Uses space-separated numbers or ranges.

choices := ChooseMulti("Select files:", files)
choices := ChooseMulti("Select files:", files, WithDisplay(func(f File) string { return f.Name }))

Input format:

  • "1 3 5" - select items 1, 3, and 5
  • "1-3" - select items 1, 2, and 3
  • "1 3-5" - select items 1, 3, 4, and 5
  • "" (empty) - select none

func ChooseMultiAction

func ChooseMultiAction[T any](verb, subject string, items []T, opts ...ChooseOption[T]) []T

ChooseMultiAction prompts for multiple selections using grammar composition.

files := ChooseMultiAction("select", "files", files)

func ColorEnabled

func ColorEnabled() bool

ColorEnabled returns true if ANSI color output is enabled.

func Confirm

func Confirm(prompt string, opts ...ConfirmOption) bool

Confirm prompts the user for yes/no confirmation. Returns true if the user enters "y" or "yes" (case-insensitive).

Basic usage:

if Confirm("Delete file?") { ... }

With options:

if Confirm("Save changes?", DefaultYes()) { ... }
if Confirm("Dangerous!", Required()) { ... }
if Confirm("Auto-continue?", Timeout(30*time.Second)) { ... }

func ConfirmAction

func ConfirmAction(verb, subject string, opts ...ConfirmOption) bool

ConfirmAction prompts for confirmation of an action using grammar composition.

if ConfirmAction("delete", "config.yaml") { ... }
if ConfirmAction("save", "changes", DefaultYes()) { ... }

func ConfirmDangerousAction

func ConfirmDangerousAction(verb, subject string) bool

ConfirmDangerousAction prompts for double confirmation of a dangerous action. Shows initial question, then a "Really verb subject?" confirmation.

if ConfirmDangerousAction("delete", "config.yaml") { ... }

func Context

func Context() context.Context

Context returns the CLI's root context. Cancelled on SIGINT/SIGTERM.

func Core

func Core() *framework.Core

Core returns the CLI's framework Core instance.

func Dim

func Dim(msg string)

Dim prints dimmed text.

func DimStr

func DimStr(msg string) string

DimStr returns dim-styled string.

func DurationFlag added in v0.0.2

func DurationFlag(cmd *Command, ptr *time.Duration, name, short string, def time.Duration, usage string)

DurationFlag adds a time.Duration flag to a command. The value will be stored in the provided pointer.

var timeout time.Duration
cli.DurationFlag(cmd, &timeout, "timeout", "t", 30*time.Second, "Request timeout")

func Echo

func Echo(key string, args ...any)

Echo translates a key via i18n.T and prints with newline. No automatic styling - use Success/Error/Warn/Info for styled output.

func Err

func Err(format string, args ...any) error

Err creates a new error from a format string. This is a direct replacement for fmt.Errorf.

func Error

func Error(msg string)

Error prints an error message with cross (red) to stderr and logs it.

func ErrorStr

func ErrorStr(msg string) string

ErrorStr returns error-styled string.

func ErrorWrap

func ErrorWrap(err error, msg string)

ErrorWrap prints a wrapped error message to stderr and logs it.

func ErrorWrapAction

func ErrorWrapAction(err error, verb string)

ErrorWrapAction prints a wrapped error using i18n grammar to stderr and logs it.

func ErrorWrapVerb

func ErrorWrapVerb(err error, verb, subject string)

ErrorWrapVerb prints a wrapped error using i18n grammar to stderr and logs it.

func Errorf

func Errorf(format string, args ...any)

Errorf prints a formatted error message to stderr and logs it.

func ExactArgs

func ExactArgs(n int) cobra.PositionalArgs

ExactArgs returns a PositionalArgs that accepts exactly N arguments.

func Execute

func Execute() error

Execute runs the CLI root command. Returns an error if the command fails.

func Exit

func Exit(code int, err error) error

Exit creates a new ExitError with the given code and error. Use this to return an error from a command with a specific exit code.

func Fatal deprecated

func Fatal(err error)

Fatal prints an error message to stderr, logs it, and exits with code 1.

Deprecated: return an error from the command instead.

func FatalWrap deprecated

func FatalWrap(err error, msg string)

FatalWrap prints a wrapped error message to stderr, logs it, and exits with code 1. Does nothing if err is nil.

Deprecated: return an error from the command instead.

cli.FatalWrap(err, "load config")  // Prints "✗ load config: <error>" and exits

func FatalWrapVerb deprecated

func FatalWrapVerb(err error, verb, subject string)

FatalWrapVerb prints a wrapped error using i18n grammar to stderr, logs it, and exits with code 1. Does nothing if err is nil.

Deprecated: return an error from the command instead.

cli.FatalWrapVerb(err, "load", "config")  // Prints "✗ Failed to load config: <error>" and exits

func Fatalf deprecated

func Fatalf(format string, args ...any)

Fatalf prints a formatted error message to stderr, logs it, and exits with code 1.

Deprecated: return an error from the command instead.

func Float64Flag added in v0.0.2

func Float64Flag(cmd *Command, ptr *float64, name, short string, def float64, usage string)

Float64Flag adds a float64 flag to a command. The value will be stored in the provided pointer.

var threshold float64
cli.Float64Flag(cmd, &threshold, "threshold", "t", 0.0, "Score threshold")

func FormatAge

func FormatAge(t time.Time) string

FormatAge formats a time as human-readable age (e.g., "2h ago", "3d ago").

func GhAuthenticated

func GhAuthenticated() bool

GhAuthenticated checks if the GitHub CLI is authenticated. Returns true if 'gh auth status' indicates a logged-in user.

func GitClone

func GitClone(ctx context.Context, org, repo, path string) error

GitClone clones a GitHub repository to the specified path. Prefers 'gh repo clone' if authenticated, falls back to SSH.

func Glyph

func Glyph(code string) string

Glyph converts a shortcode (e.g. ":check:") to its symbol based on the current theme.

func Hint

func Hint(label, message string)

Hint prints a labelled hint: "label: message"

cli.Hint("install", "composer require vimeo/psalm")
cli.Hint("fix", "core php fmt --fix")

func Info

func Info(msg string)

Info prints an info message with info symbol (blue).

func InfoStr

func InfoStr(msg string) string

InfoStr returns info-styled string.

func Infof

func Infof(format string, args ...any)

Infof prints a formatted info message.

func Init

func Init(opts Options) error

Init initialises the global CLI runtime. Call this once at startup (typically in main.go or cmd.Execute).

func Int64Flag added in v0.0.2

func Int64Flag(cmd *Command, ptr *int64, name, short string, def int64, usage string)

Int64Flag adds an int64 flag to a command. The value will be stored in the provided pointer.

var seed int64
cli.Int64Flag(cmd, &seed, "seed", "s", 0, "Random seed")

func IntFlag

func IntFlag(cmd *Command, ptr *int, name, short string, def int, usage string)

IntFlag adds an integer flag to a command. The value will be stored in the provided pointer.

var count int
cli.IntFlag(cmd, &count, "count", "n", 10, "Number of items")

func Is

func Is(err, target error) bool

Is reports whether any error in err's tree matches target. This is a re-export of errors.Is for convenience.

func IsStderrTTY

func IsStderrTTY() bool

IsStderrTTY returns true if stderr is a terminal.

func IsStdinTTY

func IsStdinTTY() bool

IsStdinTTY returns true if stdin is a terminal.

func IsTTY

func IsTTY() bool

IsTTY returns true if stdout is a terminal.

func Join

func Join(errs ...error) error

Join returns an error that wraps the given errors. This is a re-export of errors.Join for convenience.

func Label

func Label(word, value string)

Label prints a "Label: value" line.

func LogDebug

func LogDebug(msg string, keyvals ...any)

LogDebug logs a debug message with optional key-value pairs if log service is available.

func LogError

func LogError(msg string, keyvals ...any)

LogError logs an error message with optional key-value pairs if log service is available.

func LogInfo

func LogInfo(msg string, keyvals ...any)

LogInfo logs an info message with optional key-value pairs if log service is available.

func LogSecurity

func LogSecurity(msg string, keyvals ...any)

LogSecurity logs a security message if log service is available.

func LogWarn

func LogWarn(msg string, keyvals ...any)

LogWarn logs a warning message with optional key-value pairs if log service is available.

func Main

func Main(commands ...framework.Option)

Main initialises and runs the CLI application. Pass command services via WithCommands to register CLI commands through the Core framework lifecycle.

cli.Main(
    cli.WithCommands("config", config.AddConfigCommands),
    cli.WithCommands("doctor", doctor.AddDoctorCommands),
)

Exits with code 1 on error or panic.

func MaximumNArgs

func MaximumNArgs(n int) cobra.PositionalArgs

MaximumNArgs returns a PositionalArgs that accepts maximum N arguments.

func MinimumNArgs

func MinimumNArgs(n int) cobra.PositionalArgs

MinimumNArgs returns a PositionalArgs that accepts minimum N arguments.

func MultiSelect

func MultiSelect(label string, options []string) ([]string, error)

MultiSelect presents checkboxes (space-separated numbers).

func NewI18nService

func NewI18nService(opts I18nOptions) func(*framework.Core) (any, error)

NewI18nService creates an i18n service factory.

func NewLogService

func NewLogService(opts LogOptions) func(*framework.Core) (any, error)

NewLogService creates a log service factory with CLI styling.

func NoArgs

func NoArgs() cobra.PositionalArgs

NoArgs returns a PositionalArgs that accepts no arguments.

func Pad

func Pad(s string, width int) string

Pad right-pads a string to width.

func PersistentBoolFlag

func PersistentBoolFlag(cmd *Command, ptr *bool, name, short string, def bool, usage string)

PersistentBoolFlag adds a persistent boolean flag (inherited by subcommands).

func PersistentStringFlag

func PersistentStringFlag(cmd *Command, ptr *string, name, short, def, usage string)

PersistentStringFlag adds a persistent string flag (inherited by subcommands).

func Print

func Print(format string, args ...any)

Print outputs formatted text (no newline). Glyph shortcodes like :check: are converted.

func Println

func Println(format string, args ...any)

Println outputs formatted text with newline. Glyph shortcodes like :check: are converted.

func Progress

func Progress(verb string, current, total int, item ...string)

Progress prints a progress indicator that overwrites the current line. Uses i18n.Progress for gerund form ("Checking...").

func ProgressDone

func ProgressDone()

ProgressDone clears the progress line.

func Prompt

func Prompt(label, defaultVal string) (string, error)

Prompt asks for text input with a default value.

func Question

func Question(prompt string, opts ...QuestionOption) string

Question prompts the user for text input.

name := Question("Enter your name:")
name := Question("Enter your name:", WithDefault("Anonymous"))
name := Question("Enter your name:", RequiredInput())

func QuestionAction

func QuestionAction(verb, subject string, opts ...QuestionOption) string

QuestionAction prompts for text input using grammar composition.

name := QuestionAction("rename", "old.txt")

func RegisterCommands

func RegisterCommands(fn CommandRegistration)

RegisterCommands registers a function that adds commands to the CLI. Call this in your package's init() to register commands.

func init() {
    cli.RegisterCommands(AddCommands)
}

func AddCommands(root *cobra.Command) {
    root.AddCommand(myCmd)
}

func RegisteredCommands added in v0.0.3

func RegisteredCommands() iter.Seq[CommandRegistration]

RegisteredCommands returns an iterator over the registered command functions.

func Result

func Result(passed bool, message string)

Result prints a result line: "✓ message" or "✗ message"

cli.Result(passed, "All tests passed")
cli.Result(false, "3 tests failed")

func RootCmd

func RootCmd() *cobra.Command

RootCmd returns the CLI's root cobra command.

func Run

func Run(ctx context.Context) error

Run blocks until context is cancelled or signal received. Simple helper for daemon mode without advanced features.

cli.Init(cli.Options{AppName: "myapp"})
defer cli.Shutdown()
cli.Run(cli.Context())

func RunWithTimeout

func RunWithTimeout(timeout time.Duration) func()

RunWithTimeout wraps Run with a graceful shutdown timeout. The returned function should be deferred to replace cli.Shutdown().

cli.Init(cli.Options{AppName: "myapp"})
shutdown := cli.RunWithTimeout(30 * time.Second)
defer shutdown()
cli.Run(cli.Context())

func Scanln

func Scanln(a ...any) (int, error)

Scanln reads from stdin.

func Section

func Section(name string)

Section prints a section header: "── SECTION ──"

cli.Section("audit")  // ── AUDIT ──

func Select

func Select(label string, options []string) (string, error)

Select presents numbered options and returns the selected value.

func SemVer

func SemVer() string

SemVer returns the full SemVer 2.0.0 version string.

  • Release: 1.2.0
  • Pre-release: 1.2.0-dev.8
  • Full: 1.2.0-dev.8+df94c24.20260206

func SetColorEnabled

func SetColorEnabled(enabled bool)

SetColorEnabled enables or disables ANSI color output. This overrides the NO_COLOR environment variable check.

func Severity

func Severity(level, message string)

Severity prints a severity-styled message.

cli.Severity("critical", "SQL injection")  // red, bold
cli.Severity("high", "XSS vulnerability")  // orange
cli.Severity("medium", "Missing CSRF")     // amber
cli.Severity("low", "Debug enabled")       // gray

func Shutdown

func Shutdown()

Shutdown gracefully shuts down the CLI.

func Sprint

func Sprint(args ...any) string

Sprint formats using default formats (fmt.Sprint wrapper).

func Sprintf

func Sprintf(format string, args ...any) string

Sprintf formats a string (fmt.Sprintf wrapper).

func StringFlag

func StringFlag(cmd *Command, ptr *string, name, short, def, usage string)

StringFlag adds a string flag to a command. The value will be stored in the provided pointer.

var output string
cli.StringFlag(cmd, &output, "output", "o", "", "Output file path")

func StringSliceFlag

func StringSliceFlag(cmd *Command, ptr *[]string, name, short string, def []string, usage string)

StringSliceFlag adds a string slice flag to a command. The value will be stored in the provided pointer.

var tags []string
cli.StringSliceFlag(cmd, &tags, "tag", "t", nil, "Tags to apply")

func Styled

func Styled(style *AnsiStyle, text string) string

Styled returns text with a style applied.

func Styledf

func Styledf(style *AnsiStyle, format string, args ...any) string

Styledf returns formatted text with a style applied.

func Success

func Success(msg string)

Success prints a success message with checkmark (green).

func SuccessStr

func SuccessStr(msg string) string

SuccessStr returns success-styled string.

func Successf

func Successf(format string, args ...any)

Successf prints a formatted success message.

func T

func T(key string, args ...map[string]any) string

T translates a key using the CLI's i18n service. Falls back to the global i18n.T if CLI not initialised.

func Task

func Task(label, message string)

Task prints a task header: "[label] message"

cli.Task("php", "Running tests...")  // [php] Running tests...
cli.Task("go", i18n.Progress("build"))  // [go] Building...

func Text

func Text(args ...any)

Text prints arguments like fmt.Println, but handling glyphs.

func Truncate

func Truncate(s string, max int) string

Truncate shortens a string to max length with ellipsis.

func UseASCII

func UseASCII()

UseASCII switches the glyph theme to ASCII and disables colors.

func UseEmoji

func UseEmoji()

UseEmoji switches the glyph theme to Emoji.

func UseRenderBoxed

func UseRenderBoxed()

UseRenderBoxed sets the render style to boxed (Unicode box drawing).

func UseRenderFlat

func UseRenderFlat()

UseRenderFlat sets the render style to flat (no borders).

func UseRenderSimple

func UseRenderSimple()

UseRenderSimple sets the render style to simple (--- separators).

func UseUnicode

func UseUnicode()

UseUnicode switches the glyph theme to Unicode.

func Warn

func Warn(msg string)

Warn prints a warning message with warning symbol (amber) to stderr and logs it.

func WarnStr

func WarnStr(msg string) string

WarnStr returns warning-styled string.

func Warnf

func Warnf(format string, args ...any)

Warnf prints a formatted warning message to stderr and logs it.

func WithAppName

func WithAppName(name string)

WithAppName sets the application name used in help text and shell completion. Call before Main for variant binaries (e.g. "lem", "devops").

cli.WithAppName("lem")
cli.Main()

func WithCommands added in v0.0.2

func WithCommands(name string, register func(root *Command)) framework.Option

WithCommands creates a framework Option that registers a command group. The register function receives the root command during service startup, allowing commands to participate in the Core lifecycle.

cli.Main(
    cli.WithCommands("config", config.AddConfigCommands),
    cli.WithCommands("doctor", doctor.AddDoctorCommands),
)

func Wrap

func Wrap(err error, msg string) error

Wrap wraps an error with a message. Returns nil if err is nil.

return cli.Wrap(err, "load config")  // "load config: <original error>"

func WrapAction

func WrapAction(err error, verb string) error

WrapAction wraps an error using i18n grammar for "Failed to verb". Uses the i18n.ActionFailed function for proper grammar composition. Returns nil if err is nil.

return cli.WrapAction(err, "connect")  // "Failed to connect: <original error>"

func WrapVerb

func WrapVerb(err error, verb, subject string) error

WrapVerb wraps an error using i18n grammar for "Failed to verb subject". Uses the i18n.ActionFailed function for proper grammar composition. Returns nil if err is nil.

return cli.WrapVerb(err, "load", "config")  // "Failed to load config: <original error>"

Types

type AnsiStyle

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

AnsiStyle represents terminal text styling. Use NewStyle() to create, chain methods, call Render().

func NewStyle

func NewStyle() *AnsiStyle

NewStyle creates a new empty style.

func (*AnsiStyle) Background

func (s *AnsiStyle) Background(hex string) *AnsiStyle

Background sets background color from hex string.

func (*AnsiStyle) Bold

func (s *AnsiStyle) Bold() *AnsiStyle

Bold enables bold text.

func (*AnsiStyle) Dim

func (s *AnsiStyle) Dim() *AnsiStyle

Dim enables dim text.

func (*AnsiStyle) Foreground

func (s *AnsiStyle) Foreground(hex string) *AnsiStyle

Foreground sets foreground color from hex string.

func (*AnsiStyle) Italic

func (s *AnsiStyle) Italic() *AnsiStyle

Italic enables italic text.

func (*AnsiStyle) Render

func (s *AnsiStyle) Render(text string) string

Render applies the style to text. Returns plain text if NO_COLOR is set or colors are disabled.

func (*AnsiStyle) Underline

func (s *AnsiStyle) Underline() *AnsiStyle

Underline enables underlined text.

type BorderStyle

type BorderStyle int

BorderStyle selects the box-drawing character set for table borders.

const (
	// BorderNone disables borders (default).
	BorderNone BorderStyle = iota
	// BorderNormal uses standard box-drawing: ┌─┬┐ │ ├─┼┤ └─┴┘
	BorderNormal
	// BorderRounded uses rounded corners: ╭─┬╮ │ ├─┼┤ ╰─┴╯
	BorderRounded
	// BorderHeavy uses heavy box-drawing: ┏━┳┓ ┃ ┣━╋┫ ┗━┻┛
	BorderHeavy
	// BorderDouble uses double-line box-drawing: ╔═╦╗ ║ ╠═╬╣ ╚═╩╝
	BorderDouble
)

type CellStyleFn

type CellStyleFn func(value string) *AnsiStyle

CellStyleFn returns a style based on the cell's raw value. Return nil to use the table's default CellStyle.

type CheckBuilder

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

CheckBuilder provides fluent API for check results.

func Check

func Check(name string) *CheckBuilder

Check starts building a check result line.

cli.Check("audit").Pass()
cli.Check("fmt").Fail().Duration("2.3s")
cli.Check("test").Skip()

func (*CheckBuilder) Duration

func (c *CheckBuilder) Duration(d string) *CheckBuilder

Duration adds duration to the check result.

func (*CheckBuilder) Fail

func (c *CheckBuilder) Fail() *CheckBuilder

Fail marks the check as failed.

func (*CheckBuilder) Message

func (c *CheckBuilder) Message(msg string) *CheckBuilder

Message adds a custom message instead of status.

func (*CheckBuilder) Pass

func (c *CheckBuilder) Pass() *CheckBuilder

Pass marks the check as passed.

func (*CheckBuilder) Print

func (c *CheckBuilder) Print()

Print outputs the check result.

func (*CheckBuilder) Skip

func (c *CheckBuilder) Skip() *CheckBuilder

Skip marks the check as skipped.

func (*CheckBuilder) String

func (c *CheckBuilder) String() string

String returns the formatted check line.

func (*CheckBuilder) Warn

func (c *CheckBuilder) Warn() *CheckBuilder

Warn marks the check as warning.

type ChooseOption

type ChooseOption[T any] func(*chooseConfig[T])

ChooseOption configures Choose behaviour.

func Display

func Display[T any](fn func(T) string) ChooseOption[T]

Display sets a custom display function for items. Alias for WithDisplay for shorter syntax.

Choose("Select:", items, Display(func(f File) string { return f.Name }))

func Filter

func Filter[T any]() ChooseOption[T]

Filter enables type-to-filter functionality. Users can type to narrow down the list of options. Note: This is a hint for interactive UIs; the basic CLI Choose implementation uses numbered selection which doesn't support filtering.

func Multi

func Multi[T any]() ChooseOption[T]

Multi allows multiple selections. Use ChooseMulti instead of Choose when this option is needed.

func WithDefaultIndex

func WithDefaultIndex[T any](idx int) ChooseOption[T]

WithDefaultIndex sets the default selection index (0-based).

func WithDisplay

func WithDisplay[T any](fn func(T) string) ChooseOption[T]

WithDisplay sets a custom display function for items.

type Command

type Command = cobra.Command

Command is the cobra command type. Re-exported for convenience so packages don't need to import cobra directly.

func NewCommand

func NewCommand(use, short, long string, run func(cmd *Command, args []string) error) *Command

NewCommand creates a new command with a RunE handler. This is the standard way to create commands that may return errors.

cmd := cli.NewCommand("build", "Build the project", "", func(cmd *cli.Command, args []string) error {
    // Build logic
    return nil
})

func NewGroup

func NewGroup(use, short, long string) *Command

NewGroup creates a new command group (no RunE). Use this for parent commands that only contain subcommands.

devCmd := cli.NewGroup("dev", "Development commands", "")
devCmd.AddCommand(buildCmd, testCmd)

func NewRun

func NewRun(use, short, long string, run func(cmd *Command, args []string)) *Command

NewRun creates a new command with a simple Run handler (no error return). Use when the command cannot fail.

cmd := cli.NewRun("version", "Show version", "", func(cmd *cli.Command, args []string) {
    cli.Println("v1.0.0")
})

func WithArgs

func WithArgs(cmd *Command, args cobra.PositionalArgs) *Command

WithArgs sets the Args validation function for a command. Returns the command for chaining.

cmd := cli.NewCommand("build", "Build", "", run).WithArgs(cobra.ExactArgs(1))

func WithExample

func WithExample(cmd *Command, example string) *Command

WithExample sets the Example field for a command. Returns the command for chaining.

type CommandRegistration

type CommandRegistration func(root *cobra.Command)

CommandRegistration is a function that adds commands to the root.

type Composite

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

Composite represents an HLCRF layout node.

func Layout

func Layout(variant string) *Composite

Layout creates a new layout from a variant string.

func ParseVariant

func ParseVariant(variant string) (*Composite, error)

ParseVariant parses a variant string like "H[LC]C[HCF]F".

func (*Composite) C

func (c *Composite) C(items ...any) *Composite

C adds content to Content region.

func (*Composite) F

func (c *Composite) F(items ...any) *Composite

F adds content to Footer region.

func (*Composite) H

func (c *Composite) H(items ...any) *Composite

H adds content to Header region.

func (*Composite) L

func (c *Composite) L(items ...any) *Composite

L adds content to Left region.

func (*Composite) R

func (c *Composite) R(items ...any) *Composite

R adds content to Right region.

func (*Composite) Regions added in v0.0.3

func (c *Composite) Regions() iter.Seq[Region]

Regions returns an iterator over the regions in the composite.

func (*Composite) Render

func (c *Composite) Render()

Render outputs the layout to terminal.

func (*Composite) Slots added in v0.0.3

func (c *Composite) Slots() iter.Seq2[Region, *Slot]

Slots returns an iterator over the slots in the composite.

func (*Composite) String

func (c *Composite) String() string

String returns the rendered layout.

type ConfirmOption

type ConfirmOption func(*confirmConfig)

ConfirmOption configures Confirm behaviour.

func DefaultYes

func DefaultYes() ConfirmOption

DefaultYes sets the default response to "yes" (pressing Enter confirms).

func Required

func Required() ConfirmOption

Required prevents empty responses; user must explicitly type y/n.

func Timeout

func Timeout(d time.Duration) ConfirmOption

Timeout sets a timeout after which the default response is auto-selected. If no default is set (not Required and not DefaultYes), defaults to "no".

Confirm("Continue?", Timeout(30*time.Second))  // Auto-no after 30s
Confirm("Continue?", DefaultYes(), Timeout(10*time.Second))  // Auto-yes after 10s

type Daemon

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

Daemon manages daemon lifecycle.

func NewDaemon

func NewDaemon(opts DaemonOptions) *Daemon

NewDaemon creates a daemon runner with the given options.

func (*Daemon) HealthAddr

func (d *Daemon) HealthAddr() string

HealthAddr returns the health server address, or empty if disabled.

func (*Daemon) Run

func (d *Daemon) Run(ctx context.Context) error

Run blocks until the context is cancelled or a signal is received. Handles graceful shutdown with the configured timeout.

func (*Daemon) SetReady

func (d *Daemon) SetReady(ready bool)

SetReady sets the daemon readiness status for health checks.

func (*Daemon) Start

func (d *Daemon) Start() error

Start initialises the daemon (PID file, health server). Call this after cli.Init().

func (*Daemon) Stop

func (d *Daemon) Stop() error

Stop performs graceful shutdown.

type DaemonOptions

type DaemonOptions struct {
	// PIDFile path for single-instance enforcement.
	// Leave empty to skip PID file management.
	PIDFile string

	// ShutdownTimeout is the maximum time to wait for graceful shutdown.
	// Default: 30 seconds.
	ShutdownTimeout time.Duration

	// HealthAddr is the address for health check endpoints.
	// Example: ":8080", "127.0.0.1:9000"
	// Leave empty to disable health checks.
	HealthAddr string

	// HealthChecks are additional health check functions.
	HealthChecks []HealthCheck

	// OnReload is called when SIGHUP is received.
	// Use for config reloading. Leave nil to ignore SIGHUP.
	OnReload func() error
}

DaemonOptions configures daemon mode execution.

type ExitError

type ExitError struct {
	Code int
	Err  error
}

ExitError represents an error that should cause the CLI to exit with a specific code.

func (*ExitError) Error

func (e *ExitError) Error() string

func (*ExitError) Unwrap

func (e *ExitError) Unwrap() error

type Frame

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

Frame is a live compositional AppShell for TUI. Uses HLCRF variant strings for region layout — same as the static Layout system, but with live-updating Model components instead of static strings.

frame := cli.NewFrame("HCF")
frame.Header(cli.StatusLine("core dev", "18 repos", "main"))
frame.Content(myTableModel)
frame.Footer(cli.KeyHints("↑/↓ navigate", "enter select", "q quit"))
frame.Run()

func NewFrame

func NewFrame(variant string) *Frame

NewFrame creates a new Frame with the given HLCRF variant string.

frame := cli.NewFrame("HCF")      // header, content, footer
frame := cli.NewFrame("H[LC]F")   // header, [left + content], footer

func (*Frame) Back

func (f *Frame) Back() bool

Back pops the content history stack, restoring the previous Content model. Returns false if the history is empty.

func (*Frame) Content

func (f *Frame) Content(m Model) *Frame

Content sets the Content region model.

func (*Frame) Focus

func (f *Frame) Focus(r Region)

Focus sets focus to a specific region. Ignores the request if the region is not in this Frame's variant.

func (*Frame) Focused

func (f *Frame) Focused() Region

Focused returns the currently focused region.

func (*Frame) Footer

func (f *Frame) Footer(m Model) *Frame

Footer sets the Footer region model.

func (*Frame) Header

func (f *Frame) Header(m Model) *Frame

Header sets the Header region model.

func (*Frame) Init

func (f *Frame) Init() tea.Cmd

Init implements tea.Model. Collects Init() from all FrameModel regions.

func (*Frame) Left

func (f *Frame) Left(m Model) *Frame

Left sets the Left sidebar region model.

func (*Frame) Navigate

func (f *Frame) Navigate(m Model)

Navigate replaces the Content region with a new model, pushing the current one onto the history stack for Back().

func (*Frame) Right

func (f *Frame) Right(m Model) *Frame

Right sets the Right sidebar region model.

func (*Frame) Run

func (f *Frame) Run()

Run renders the frame and blocks. In TTY mode, it live-refreshes at ~12fps. In non-TTY mode, it renders once and returns immediately.

func (*Frame) RunFor

func (f *Frame) RunFor(d time.Duration)

RunFor runs the frame for a fixed duration, then stops. Useful for dashboards that refresh periodically.

func (*Frame) Send

func (f *Frame) Send(msg tea.Msg)

Send injects a message into the Frame's tea.Program. Safe to call before Run() (message is discarded).

func (*Frame) Stop

func (f *Frame) Stop()

Stop signals the Frame to exit its Run loop.

func (*Frame) String

func (f *Frame) String() string

String renders the frame as a static string (no ANSI, no live updates). This is the non-TTY fallback path.

func (*Frame) Update

func (f *Frame) Update(msg tea.Msg) (tea.Model, tea.Cmd)

Update implements tea.Model. Routes messages based on type and focus.

func (*Frame) View

func (f *Frame) View() string

View implements tea.Model. Composes region views using lipgloss.

func (*Frame) WithKeyMap

func (f *Frame) WithKeyMap(km KeyMap) *Frame

WithKeyMap sets custom key bindings for Frame navigation.

type FrameModel

type FrameModel interface {
	Model
	Init() tea.Cmd
	Update(tea.Msg) (FrameModel, tea.Cmd)
}

FrameModel extends Model with bubbletea lifecycle methods. Use this for interactive components that handle input. Plain Model components work unchanged — Frame wraps them automatically.

type GlyphTheme

type GlyphTheme int

GlyphTheme defines which symbols to use.

const (
	// ThemeUnicode uses standard Unicode symbols.
	ThemeUnicode GlyphTheme = iota
	// ThemeEmoji uses Emoji symbols.
	ThemeEmoji
	// ThemeASCII uses ASCII fallback symbols.
	ThemeASCII
)

type HealthCheck

type HealthCheck func() error

HealthCheck is a function that returns nil if healthy.

type HealthServer

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

HealthServer provides a minimal HTTP health check endpoint.

func NewHealthServer

func NewHealthServer(addr string) *HealthServer

NewHealthServer creates a health check server.

func (*HealthServer) AddCheck

func (h *HealthServer) AddCheck(check HealthCheck)

AddCheck registers a health check function.

func (*HealthServer) Addr

func (h *HealthServer) Addr() string

Addr returns the actual address the server is listening on. Useful when using port 0 for dynamic port assignment.

func (*HealthServer) SetReady

func (h *HealthServer) SetReady(ready bool)

SetReady sets the readiness status.

func (*HealthServer) Start

func (h *HealthServer) Start() error

Start begins serving health check endpoints. Endpoints:

  • /health - liveness probe (always 200 if server is up)
  • /ready - readiness probe (200 if ready, 503 if not)

func (*HealthServer) Stop

func (h *HealthServer) Stop(ctx context.Context) error

Stop gracefully shuts down the health server.

type I18nOptions

type I18nOptions struct {
	// Language overrides auto-detection (e.g., "en-GB", "de")
	Language string
	// Mode sets the translation mode (Normal, Strict, Collect)
	Mode i18n.Mode
}

I18nOptions configures the i18n service.

type I18nService

type I18nService struct {
	*framework.ServiceRuntime[I18nOptions]
	// contains filtered or unexported fields
}

I18nService wraps i18n as a Core service.

func (*I18nService) AvailableLanguages

func (s *I18nService) AvailableLanguages() []string

AvailableLanguages returns all available languages.

func (*I18nService) ClearMissingKeys

func (s *I18nService) ClearMissingKeys()

ClearMissingKeys resets the collected missing keys.

func (*I18nService) Language

func (s *I18nService) Language() string

Language returns the current language.

func (*I18nService) MissingKeys

func (s *I18nService) MissingKeys() []i18n.MissingKey

MissingKeys returns all missing keys collected in collect mode. Call this at the end of a QA session to report missing translations.

func (*I18nService) Mode

func (s *I18nService) Mode() i18n.Mode

Mode returns the current translation mode.

func (*I18nService) OnStartup

func (s *I18nService) OnStartup(ctx context.Context) error

OnStartup initialises the i18n service.

func (*I18nService) SetLanguage

func (s *I18nService) SetLanguage(lang string)

SetLanguage changes the current language.

func (*I18nService) SetMode

func (s *I18nService) SetMode(mode i18n.Mode)

SetMode changes the translation mode.

func (*I18nService) T

func (s *I18nService) T(key string, args ...map[string]any) string

T translates a key with optional arguments.

type KeyMap

type KeyMap struct {
	FocusNext  tea.KeyType // Tab — cycle focus forward
	FocusPrev  tea.KeyType // Shift-Tab — cycle focus backward
	FocusUp    tea.KeyType // Up — spatial: move to Header
	FocusDown  tea.KeyType // Down — spatial: move to Footer
	FocusLeft  tea.KeyType // Left — spatial: move to Left sidebar
	FocusRight tea.KeyType // Right — spatial: move to Right sidebar
	Back       tea.KeyType // Esc — Navigate back
	Quit       tea.KeyType // Ctrl-C — quit
}

KeyMap defines key bindings for Frame navigation. Use DefaultKeyMap() for sensible defaults, or build your own.

func DefaultKeyMap

func DefaultKeyMap() KeyMap

DefaultKeyMap returns the standard Frame key bindings.

type LogLevel

type LogLevel = log.Level

LogLevel aliases for backwards compatibility.

type LogOptions

type LogOptions = log.Options

LogOptions configures the log service.

type LogService

type LogService struct {
	*log.Service
}

LogService wraps log.Service with CLI styling.

func Log

func Log() *LogService

Log returns the CLI's log service, or nil if not available.

type Mode

type Mode int

Mode represents the CLI execution mode.

const (
	// ModeInteractive indicates TTY attached with coloured output.
	ModeInteractive Mode = iota
	// ModePipe indicates stdout is piped, colours disabled.
	ModePipe
	// ModeDaemon indicates headless execution, log-only output.
	ModeDaemon
)

func DetectMode

func DetectMode() Mode

DetectMode determines the execution mode based on environment. Checks CORE_DAEMON env var first, then TTY status.

func (Mode) String

func (m Mode) String() string

String returns the string representation of the Mode.

type Model

type Model interface {
	View(width, height int) string
}

Model is the interface for components that slot into Frame regions. View receives the allocated width and height and returns rendered text.

func Breadcrumb(parts ...string) Model

Breadcrumb creates a navigation breadcrumb bar.

frame.Header(cli.Breadcrumb("core", "dev", "health"))

func KeyHints

func KeyHints(hints ...string) Model

KeyHints creates a footer showing keyboard shortcuts.

frame.Footer(cli.KeyHints("↑/↓ navigate", "enter select", "q quit"))

func StaticModel

func StaticModel(text string) Model

StaticModel wraps a static string as a Model, for use in Frame regions.

func StatusLine

func StatusLine(title string, pairs ...string) Model

StatusLine creates a header/footer bar with a title and key:value pairs.

frame.Header(cli.StatusLine("core dev", "18 repos", "main"))

type ModelFunc

type ModelFunc func(width, height int) string

ModelFunc is a convenience adapter for using a function as a Model.

func (ModelFunc) View

func (f ModelFunc) View(width, height int) string

View implements Model.

type Options

type Options struct {
	AppName  string
	Version  string
	Services []framework.Option // Additional services to register

	// OnReload is called when SIGHUP is received (daemon mode).
	// Use for configuration reloading. Leave nil to ignore SIGHUP.
	OnReload func() error
}

Options configures the CLI runtime.

type PIDFile

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

PIDFile manages a process ID file for single-instance enforcement.

func NewPIDFile

func NewPIDFile(path string) *PIDFile

NewPIDFile creates a PID file manager.

func (*PIDFile) Acquire

func (p *PIDFile) Acquire() error

Acquire writes the current PID to the file. Returns error if another instance is running.

func (*PIDFile) Path

func (p *PIDFile) Path() string

Path returns the PID file path.

func (*PIDFile) Release

func (p *PIDFile) Release() error

Release removes the PID file.

type PositionalArgs added in v0.0.2

type PositionalArgs = cobra.PositionalArgs

PositionalArgs is the cobra positional args type.

type QueryTranslate

type QueryTranslate struct {
	Key  string
	Args map[string]any
}

QueryTranslate requests a translation.

type QuestionOption

type QuestionOption func(*questionConfig)

QuestionOption configures Question behaviour.

func RequiredInput

func RequiredInput() QuestionOption

RequiredInput prevents empty responses.

func WithDefault

func WithDefault(value string) QuestionOption

WithDefault sets the default value shown in brackets.

func WithValidator

func WithValidator(fn func(string) error) QuestionOption

WithValidator adds a validation function for the response.

type Region

type Region rune

Region represents one of the 5 HLCRF regions.

const (
	// RegionHeader is the top region of the layout.
	RegionHeader Region = 'H'
	// RegionLeft is the left sidebar region.
	RegionLeft Region = 'L'
	// RegionContent is the main content region.
	RegionContent Region = 'C'
	// RegionRight is the right sidebar region.
	RegionRight Region = 'R'
	// RegionFooter is the bottom region of the layout.
	RegionFooter Region = 'F'
)

type RenderStyle

type RenderStyle int

RenderStyle controls how layouts are rendered.

const (
	// RenderFlat uses no borders or decorations.
	RenderFlat RenderStyle = iota
	// RenderSimple uses --- separators between sections.
	RenderSimple
	// RenderBoxed uses Unicode box drawing characters.
	RenderBoxed
)

Render style constants for layout output.

type Renderable

type Renderable interface {
	Render() string
}

Renderable is anything that can be rendered to terminal.

type SignalOption

type SignalOption func(*signalService)

SignalOption configures signal handling.

func WithReloadHandler

func WithReloadHandler(fn func() error) SignalOption

WithReloadHandler sets a callback for SIGHUP.

type Slot

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

Slot holds content for a region.

type Stream

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

Stream renders growing text as tokens arrive, with optional word-wrap. Safe for concurrent writes from a single producer goroutine.

stream := cli.NewStream(cli.WithWordWrap(80))
go func() {
    for token := range tokens {
        stream.Write(token)
    }
    stream.Done()
}()
stream.Wait()

func NewStream

func NewStream(opts ...StreamOption) *Stream

NewStream creates a streaming text renderer.

func (*Stream) Captured

func (s *Stream) Captured() string

Captured returns the stream output as a string when using a bytes.Buffer. Panics if the output writer is not a *strings.Builder or fmt.Stringer.

func (*Stream) Column

func (s *Stream) Column() int

Content returns the current column position (for testing).

func (*Stream) Done

func (s *Stream) Done()

Done signals that no more text will arrive.

func (*Stream) Wait

func (s *Stream) Wait()

Wait blocks until Done is called.

func (*Stream) Write

func (s *Stream) Write(text string)

Write appends text to the stream. Handles word-wrap if configured.

func (*Stream) WriteFrom

func (s *Stream) WriteFrom(r io.Reader) error

WriteFrom reads from r and streams all content until EOF.

type StreamOption

type StreamOption func(*Stream)

StreamOption configures a Stream.

func WithStreamOutput

func WithStreamOutput(w io.Writer) StreamOption

WithStreamOutput sets the output writer (default: os.Stdout).

func WithWordWrap

func WithWordWrap(cols int) StreamOption

WithWordWrap sets the word-wrap column width.

type StringBlock

type StringBlock string

StringBlock is a simple string that implements Renderable.

func (StringBlock) Render

func (s StringBlock) Render() string

Render returns the string content.

type Table

type Table struct {
	Headers []string
	Rows    [][]string
	Style   TableStyle
	// contains filtered or unexported fields
}

Table renders tabular data with aligned columns. Supports optional box-drawing borders and per-column cell styling.

t := cli.NewTable("REPO", "STATUS", "BRANCH").
    WithBorders(cli.BorderRounded).
    WithCellStyle(1, func(val string) *cli.AnsiStyle {
        if val == "clean" { return cli.SuccessStyle }
        return cli.WarningStyle
    })
t.AddRow("core-php", "clean", "main")
t.Render()

func NewTable

func NewTable(headers ...string) *Table

NewTable creates a table with headers.

func (*Table) AddRow

func (t *Table) AddRow(cells ...string) *Table

AddRow adds a row to the table.

func (*Table) Render

func (t *Table) Render()

Render prints the table to stdout.

func (*Table) String

func (t *Table) String() string

String renders the table.

func (*Table) WithBorders

func (t *Table) WithBorders(style BorderStyle) *Table

WithBorders enables box-drawing borders on the table.

func (*Table) WithCellStyle

func (t *Table) WithCellStyle(col int, fn CellStyleFn) *Table

WithCellStyle sets a per-column style function. The function receives the raw cell value and returns a style.

func (*Table) WithMaxWidth

func (t *Table) WithMaxWidth(w int) *Table

WithMaxWidth sets the maximum table width, truncating columns to fit.

type TableStyle

type TableStyle struct {
	HeaderStyle *AnsiStyle
	CellStyle   *AnsiStyle
	Separator   string
}

TableStyle configures the appearance of table output.

func DefaultTableStyle

func DefaultTableStyle() TableStyle

DefaultTableStyle returns sensible defaults.

type TaskTracker

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

TaskTracker displays multiple concurrent tasks with individual spinners.

tracker := cli.NewTaskTracker()
for _, repo := range repos {
    t := tracker.Add(repo.Name)
    go func(t *cli.TrackedTask) {
        t.Update("pulling...")
        // ...
        t.Done("up to date")
    }(t)
}
tracker.Wait()

func NewTaskTracker

func NewTaskTracker() *TaskTracker

NewTaskTracker creates a new parallel task tracker.

func (*TaskTracker) Add

func (tr *TaskTracker) Add(name string) *TrackedTask

Add registers a task and returns it for goroutine use.

func (*TaskTracker) Snapshots added in v0.0.3

func (tr *TaskTracker) Snapshots() iter.Seq2[string, string]

Snapshots returns an iterator over snapshots of tasks in the tracker.

func (*TaskTracker) String

func (tr *TaskTracker) String() string

String returns the current state of all tasks as plain text (no ANSI).

func (*TaskTracker) Summary

func (tr *TaskTracker) Summary() string

Summary returns a one-line summary of task results.

func (*TaskTracker) Tasks added in v0.0.3

func (tr *TaskTracker) Tasks() iter.Seq[*TrackedTask]

Tasks returns an iterator over the tasks in the tracker.

func (*TaskTracker) Wait

func (tr *TaskTracker) Wait()

Wait renders the task display and blocks until all tasks complete. Uses ANSI cursor manipulation for live updates when connected to a terminal. Falls back to line-by-line output for non-TTY.

type TrackedTask

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

TrackedTask represents a single task in a TaskTracker. Safe for concurrent use — call Update, Done, or Fail from any goroutine.

func (*TrackedTask) Done

func (t *TrackedTask) Done(message string)

Done marks the task as successfully completed with a final message.

func (*TrackedTask) Fail

func (t *TrackedTask) Fail(message string)

Fail marks the task as failed with an error message.

func (*TrackedTask) Update

func (t *TrackedTask) Update(status string)

Update sets the task status message and marks it as running.

type TreeNode

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

TreeNode represents a node in a displayable tree structure. Use NewTree to create a root, then Add children.

tree := cli.NewTree("core-php")
tree.Add("core-tenant").Add("core-bio")
tree.Add("core-admin")
tree.Add("core-api")
fmt.Print(tree)
// core-php
// ├── core-tenant
// │   └── core-bio
// ├── core-admin
// └── core-api

func NewTree

func NewTree(label string) *TreeNode

NewTree creates a new tree with the given root label.

func (*TreeNode) Add

func (n *TreeNode) Add(label string) *TreeNode

Add appends a child node and returns the child for chaining.

func (*TreeNode) AddStyled

func (n *TreeNode) AddStyled(label string, style *AnsiStyle) *TreeNode

AddStyled appends a styled child node and returns the child for chaining.

func (*TreeNode) AddTree

func (n *TreeNode) AddTree(child *TreeNode) *TreeNode

AddTree appends an existing tree as a child and returns the parent for chaining.

func (*TreeNode) Children added in v0.0.3

func (n *TreeNode) Children() iter.Seq[*TreeNode]

Children returns an iterator over the node's children.

func (*TreeNode) Render

func (n *TreeNode) Render()

Render prints the tree to stdout.

func (*TreeNode) String

func (n *TreeNode) String() string

String renders the tree with box-drawing characters. Implements fmt.Stringer.

func (*TreeNode) WithStyle

func (n *TreeNode) WithStyle(style *AnsiStyle) *TreeNode

WithStyle sets the style on this node and returns it for chaining.

Jump to

Keyboard shortcuts

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