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
- Variables
- func ArbitraryArgs() cobra.PositionalArgs
- func As(err error, target any) bool
- func Blank()
- func BoolFlag(cmd *Command, ptr *bool, name, short string, def bool, usage string)
- func Choose[T any](prompt string, items []T, opts ...ChooseOption[T]) T
- func ChooseAction[T any](verb, subject string, items []T, opts ...ChooseOption[T]) T
- func ChooseMulti[T any](prompt string, items []T, opts ...ChooseOption[T]) []T
- func ChooseMultiAction[T any](verb, subject string, items []T, opts ...ChooseOption[T]) []T
- func ColorEnabled() bool
- func Confirm(prompt string, opts ...ConfirmOption) bool
- func ConfirmAction(verb, subject string, opts ...ConfirmOption) bool
- func ConfirmDangerousAction(verb, subject string) bool
- func Context() context.Context
- func Core() *framework.Core
- func Dim(msg string)
- func DimStr(msg string) string
- func Echo(key string, args ...any)
- func Err(format string, args ...any) error
- func Error(msg string)
- func ErrorStr(msg string) string
- func Errorf(format string, args ...any)
- func ExactArgs(n int) cobra.PositionalArgs
- func Execute() error
- func Fatal(err error)
- func FatalWrap(err error, msg string)
- func FatalWrapVerb(err error, verb, subject string)
- func Fatalf(format string, args ...any)
- func FormatAge(t time.Time) string
- func GhAuthenticated() bool
- func GitClone(ctx context.Context, org, repo, path string) error
- func Glyph(code string) string
- func Hint(label, message string)
- func Info(msg string)
- func InfoStr(msg string) string
- func Infof(format string, args ...any)
- func Init(opts Options) error
- func IntFlag(cmd *Command, ptr *int, name, short string, def int, usage string)
- func Is(err, target error) bool
- func IsStderrTTY() bool
- func IsStdinTTY() bool
- func IsTTY() bool
- func Join(errs ...error) error
- func Label(word, value string)
- func LogDebug(msg string)
- func LogError(msg string)
- func LogInfo(msg string)
- func LogWarn(msg string)
- func Main()
- func MaximumNArgs(n int) cobra.PositionalArgs
- func MinimumNArgs(n int) cobra.PositionalArgs
- func MultiSelect(label string, options []string) ([]string, error)
- func NewI18nService(opts I18nOptions) func(*framework.Core) (any, error)
- func NewLogService(opts LogOptions) func(*framework.Core) (any, error)
- func NoArgs() cobra.PositionalArgs
- func Pad(s string, width int) string
- func PersistentBoolFlag(cmd *Command, ptr *bool, name, short string, def bool, usage string)
- func PersistentStringFlag(cmd *Command, ptr *string, name, short, def, usage string)
- func Print(format string, args ...any)
- func Println(format string, args ...any)
- func Progress(verb string, current, total int, item ...string)
- func ProgressDone()
- func Prompt(label, defaultVal string) (string, error)
- func Question(prompt string, opts ...QuestionOption) string
- func QuestionAction(verb, subject string, opts ...QuestionOption) string
- func RegisterCommands(fn CommandRegistration)
- func Result(passed bool, message string)
- func RootCmd() *cobra.Command
- func Run(ctx context.Context) error
- func RunWithTimeout(timeout time.Duration) func()
- func Scanln(a ...any) (int, error)
- func Section(name string)
- func Select(label string, options []string) (string, error)
- func SetColorEnabled(enabled bool)
- func Severity(level, message string)
- func Shutdown()
- func Sprint(args ...any) string
- func Sprintf(format string, args ...any) string
- func StringFlag(cmd *Command, ptr *string, name, short, def, usage string)
- func StringSliceFlag(cmd *Command, ptr *[]string, name, short string, def []string, usage string)
- func Styled(style *AnsiStyle, text string) string
- func Styledf(style *AnsiStyle, format string, args ...any) string
- func Success(msg string)
- func SuccessStr(msg string) string
- func Successf(format string, args ...any)
- func T(key string, args ...map[string]any) string
- func Task(label, message string)
- func Text(args ...any)
- func Truncate(s string, max int) string
- func UseASCII()
- func UseEmoji()
- func UseRenderBoxed()
- func UseRenderFlat()
- func UseRenderSimple()
- func UseUnicode()
- func Warn(msg string)
- func WarnStr(msg string) string
- func Warnf(format string, args ...any)
- func Wrap(err error, msg string) error
- func WrapAction(err error, verb string) error
- func WrapVerb(err error, verb, subject string) error
- type AnsiStyle
- func (s *AnsiStyle) Background(hex string) *AnsiStyle
- func (s *AnsiStyle) Bold() *AnsiStyle
- func (s *AnsiStyle) Dim() *AnsiStyle
- func (s *AnsiStyle) Foreground(hex string) *AnsiStyle
- func (s *AnsiStyle) Italic() *AnsiStyle
- func (s *AnsiStyle) Render(text string) string
- func (s *AnsiStyle) Underline() *AnsiStyle
- type CheckBuilder
- func (c *CheckBuilder) Duration(d string) *CheckBuilder
- func (c *CheckBuilder) Fail() *CheckBuilder
- func (c *CheckBuilder) Message(msg string) *CheckBuilder
- func (c *CheckBuilder) Pass() *CheckBuilder
- func (c *CheckBuilder) Print()
- func (c *CheckBuilder) Skip() *CheckBuilder
- func (c *CheckBuilder) String() string
- func (c *CheckBuilder) Warn() *CheckBuilder
- type ChooseOption
- type Command
- func NewCommand(use, short, long string, run func(cmd *Command, args []string) error) *Command
- func NewGroup(use, short, long string) *Command
- func NewRun(use, short, long string, run func(cmd *Command, args []string)) *Command
- func WithArgs(cmd *Command, args cobra.PositionalArgs) *Command
- func WithExample(cmd *Command, example string) *Command
- type CommandRegistration
- type Composite
- type ConfirmOption
- type Daemon
- type DaemonOptions
- type GlyphTheme
- type HealthCheck
- type HealthServer
- type I18nOptions
- type I18nService
- func (s *I18nService) AvailableLanguages() []string
- func (s *I18nService) ClearMissingKeys()
- func (s *I18nService) Language() string
- func (s *I18nService) MissingKeys() []i18n.MissingKey
- func (s *I18nService) Mode() i18n.Mode
- func (s *I18nService) OnStartup(ctx context.Context) error
- func (s *I18nService) SetLanguage(lang string)
- func (s *I18nService) SetMode(mode i18n.Mode)
- func (s *I18nService) T(key string, args ...map[string]any) string
- type LogLevel
- type LogOptions
- type LogService
- type Mode
- type Options
- type PIDFile
- type QueryTranslate
- type QuestionOption
- type Region
- type RenderStyle
- type Renderable
- type SignalOption
- type Slot
- type StringBlock
- type Table
- type TableStyle
Constants ¶
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.
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)
const (
// AppName is the CLI application name.
AppName = "core"
)
Variables ¶
var ( SuccessStyle = NewStyle().Bold().Foreground(ColourGreen500) ErrorStyle = NewStyle().Bold().Foreground(ColourRed500) WarningStyle = NewStyle().Bold().Foreground(ColourAmber500) InfoStyle = NewStyle().Foreground(ColourBlue400) 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
var AppVersion = "dev"
AppVersion is set at build time via ldflags:
go build -ldflags="-X github.com/host-uk/core/pkg/cli.AppVersion=v1.0.0"
Functions ¶
func ArbitraryArgs ¶
func ArbitraryArgs() cobra.PositionalArgs
ArbitraryArgs returns a PositionalArgs that accepts any arguments.
func As ¶
As finds the first error in err's tree that matches target. This is a re-export of errors.As for convenience.
func BoolFlag ¶
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 ¶ added in v0.0.4
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 ¶
ConfirmDangerousAction prompts for double confirmation of a dangerous action. Shows initial question, then a "Really verb subject?" confirmation.
if ConfirmDangerousAction("delete", "config.yaml") { ... }
func Echo ¶ added in v0.0.3
Echo translates a key via i18n.T and prints with newline. No automatic styling - use Success/Error/Warn/Info for styled output.
func Err ¶
Err creates a new error from a format string. This is a direct replacement for fmt.Errorf.
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 FatalWrap ¶
FatalWrap prints a wrapped error message and exits with code 1. Does nothing if err is nil.
cli.FatalWrap(err, "load config") // Prints "✗ load config: <error>" and exits
func FatalWrapVerb ¶
FatalWrapVerb prints a wrapped error using i18n grammar and exits with code 1. Does nothing if err is nil.
cli.FatalWrapVerb(err, "load", "config") // Prints "✗ Failed to load config: <error>" and exits
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 ¶
GitClone clones a GitHub repository to the specified path. Prefers 'gh repo clone' if authenticated, falls back to SSH.
func Glyph ¶ added in v0.0.3
Glyph converts a shortcode (e.g. ":check:") to its symbol based on the current theme.
func Hint ¶ added in v0.0.3
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 Init ¶
Init initialises the global CLI runtime. Call this once at startup (typically in main.go or cmd.Execute).
func IntFlag ¶
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 ¶
Is reports whether any error in err's tree matches target. This is a re-export of errors.Is for convenience.
func Join ¶
Join returns an error that wraps the given errors. This is a re-export of errors.Join for convenience.
func LogDebug ¶
func LogDebug(msg string)
LogDebug logs a debug message if log service is available.
func LogError ¶
func LogError(msg string)
LogError logs an error message if log service is available.
func Main ¶
func Main()
Main initialises and runs the CLI application. This is the main entry point for the CLI. Exits with code 1 on error.
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 ¶ added in v0.0.3
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 PersistentBoolFlag ¶
PersistentBoolFlag adds a persistent boolean flag (inherited by subcommands).
func PersistentStringFlag ¶
PersistentStringFlag adds a persistent string flag (inherited by subcommands).
func Print ¶ added in v0.0.3
Print outputs formatted text (no newline). Glyph shortcodes like :check: are converted.
func Println ¶ added in v0.0.3
Println outputs formatted text with newline. Glyph shortcodes like :check: are converted.
func Progress ¶ added in v0.0.3
Progress prints a progress indicator that overwrites the current line. Uses i18n.Progress for gerund form ("Checking...").
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 Result ¶ added in v0.0.3
Result prints a result line: "✓ message" or "✗ message"
cli.Result(passed, "All tests passed") cli.Result(false, "3 tests failed")
func Run ¶
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 ¶
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 Section ¶ added in v0.0.3
func Section(name string)
Section prints a section header: "── SECTION ──"
cli.Section("audit") // ── AUDIT ──
func SetColorEnabled ¶ added in v0.0.4
func SetColorEnabled(enabled bool)
SetColorEnabled enables or disables ANSI color output. This overrides the NO_COLOR environment variable check.
func Severity ¶ added in v0.0.3
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 StringFlag ¶
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 ¶
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 T ¶
T translates a key using the CLI's i18n service. Falls back to the global i18n.T if CLI not initialised.
func Task ¶ added in v0.0.3
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 ¶ added in v0.0.3
func Text(args ...any)
Text prints arguments like fmt.Println, but handling glyphs.
func UseASCII ¶ added in v0.0.3
func UseASCII()
UseASCII switches the glyph theme to ASCII and disables colors.
func UseRenderBoxed ¶ added in v0.0.3
func UseRenderBoxed()
UseRenderBoxed sets the render style to boxed (Unicode box drawing).
func UseRenderFlat ¶ added in v0.0.3
func UseRenderFlat()
UseRenderFlat sets the render style to flat (no borders).
func UseRenderSimple ¶ added in v0.0.3
func UseRenderSimple()
UseRenderSimple sets the render style to simple (--- separators).
func Warn ¶ added in v0.0.3
func Warn(msg string)
Warn prints a warning message with warning symbol (amber).
func Wrap ¶
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 ¶
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>"
Types ¶
type AnsiStyle ¶ added in v0.0.3
type AnsiStyle struct {
// contains filtered or unexported fields
}
AnsiStyle represents terminal text styling. Use NewStyle() to create, chain methods, call Render().
func (*AnsiStyle) Background ¶ added in v0.0.3
Background sets background color from hex string.
func (*AnsiStyle) Foreground ¶ added in v0.0.3
Foreground sets foreground color from hex string.
type CheckBuilder ¶ added in v0.0.3
type CheckBuilder struct {
// contains filtered or unexported fields
}
CheckBuilder provides fluent API for check results.
func Check ¶ added in v0.0.3
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 ¶ added in v0.0.3
func (c *CheckBuilder) Duration(d string) *CheckBuilder
Duration adds duration to the check result.
func (*CheckBuilder) Fail ¶ added in v0.0.3
func (c *CheckBuilder) Fail() *CheckBuilder
Fail marks the check as failed.
func (*CheckBuilder) Message ¶ added in v0.0.3
func (c *CheckBuilder) Message(msg string) *CheckBuilder
Message adds a custom message instead of status.
func (*CheckBuilder) Pass ¶ added in v0.0.3
func (c *CheckBuilder) Pass() *CheckBuilder
Pass marks the check as passed.
func (*CheckBuilder) Print ¶ added in v0.0.3
func (c *CheckBuilder) Print()
Print outputs the check result.
func (*CheckBuilder) Skip ¶ added in v0.0.3
func (c *CheckBuilder) Skip() *CheckBuilder
Skip marks the check as skipped.
func (*CheckBuilder) String ¶ added in v0.0.3
func (c *CheckBuilder) String() string
String returns the formatted check line.
func (*CheckBuilder) Warn ¶ added in v0.0.3
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 ¶
Command is the cobra command type. Re-exported for convenience so packages don't need to import cobra directly.
func NewCommand ¶
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 ¶
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 ¶
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 ¶
WithExample sets the Example field for a command. Returns the command for chaining.
type CommandRegistration ¶
CommandRegistration is a function that adds commands to the root.
type Composite ¶ added in v0.0.3
type Composite struct {
// contains filtered or unexported fields
}
Composite represents an HLCRF layout node.
func ParseVariant ¶ added in v0.0.3
ParseVariant parses a variant string like "H[LC]C[HCF]F".
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 ¶
HealthAddr returns the health server address, or empty if disabled.
func (*Daemon) Run ¶
Run blocks until the context is cancelled or a signal is received. Handles graceful shutdown with the configured timeout.
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 GlyphTheme ¶ added in v0.0.3
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)
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.
type LogService ¶
LogService wraps log.Service with CLI styling.
type Mode ¶
type Mode int
Mode represents the CLI execution mode.
func DetectMode ¶
func DetectMode() Mode
DetectMode determines the execution mode based on environment. Checks CORE_DAEMON env var first, then TTY status.
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.
type QueryTranslate ¶
QueryTranslate requests a translation.
type QuestionOption ¶
type QuestionOption func(*questionConfig)
QuestionOption configures Question behaviour.
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 ¶ added in v0.0.3
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 Region = 'F' )
type RenderStyle ¶ added in v0.0.3
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 ¶ added in v0.0.3
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 ¶ added in v0.0.3
type Slot struct {
// contains filtered or unexported fields
}
Slot holds content for a region.
type StringBlock ¶ added in v0.0.3
type StringBlock string
StringBlock is a simple string that implements Renderable.
func (StringBlock) Render ¶ added in v0.0.3
func (s StringBlock) Render() string
Render returns the string content.
type Table ¶
type Table struct {
Headers []string
Rows [][]string
Style TableStyle
}
Table renders tabular data with aligned columns. HLCRF is for layout; Table is for tabular data - they serve different purposes.
type TableStyle ¶ added in v0.0.3
TableStyle configures the appearance of table output.
func DefaultTableStyle ¶ added in v0.0.3
func DefaultTableStyle() TableStyle
DefaultTableStyle returns sensible defaults.