tui

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2025 License: GPL-2.0 Imports: 15 Imported by: 0

README

PlanetUI

PlanetUI is a composable terminal user interface (TUI) framework for Go. It extends the original minimal command loop with structured command metadata, lifecycle hooks, dependency injection, context navigation, typed argument parsing, output management, and background task execution—while preserving compatibility with legacy commands.

Features

  • Structured commands with CommandSpec, rich metadata, aliases, tags, and auto-generated usage strings
  • Lifecycle + middleware support so authentication, logging, and validation run consistently before/after commands
  • Built-in argument parsing using declarative ArgSpec/FlagSpec with typed accessors
  • Context manager providing hierarchical navigation, alias resolution, and payload/state passing
  • Session + services stores for sharing data and dependencies across commands
  • Async/background tasks with cancellation, progress output, and task inspection
  • Output channels enabling leveled messaging, JSON/table rendering, and test-friendly capture
  • Legacy compatibility through RegisterLegacyCommand adapters so existing commands keep working

Installation

go get github.com/network-plane/planetui

Quick Start

package main

import (
    "log"

    "github.com/chzyer/readline"
    tui "github.com/network-plane/planetui"
)

type helloFactory struct {
    spec tui.CommandSpec
}

type helloCommand struct {
    spec tui.CommandSpec
}

func newHelloFactory() tui.CommandFactory {
    spec := tui.CommandSpec{
        Name:        "hello",
        Summary:     "Print a greeting",
        Description: "Outputs a greeting and optional name.",
        Context:     "demo",
        Args: []tui.ArgSpec{
            {Name: "name", Type: tui.ArgTypeString, Required: false, Description: "Name to greet"},
        },
    }
    return &helloFactory{spec: spec}
}

func (f *helloFactory) Spec() tui.CommandSpec { return f.spec }

func (f *helloFactory) New(rt tui.CommandRuntime) (tui.Command, error) {
    return &helloCommand{spec: f.spec}, nil
}

func (c *helloCommand) Spec() tui.CommandSpec { return c.spec }

func (c *helloCommand) Execute(rt tui.CommandRuntime, input tui.CommandInput) tui.CommandResult {
    name := input.Args.String("name")
    if name == "" {
        name = "world"
    }
    rt.Output().Info("hello " + name + "!")
    return tui.CommandResult{Status: tui.StatusSuccess}
}

func main() {
    rl, err := readline.NewEx(&readline.Config{})
    if err != nil {
        log.Fatal(err)
    }
    defer rl.Close()

    tui.RegisterContext("demo", "Example commands")
    tui.RegisterCommand(newHelloFactory())

    if err := tui.Run(rl); err != nil {
        log.Fatal(err)
    }
}

Working With Commands

  • Describe metadata in CommandSpec; PlanetUI uses it for help text, autocomplete, and validation.
  • Use CommandInput.Args/Flags typed helpers (String, Int, Bool, Duration, DecodeJSON, etc.).
  • Return a CommandResult to signal success, surface structured errors, pass pipeline payloads, or request context navigation.
  • Access shared session data via CommandRuntime.Session(), services via Services(), and spawn background work with TaskManager().Spawn.
  • Emit output through CommandRuntime.Output(); messages are automatically captured for tests and respect verbosity levels.
  • Register middleware with tui.UseMiddleware or when constructing a custom Engine to add logging, auth, timing, etc.

Migration from the Original Minimal TUI

The original planetui package exposed a very small surface area:

type Command interface {
    Name() string
    Help() string
    Exec(args []string)
}

func RegisterContext(name, description string)
func RegisterCommand(ctx string, cmd Command)
func Run(rl *readline.Instance)

Moving to the new framework provides far richer behaviour. The steps below help migrate existing apps incrementally:

  1. Wrap legacy commands (optional bridge). Call tui.RegisterLegacyCommand(ctx, legacyCmd) to keep using the old Command interface while you migrate. Legacy commands run exactly as before, but without access to new features.
  2. Adopt factories. Replace direct command instances with a CommandFactory that returns a fresh Command per execution. This unlocks dependency injection and isolates per-run state.
  3. Describe metadata. Implement Spec() CommandSpec on your command (and factory) to declare name, aliases, contexts, arguments, and flags. PlanetUI now drives help/autocomplete from the spec.
  4. Return results instead of printing. Change Exec implementations to Execute(rt, input) CommandResult. Use CommandResult.Status, Error, Messages, and Payload to communicate outcomes instead of calling fmt.Print directly.
  5. Use typed inputs. Replace manual []string parsing with input.Args/input.Flags based on the specs declared in step 3.
  6. Adopt runtime services. Access session storage, shared dependencies, output channels, context navigation, and task management through the provided CommandRuntime methods rather than global variables.
  7. Clean up legacy helpers. Once all commands implement the new interface, remove RegisterLegacyCommand calls and rely exclusively on RegisterCommand with factories.
Key API Changes
Legacy API New API
Command.Name/Help/Exec([]string) Command.Spec() CommandSpec + Execute(CommandRuntime, CommandInput)
RegisterCommand(ctx string, cmd Command) RegisterCommand(factory CommandFactory)
fmt.Print inside commands rt.Output().Info/Warn/Error/WriteJSON/WriteTable
currentCtx global / manual navigation rt.NavigateTo, rt.PushContext, rt.PopContext
No argument parsing helpers Declarative ArgSpec/FlagSpec + typed ValueSet access
No async support rt.TaskManager().Spawn with cancellation + inspection

Following these steps lets you layer the advanced command system on top of existing functionality without a flag-day rewrite.

Contributing

Contributions are always welcome! All contributions are required to follow the Google Go Style Guide.

Authors

License

I will always follow the Linux Kernel License as primary, if you require any other OPEN license please let me know and I will try to accomodate it.

License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AggregateMessages added in v1.0.1

func AggregateMessages(out OutputChannel, messages []OutputMessage)

AggregateMessages renders structured messages to an output channel.

func EnsureLineBreak added in v1.0.2

func EnsureLineBreak(out OutputChannel)

EnsureLineBreak guarantees the next prompt starts on a fresh line.

func FormatUsage added in v1.0.1

func FormatUsage(spec CommandSpec) string

FormatUsage renders a usage string from command spec.

func RegisterCommand

func RegisterCommand(factory CommandFactory)

RegisterCommand registers a command factory with the default engine.

func RegisterContext

func RegisterContext(name, description string, opts ...ContextOption)

RegisterContext registers a context with optional modifiers.

func RegisterLegacyCommand added in v1.0.1

func RegisterLegacyCommand(ctx string, cmd LegacyCommand)

RegisterLegacyCommand adapts a legacy command into the new runtime.

func ResetEngine added in v1.0.1

func ResetEngine(options ...Option)

ResetEngine replaces the default engine (primarily for tests).

func Run

func Run(rl *readline.Instance) error

Run starts the main loop using the default engine.

func SetHelpHeader

func SetHelpHeader(header string)

SetHelpHeader customises the help header for the default engine.

func SetOutputLevel added in v1.0.1

func SetOutputLevel(level OutputLevel)

SetOutputLevel adjusts default verbosity for the default engine.

func SetOutputWriter added in v1.0.1

func SetOutputWriter(w io.Writer) io.Writer

SetOutputWriter sets the writer used for command output, returning the previous writer.

func SetPrompt

func SetPrompt(prompt string)

SetPrompt customises the base prompt for the default engine.

func UseMiddleware added in v1.0.1

func UseMiddleware(mw ...Middleware)

UseMiddleware appends middleware to the default engine.

Types

type ArgSpec added in v1.0.1

type ArgSpec struct {
	Name        string
	Type        ArgType
	Required    bool
	Repeatable  bool
	Description string
	Default     any
	EnumValues  []string
}

ArgSpec defines positional argument metadata.

type ArgType added in v1.0.1

type ArgType string

ArgType enumerates supported argument data types.

const (
	ArgTypeString   ArgType = "string"
	ArgTypeInt      ArgType = "int"
	ArgTypeFloat    ArgType = "float"
	ArgTypeBool     ArgType = "bool"
	ArgTypeDuration ArgType = "duration"
	ArgTypeEnum     ArgType = "enum"
	ArgTypeJSON     ArgType = "json"
)

type ArgsParser added in v1.0.1

type ArgsParser struct{}

ArgsParser parses raw args into typed value sets according to specs.

func NewArgsParser added in v1.0.1

func NewArgsParser() *ArgsParser

NewArgsParser constructs an ArgsParser.

func (*ArgsParser) Parse added in v1.0.1

func (p *ArgsParser) Parse(raw []string, spec CommandSpec) (ValueSet, ValueSet, error)

Parse parses raw arguments with provided spec metadata.

type Command

type Command interface {
	Spec() CommandSpec
	Execute(rt CommandRuntime, input CommandInput) CommandResult
}

Command is the primary interface implemented by concrete commands.

type CommandEntry added in v1.0.1

type CommandEntry struct {
	Factory CommandFactory
	Spec    CommandSpec
}

CommandEntry stores command factory and resolved names.

type CommandError added in v1.0.1

type CommandError struct {
	Err         error
	Message     string
	Severity    SeverityLevel
	Hints       []string
	Recoverable bool
}

CommandError wraps an error with user facing metadata.

type CommandFactory added in v1.0.1

type CommandFactory interface {
	Spec() CommandSpec
	New(rt CommandRuntime) (Command, error)
}

CommandFactory builds command instances with access to runtime services.

func NewLegacyAdapter added in v1.0.1

func NewLegacyAdapter(cmd LegacyCommand, ctx string) CommandFactory

NewLegacyAdapter creates a CommandFactory from a legacy command.

type CommandInput added in v1.0.1

type CommandInput struct {
	Context  context.Context
	Raw      []string
	Args     ValueSet
	Flags    ValueSet
	Pipeline any
}

CommandInput contains parsed arguments, flags, and runtime context.

type CommandRegistry added in v1.0.1

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

CommandRegistry manages contexts and command registrations.

func NewCommandRegistry added in v1.0.1

func NewCommandRegistry() *CommandRegistry

NewCommandRegistry constructs a registry.

func (*CommandRegistry) Commands added in v1.0.1

func (r *CommandRegistry) Commands(ctx string, includeHidden bool) []CommandSpec

Commands returns command names for a context.

func (*CommandRegistry) Context added in v1.0.1

func (r *CommandRegistry) Context(name string) (ContextSpec, bool)

Context retrieves a context specification.

func (*CommandRegistry) Contexts added in v1.0.1

func (r *CommandRegistry) Contexts(includeHidden bool) []ContextSpec

Contexts lists registered contexts.

func (*CommandRegistry) LoadPlugins added in v1.0.1

func (r *CommandRegistry) LoadPlugins(dir string) error

LoadPlugins loads Go plugins from directory.

func (*CommandRegistry) NamespaceCommands added in v1.0.1

func (r *CommandRegistry) NamespaceCommands(namespace string) []CommandSpec

NamespaceCommands returns commands across contexts matching prefix.

func (*CommandRegistry) RegisterCommand added in v1.0.1

func (r *CommandRegistry) RegisterCommand(factory CommandFactory)

RegisterCommand registers a command factory.

func (*CommandRegistry) RegisterContext added in v1.0.1

func (r *CommandRegistry) RegisterContext(spec ContextSpec)

RegisterContext registers a new context spec.

func (*CommandRegistry) Resolve added in v1.0.1

func (r *CommandRegistry) Resolve(ctx, name string) (CommandEntry, bool)

Resolve finds a command entry for a context.

func (*CommandRegistry) ResolveContextName added in v1.0.1

func (r *CommandRegistry) ResolveContextName(name string) (string, bool)

ResolveContextName returns canonical context name, considering aliases.

func (*CommandRegistry) UnregisterCommand added in v1.0.1

func (r *CommandRegistry) UnregisterCommand(ctx, name string)

UnregisterCommand removes a command by name.

type CommandRegistryWriter added in v1.0.1

type CommandRegistryWriter interface {
	RegisterContext(spec ContextSpec)
	RegisterCommand(factory CommandFactory)
}

CommandRegistryWriter exposes safe registration subset for plugins.

type CommandResult added in v1.0.1

type CommandResult struct {
	Status      CommandStatus
	Error       *CommandError
	Payload     any
	Messages    []OutputMessage
	NextContext string
	Pipeline    any
}

CommandResult conveys the outcome of command execution.

func RecoveryMiddleware added in v1.0.1

func RecoveryMiddleware(rt CommandRuntime, input CommandInput, entry CommandEntry, next NextFunc) CommandResult

RecoveryMiddleware recovers from panics in commands.

func TimingMiddleware added in v1.0.1

func TimingMiddleware(rt CommandRuntime, input CommandInput, entry CommandEntry, next NextFunc) CommandResult

TimingMiddleware measures execution duration.

type CommandRuntime added in v1.0.1

type CommandRuntime interface {
	Session() SessionStore
	Services() ServiceRegistry
	Output() OutputChannel
	ContextManager() *ContextManager
	TaskManager() *TaskManager
	Cancellation() context.Context
	NavigateTo(name string, payload any) error
	PushContext(name string, payload any) error
	PopContext() error
	PipelineData() any
	SetPipelineData(v any)
}

CommandRuntime presents runtime services to commands.

type CommandSpec added in v1.0.1

type CommandSpec struct {
	Name         string
	Aliases      []string
	Summary      string
	Description  string
	Examples     []Example
	Args         []ArgSpec
	Flags        []FlagSpec
	Permissions  []string
	Hidden       bool
	Tags         []string
	Category     string
	Context      string
	Usage        string
	AllowPipes   bool
	DefaultAlias string
}

CommandSpec describes command metadata for discovery and help.

type CommandStatus added in v1.0.1

type CommandStatus string

CommandStatus indicates the result of a command invocation.

const (
	StatusSuccess CommandStatus = "success"
	StatusFailed  CommandStatus = "failed"
	StatusPartial CommandStatus = "partial"
	StatusPending CommandStatus = "pending"
)

type ContextManager added in v1.0.1

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

ContextManager manages context stack and transitions.

func NewContextManager added in v1.0.1

func NewContextManager(registry *CommandRegistry) *ContextManager

NewContextManager constructs a manager.

func (*ContextManager) Current added in v1.0.1

func (m *ContextManager) Current() ExecutionContext

Current returns the active context on the stack.

func (*ContextManager) Navigate added in v1.0.1

func (m *ContextManager) Navigate(name string, payload any) error

Navigate sets the stack to the specified context, replacing current.

func (*ContextManager) Pop added in v1.0.1

func (m *ContextManager) Pop() error

Pop removes the top context if not root.

func (*ContextManager) PopToRoot added in v1.0.1

func (m *ContextManager) PopToRoot() error

PopToRoot resets stack to root context.

func (*ContextManager) Prompt added in v1.0.1

func (m *ContextManager) Prompt(base string) string

Prompt returns the prompt for current context.

func (*ContextManager) Push added in v1.0.1

func (m *ContextManager) Push(name string, payload any) error

Push adds a context to the stack.

func (*ContextManager) ResolveAliases added in v1.0.1

func (m *ContextManager) ResolveAliases(name string) (string, bool)

ResolveAliases returns canonical context name.

func (*ContextManager) Stack added in v1.0.1

func (m *ContextManager) Stack() []ExecutionContext

Stack returns a copy of the current stack.

type ContextOption added in v1.0.1

type ContextOption func(*ContextSpec)

ContextOption mutates a ContextSpec before registration.

func WithContextAliases added in v1.0.1

func WithContextAliases(aliases ...string) ContextOption

WithContextAliases adds aliases for a context name.

func WithContextPrompt added in v1.0.1

func WithContextPrompt(prompt string) ContextOption

WithContextPrompt sets a custom prompt template for the context.

func WithContextTags added in v1.0.1

func WithContextTags(tags ...string) ContextOption

WithContextTags assigns tags to a context.

type ContextSpec added in v1.0.1

type ContextSpec struct {
	Name        string
	Parent      string
	Description string
	Prompt      string
	Aliases     []string
	Tags        []string
	Hidden      bool
}

ContextSpec defines metadata for an execution context.

type DefaultOutputChannel added in v1.0.1

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

DefaultOutputChannel is an in-memory channel writing to io.Writer.

func NewOutputChannel added in v1.0.1

func NewOutputChannel(w io.Writer) *DefaultOutputChannel

NewOutputChannel builds an OutputChannel targeting provided writer.

func (*DefaultOutputChannel) Buffer added in v1.0.1

func (c *DefaultOutputChannel) Buffer() *bytes.Buffer

Buffer exposes captured output, useful in tests.

func (*DefaultOutputChannel) Error added in v1.0.1

func (c *DefaultOutputChannel) Error(msg string)

Error writes an error message.

func (*DefaultOutputChannel) Info added in v1.0.1

func (c *DefaultOutputChannel) Info(msg string)

Info writes an informational message.

func (*DefaultOutputChannel) Level added in v1.0.1

func (c *DefaultOutputChannel) Level() OutputLevel

Level returns current verbosity.

func (*DefaultOutputChannel) SetLevel added in v1.0.1

func (c *DefaultOutputChannel) SetLevel(level OutputLevel)

SetLevel updates verbosity.

func (*DefaultOutputChannel) Warn added in v1.0.1

func (c *DefaultOutputChannel) Warn(msg string)

Warn writes a warning message.

func (*DefaultOutputChannel) WriteJSON added in v1.0.1

func (c *DefaultOutputChannel) WriteJSON(v any)

WriteJSON renders JSON output respecting verbosity.

func (*DefaultOutputChannel) WriteTable added in v1.0.1

func (c *DefaultOutputChannel) WriteTable(headers []string, rows [][]string)

WriteTable renders tabular output without border markers.

func (*DefaultOutputChannel) Writer added in v1.0.1

func (c *DefaultOutputChannel) Writer() io.Writer

Writer returns the underlying writer.

type Engine added in v1.0.1

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

Engine orchestrates command resolution and execution.

func DefaultEngine added in v1.0.1

func DefaultEngine() *Engine

DefaultEngine returns the shared default engine instance.

func NewEngine added in v1.0.1

func NewEngine(options ...Option) *Engine

NewEngine constructs an Engine with defaults.

func (*Engine) Contexts added in v1.0.1

func (e *Engine) Contexts() *ContextManager

Contexts returns the context manager.

func (*Engine) RegisterCommand added in v1.0.1

func (e *Engine) RegisterCommand(factory CommandFactory)

RegisterCommand registers a command factory.

func (*Engine) RegisterContext added in v1.0.1

func (e *Engine) RegisterContext(spec ContextSpec)

RegisterContext adds a context specification to the registry.

func (*Engine) Registry added in v1.0.1

func (e *Engine) Registry() *CommandRegistry

Registry exposes the command registry for external registration.

func (*Engine) Run added in v1.0.1

func (e *Engine) Run(rl *readline.Instance) error

Run starts the interactive loop.

func (*Engine) Services added in v1.0.1

func (e *Engine) Services() ServiceRegistry

Services exposes the service registry.

func (*Engine) Session added in v1.0.1

func (e *Engine) Session() SessionStore

Session exposes the session store.

func (*Engine) SetHelpHeader added in v1.0.1

func (e *Engine) SetHelpHeader(header string)

SetHelpHeader updates the help header string.

func (*Engine) SetOutputLevel added in v1.0.1

func (e *Engine) SetOutputLevel(level OutputLevel)

SetOutputLevel updates output verbosity.

func (*Engine) SetOutputWriter added in v1.0.1

func (e *Engine) SetOutputWriter(w io.Writer) io.Writer

SetOutputWriter swaps the engine's writer for command output, returning the previous writer.

func (*Engine) SetPrompt added in v1.0.1

func (e *Engine) SetPrompt(prompt string)

SetPrompt updates the base prompt string.

type Example added in v1.0.1

type Example struct {
	Description string
	Command     string
}

Example documents an example invocation of a command.

type ExecutionContext added in v1.0.1

type ExecutionContext struct {
	Spec    ContextSpec
	State   map[string]any
	Payload any
}

ExecutionContext is an active context on the stack.

type FlagSpec added in v1.0.1

type FlagSpec struct {
	Name        string
	Shorthand   string
	Type        ArgType
	Required    bool
	Description string
	Default     any
	EnumValues  []string
	Hidden      bool
}

FlagSpec defines flag metadata.

type LegacyAdapter added in v1.0.1

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

LegacyAdapter wraps a LegacyCommand into the new Command interface.

func (*LegacyAdapter) Execute added in v1.0.1

Execute delegates to the legacy command, capturing output.

func (*LegacyAdapter) Spec added in v1.0.1

func (a *LegacyAdapter) Spec() CommandSpec

Spec returns metadata for the wrapped command.

type LegacyCommand added in v1.0.1

type LegacyCommand interface {
	Name() string
	Help() string
	Exec(args []string)
}

LegacyCommand describes the original interface from the minimal framework.

type MemorySessionStore added in v1.0.1

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

MemorySessionStore is an in-memory implementation of SessionStore.

func NewSessionStore added in v1.0.1

func NewSessionStore() *MemorySessionStore

NewSessionStore constructs a MemorySessionStore.

func (*MemorySessionStore) Delete added in v1.0.1

func (s *MemorySessionStore) Delete(key string)

Delete removes a key.

func (*MemorySessionStore) Get added in v1.0.1

func (s *MemorySessionStore) Get(key string) (any, bool)

Get retrieves a value.

func (*MemorySessionStore) Keys added in v1.0.1

func (s *MemorySessionStore) Keys() []string

Keys lists stored keys.

func (*MemorySessionStore) Set added in v1.0.1

func (s *MemorySessionStore) Set(key string, value any)

Set stores a key/value pair.

type Middleware added in v1.0.1

Middleware wraps command execution with cross-cutting logic.

type NextFunc added in v1.0.1

NextFunc represents the next handler in the middleware chain.

type Option added in v1.0.1

type Option func(*Engine)

Option configures the engine.

func WithHelpHeader added in v1.0.1

func WithHelpHeader(header string) Option

WithHelpHeader customises the help header string.

func WithMiddleware added in v1.0.1

func WithMiddleware(mw ...Middleware) Option

WithMiddleware appends middleware functions.

func WithOutputLevel added in v1.0.1

func WithOutputLevel(level OutputLevel) Option

WithOutputLevel sets default output verbosity.

func WithOutputWriter added in v1.0.1

func WithOutputWriter(w io.Writer) Option

WithOutputWriter overrides the engine output writer.

func WithPrompt added in v1.0.1

func WithPrompt(prompt string) Option

WithPrompt sets the base prompt prefix.

func WithServices added in v1.0.1

func WithServices(register func(ServiceRegistry)) Option

WithServices seeds the service registry.

type OutputChannel added in v1.0.1

type OutputChannel interface {
	Level() OutputLevel
	SetLevel(level OutputLevel)
	Info(msg string)
	Warn(msg string)
	Error(msg string)
	WriteJSON(v any)
	WriteTable(headers []string, rows [][]string)
	Writer() io.Writer
	Buffer() *bytes.Buffer
}

OutputChannel controls command output levels and formats.

type OutputLevel added in v1.0.1

type OutputLevel int

OutputLevel enumerates verbosity levels.

const (
	OutputQuiet OutputLevel = iota
	OutputNormal
	OutputVerbose
	OutputDebug
)

type OutputMessage added in v1.0.1

type OutputMessage struct {
	Level   SeverityLevel
	Format  string
	Content string
}

OutputMessage allows commands to suggest standardised output.

type ServiceRegistry added in v1.0.1

type ServiceRegistry interface {
	Register(name string, value any)
	Get(name string) (any, bool)
}

ServiceRegistry exposes shared dependencies to commands.

type SessionStore added in v1.0.1

type SessionStore interface {
	Get(key string) (any, bool)
	Set(key string, value any)
	Delete(key string)
	Keys() []string
}

SessionStore provides shared state across commands during a session.

type SeverityLevel added in v1.0.1

type SeverityLevel string

SeverityLevel indicates the severity of an error surfaced to the user.

const (
	SeverityInfo    SeverityLevel = "info"
	SeverityWarning SeverityLevel = "warning"
	SeverityError   SeverityLevel = "error"
)

type SimpleServiceRegistry added in v1.0.1

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

SimpleServiceRegistry is a basic map-backed ServiceRegistry.

func NewServiceRegistry added in v1.0.1

func NewServiceRegistry() *SimpleServiceRegistry

NewServiceRegistry constructs a SimpleServiceRegistry.

func (*SimpleServiceRegistry) Get added in v1.0.1

func (r *SimpleServiceRegistry) Get(name string) (any, bool)

Get retrieves a service.

func (*SimpleServiceRegistry) Register added in v1.0.1

func (r *SimpleServiceRegistry) Register(name string, value any)

Register stores a service instance.

type TaskFunc added in v1.0.1

type TaskFunc func(ctx context.Context, output OutputChannel) error

TaskFunc represents an asynchronous job.

type TaskHandle added in v1.0.1

type TaskHandle struct {
	ID       string
	Name     string
	Status   TaskStatus
	Error    error
	Metadata map[string]any
	// contains filtered or unexported fields
}

TaskHandle represents a running task.

type TaskManager added in v1.0.1

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

TaskManager supervises background tasks.

func NewTaskManager added in v1.0.1

func NewTaskManager(output OutputChannel) *TaskManager

NewTaskManager constructs a TaskManager.

func (*TaskManager) Cancel added in v1.0.1

func (m *TaskManager) Cancel(id string) bool

Cancel cancels a task by ID.

func (*TaskManager) DescribeTask added in v1.0.1

func (m *TaskManager) DescribeTask(id string) (*TaskHandle, bool)

DescribeTask returns handle by ID.

func (*TaskManager) SetOutputChannel added in v1.0.1

func (m *TaskManager) SetOutputChannel(out OutputChannel)

SetOutputChannel updates the output destination for future task logs.

func (*TaskManager) Spawn added in v1.0.1

func (m *TaskManager) Spawn(name string, fn TaskFunc, opts TaskOptions) *TaskHandle

Spawn launches an async task.

func (*TaskManager) Tasks added in v1.0.1

func (m *TaskManager) Tasks() []*TaskHandle

Tasks lists tasks.

type TaskOptions added in v1.0.1

type TaskOptions struct {
	Timeout  time.Duration
	Metadata map[string]any
}

TaskOptions configure async tasks.

type TaskStatus added in v1.0.1

type TaskStatus string

TaskStatus enumerates async task states.

const (
	TaskPending   TaskStatus = "pending"
	TaskRunning   TaskStatus = "running"
	TaskSucceeded TaskStatus = "succeeded"
	TaskFailed    TaskStatus = "failed"
	TaskCancelled TaskStatus = "cancelled"
)

type ValueSet added in v1.0.1

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

ValueSet provides typed accessors for parsed arguments or flags.

func (ValueSet) Bool added in v1.0.1

func (v ValueSet) Bool(name string) bool

Bool retrieves a boolean value.

func (ValueSet) DecodeJSON added in v1.0.1

func (v ValueSet) DecodeJSON(name string, dest any) error

DecodeJSON decodes the value into the provided destination.

func (ValueSet) Duration added in v1.0.1

func (v ValueSet) Duration(name string) time.Duration

Duration retrieves a time.Duration value.

func (ValueSet) Float added in v1.0.1

func (v ValueSet) Float(name string) float64

Float retrieves a float value.

func (ValueSet) Int added in v1.0.1

func (v ValueSet) Int(name string) int

Int retrieves an integer value.

func (ValueSet) Raw added in v1.0.1

func (v ValueSet) Raw(name string) (any, bool)

Raw returns the raw stored value without conversion.

func (ValueSet) String added in v1.0.1

func (v ValueSet) String(name string) string

String retrieves a string value.

func (ValueSet) Strings added in v1.0.1

func (v ValueSet) Strings(name string) []string

Strings returns a slice of strings for repeatable args/flags.

Jump to

Keyboard shortcuts

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