clicky

package module
v1.21.21 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2026 License: Apache-2.0 Imports: 36 Imported by: 83

README

Clicky

Clicky is a Go toolkit for turning structured data and Cobra CLIs into polished command-line, web, and AI-facing interfaces. It includes:

  • multi-format output for structs, maps, slices, and schema-driven data
  • styled terminal and HTML rendering based on pretty tags and Tailwind-like classes
  • concurrent task execution with progress rendering, retries, cancellation, and typed results
  • Echo middleware configured from Go or YAML
  • Cobra extensions for OpenAPI, Swagger UI, HTTP command execution, and MCP servers
  • helper packages for text processing, command execution, entity commands, and linting

The module path is:

go get github.com/flanksource/clicky

Install the CLI

go install github.com/flanksource/clicky/cmd/clicky@latest

For local development:

make build
./clicky --help

The clicky binary formats JSON/YAML data with a schema, validates schemas, runs the API linter, and can expose its own Cobra commands through OpenAPI and MCP.

clicky pretty --schema examples/order-schema.yaml examples/example-data.json
clicky pretty --schema examples/order-schema.yaml --format html --output order.html examples/example-data.json
clicky schema validate examples/order-schema.yaml
clicky schema example -o schema.yaml
clicky lint ./...

Library Usage

Format Structured Data
package main

import (
	"fmt"

	"github.com/flanksource/clicky"
)

type Server struct {
	Name   string `pretty:"label=Server"`
	Status string `pretty:"color=green,sort"`
	CPU    int    `pretty:"label=CPU %,color=blue"`
}

func main() {
	servers := []Server{
		{Name: "api-01", Status: "ready", CPU: 31},
		{Name: "db-01", Status: "ready", CPU: 54},
	}

	out, err := clicky.Format(servers, clicky.FormatOptions{Format: "pretty"})
	if err != nil {
		panic(err)
	}
	fmt.Print(out)
}

Supported formats include pretty, json, yaml, csv, markdown, html, html-react, html-static, pdf, slack, excel, and tree. Common aliases such as md, yml, and xlsx are accepted.

FormatOptions.Format can also describe multiple sinks:

clicky.PrintAndWriteSinks(data, clicky.FormatOptions{
	Format: "pretty,json=out.json,markdown=summary.md",
})
Run Typed Tasks
package main

import (
	"fmt"
	"time"

	"github.com/flanksource/clicky"
)

func main() {
	job := clicky.StartTask("load servers", func(ctx clicky.Context, t *clicky.Task) ([]string, error) {
		for i := 1; i <= 3; i++ {
			t.SetProgress(i, 3)
			time.Sleep(100 * time.Millisecond)
		}
		return []string{"api-01", "db-01"}, nil
	})

	servers, err := job.GetResult()
	if err != nil {
		panic(err)
	}
	fmt.Println(servers)

	clicky.WaitForGlobalCompletion()
}

For grouped work, use clicky.StartGroup[T] or task.StartGroup[T] with task.WithConcurrency(n).

Add Common Flags to a Cobra CLI
rootCmd := &cobra.Command{Use: "myapp"}
flags := clicky.BindAllFlagsToCommand(rootCmd, "format", "tasks")

rootCmd.PersistentPreRun = func(cmd *cobra.Command, args []string) {
	flags.UseFlags()
}

This adds grouped logging, formatting, and task flags such as --format, --filter, --no-color, --no-progress, and --max-concurrent.

Add OpenAPI and MCP to a Cobra CLI
import "github.com/flanksource/clicky/extensions"

extensions.CobraExtensions(rootCmd).All()

This adds:

  • openapi generate
  • openapi validate <file>
  • openapi serve
  • mcp serve
  • mcp config
  • mcp tools
  • mcp install
  • mcp prompts

Example commands:

myapp openapi generate --format yaml --output openapi.yaml
myapp openapi serve --port 8080 --enable-executor
myapp mcp tools --format markdown
myapp mcp serve --auto-expose
Configure Echo Middleware
package main

import (
	"log"

	"github.com/flanksource/clicky/middleware"
	"github.com/labstack/echo/v4"
)

func main() {
	e := echo.New()

	config, err := middleware.LoadConfigFromYAML("config/production.yaml")
	if err != nil {
		log.Fatal(err)
	}
	if err := middleware.ValidateConfig(config); err != nil {
		log.Fatal(err)
	}

	middleware.ApplyMiddleware(e, config)
	log.Fatal(e.Start(":8080"))
}

Preset helpers are also available:

middleware.ApplyMinimalMiddleware(e)
middleware.ApplyDefaultMiddleware(e)
middleware.ApplyProductionMiddleware(e)

Schema Formatting

The CLI can format dynamic JSON/YAML data using schema files. A schema describes fields, labels, types, styles, color rules, table fields, tree fields, and format-specific options.

fields:
  - name: id
    label: Order ID
    type: string
    style: text-blue-600 font-bold
  - name: status
    type: string
    color_options:
      green: completed
      yellow: processing
      red: failed
  - name: total_amount
    type: float
    format: currency
  - name: items
    type: array
    format: table
    table_options:
      fields:
        - name: product_name
          type: string
        - name: quantity
          type: int
        - name: price
          type: float
          format: currency

Generate a fuller example with:

clicky schema example

Package Map

  • api: render primitives such as text, tables, trees, code blocks, badges, links, stack traces, and schema parsing
  • formatters: output managers and implementations for terminal, JSON, YAML, CSV, Markdown, HTML, PDF, Excel, Slack, and tree formats
  • task: task manager, typed tasks, groups, progress rendering, retries, shutdown handling, and output capture
  • middleware: Echo v4 middleware configuration, validation, auth, interceptors, and presets
  • rpc: Cobra-to-OpenAPI generation, Swagger UI server, validation, and HTTP command execution
  • mcp: Model Context Protocol server and tool discovery for Cobra commands
  • extensions: fluent helpers that attach OpenAPI and MCP commands to Cobra roots
  • exec: command execution wrappers with logging and process-group handling
  • flags: struct-tag flag binding helpers
  • text: tokenization, redaction, and line processing utilities
  • lint: Go analyzer for Clicky API usage

Development

go mod download
make test
make lint
make build

Useful targeted commands:

go test ./formatters/...
go test ./task/...
go test ./middleware/...
go test -tags integration ./rpc/... -run TestOpenAPIServe_E2E

The task UI bundle is built separately:

make task-ui

Examples

The examples/ directory includes focused demos for:

  • schema-driven formatting
  • Cobra integration
  • OpenAPI and Swagger serving
  • MCP integration
  • Echo middleware
  • task manager behavior
  • file tree, PDF widgets, and entity workflows

Start with examples/README.md and the schema/data pairs in examples/order-schema.yaml and examples/example-data.json.

Documentation

Index

Constants

View Source
const (
	StatusPending   = task.StatusPending
	StatusRunning   = task.StatusRunning
	StatusSuccess   = task.StatusSuccess
	StatusFailed    = task.StatusFailed
	StatusWarning   = task.StatusWarning
	StatusCancelled = task.StatusCancelled
)

Status constants

View Source
const (
	CategoryLogging = "Logging"
	CategoryTasks   = "Tasks"
	CategoryFormat  = "Format"
)

Flag category labels rendered as section headers in --help output.

View Source
const FlagCategoryAnnotation = "clicky_category"

FlagCategoryAnnotation is the pflag annotation key used to tag flags with a display category, so the usage template can render them in grouped sections.

Variables

View Source
var (
	DefaultRetryConfig        = task.DefaultRetryConfig
	DefaultTaskManagerOptions = task.DefaultManagerOptions
	WithTimeout               = task.WithTimeout
	WithTaskTimeout           = task.WithTaskTimeout
	WithDependencies          = task.WithDependencies
	WithFunc                  = task.WithFunc
	WithModel                 = task.WithModel
	WithPrompt                = task.WithPrompt
	WithRetryConfig           = task.WithRetryConfig
	WithPriority              = task.WithPriority
	BindTaskManagerFlags      = task.BindManagerFlags
	BindTaskManagerPFlags     = task.BindManagerPFlags
)

Function aliases for backward compatibility

View Source
var (
	WithSourceResolver        = api.WithSourceResolver
	WithSourceResolverContext = api.WithSourceResolverContext
	WithStackInclude          = api.WithStackInclude
	WithStackExclude          = api.WithStackExclude
	WithStackContext          = api.WithStackContext
	WithMaxStackFrames        = api.WithMaxFrames
)
View Source
var Badge = api.Badge
View Source
var Class = api.Clz
View Source
var CodeBlock = api.CodeBlock
View Source
var Column = api.Column
View Source
var Exec = exec.NewExec
View Source
var Execf = exec.NewExecf
View Source
var (
	Formatter = formatters.NewFormatManager()
)
View Source
var Human = api.Human
View Source
var KeyValue = api.KeyValue
View Source
var LinkTargetClicky = api.LinkTargetClicky
View Source
var LinkTargetDialog = api.LinkTargetDialog
View Source
var LinkTargetExpand = api.LinkTargetExpand
View Source
var LinkTargetHover = api.LinkTargetHover
View Source
var LinkTargetSelf = api.LinkTargetSelf
View Source
var LinkTargetTab = api.LinkTargetTab
View Source
var LinkTargetWindow = api.LinkTargetWindow
View Source
var StackTraceJava = api.ParseJavaStackTrace

StackTraceJava is the explicit Java parser. Equivalent to StackTrace today; kept distinct so future non-Java parsers (Python, .NET) can plug in without breaking callers that have explicitly opted into Java semantics.

Functions

func Action

func Action[R any](name string, fn func(id string, flags map[string]string) (R, error)) *actionSpec[R]

Action creates a typed custom operation on a single entity by ID.

func ActionWithContext

func ActionWithContext[R any](name string, fn func(ctx context.Context, id string, flags map[string]string) (R, error)) *actionSpec[R]

ActionWithContext creates a typed action whose run closure receives the request-scoped context (cmd.Context() on the CLI, r.Context() over HTTP), so it can resolve a per-request database/config instead of a process global.

func ActionWithFlags

func ActionWithFlags[R any](name string, flags ActionFlags, fn func(id string, flags map[string]string) (R, error)) *actionSpec[R]

ActionWithFlags creates a typed custom operation with typed action flags.

func ActionWithFlagsAndContext

func ActionWithFlagsAndContext[R any](name string, flags ActionFlags, fn func(ctx context.Context, id string, flags map[string]string) (R, error)) *actionSpec[R]

ActionWithFlagsAndContext is ActionWithContext with typed action flags.

func AddCommand

func AddCommand[T any, R any](parent *cobra.Command, opts T, fn func(opts T) (R, error)) *cobra.Command

AddCommand creates a Cobra command with automatic flag parsing from struct tags, execution, and result formatting.

Type parameter T must be a struct with tags defining flags:

  • flag:"name" - flag name (required)
  • help:"description" - flag help text
  • default:"value" - default value
  • short:"x" - short flag variant
  • required:"true" - mark flag as required
  • stdin:"true" - mark field as default for stdin input (only one field)

Supports @ prefix for file/URL loading:

  • @file.txt - read from file
  • @https://... - fetch from URL
  • For slices: one value per line (skip empty lines and # comments)
  • For slices: @file.csv:ColumnName reads a named column from a CSV (first row is the header, empty cells are skipped)
  • For slices: @file.xlsx:ColumnName / @file.xls:ColumnName reads a named column from the first worksheet (case-insensitive header match)

Supported types:

  • string, int, bool
  • duration.Duration (supports "30d", "2w", etc.)
  • time.Time (supports datamath like "now-7d", "now/d", "now-1M/M")
  • []string, []int (slices)

Datamath expressions for time.Time fields (Elasticsearch compatible):

  • now : current time
  • now-7d : 7 days ago
  • now+2h : 2 hours from now
  • now/d : start of current day
  • now-7d/d : start of day 7 days ago
  • now/w : start of this week
  • now-1M/M : start of last month
  • now/y : start of this year
  • Units: y (year), M (month), w (week), d (day), h (hour), m (minute), s (second)

Example:

type ListOptions struct {
    Role   string            `flag:"role" help:"Filter by role" short:"r"`
    Limit  int               `flag:"limit" help:"Max results" default:"50"`
    Since  time.Time         `flag:"since" help:"Created since" default:"now-30d"`
    Tags   []string          `flag:"tags" help:"Filter tags" stdin:"true"`
    MaxAge duration.Duration `flag:"max-age" help:"Max age" default:"365d"`
}

cmd := &cobra.Command{Use: "list", Short: "List users"}
clicky.AddCommand(cmd, ListOptions{}, func(opts ListOptions) (any, error) {
    return fetchUsers(opts)
})

Usage examples:

myapp list --tags @tags.txt              # load from file
myapp list --since now-30d               # datamath
echo -e "tag1\ntag2" | myapp list        # stdin
myapp list --max-age 60d --json          # with formatting

func AddCommandWithContext

func AddCommandWithContext[T any, R any](parent *cobra.Command, opts T, fn func(ctx context.Context, opts T) (R, error)) *cobra.Command

AddCommandWithContext is AddCommand whose closure receives the request-scoped context (cmd.Context() on the CLI, r.Context() over HTTP). It derives the command name from the opts struct exactly like AddCommand, then delegates to AddNamedCommandWithContext so the subcommand can resolve a per-request database/config instead of a process global.

func AddFormatCallback

func AddFormatCallback(callback FormatCallback)

AddFormatCallback registers a global formatting callback. The callback is applied to top-level clicky formatting as well as HTTP/RPC response formatting paths.

func AddNamedCommand

func AddNamedCommand[T any, R any](name string, parent *cobra.Command, opts T, fn func(opts T) (R, error)) *cobra.Command

func AddNamedCommandWithContext

func AddNamedCommandWithContext[T any, R any](name string, parent *cobra.Command, opts T, fn func(ctx context.Context, opts T) (R, error)) *cobra.Command

AddNamedCommandWithContext is AddNamedCommand whose closure receives the request-scoped context (cmd.Context() on the CLI, r.Context() over HTTP), so the subcommand can resolve a per-request database/config instead of a process global. Same flag/arg binding and rendering as AddNamedCommand.

func Admonition

func Admonition(severity api.Severity, title, body api.Textable) api.Admonition

func BulkAction

func BulkAction[R any](name string, fn func(ids []string, flags map[string]string) (R, error)) *bulkActionSpec[R]

BulkAction creates a typed custom operation on multiple entity IDs.

func BulkActionWithFilter

func BulkActionWithFilter[ListOpts any, R any](
	name string,
	run func(ids []string, flags map[string]string) (R, error),
	runFilter func(opts ListOpts, flags map[string]string) (R, error),
) *bulkActionSpec[R]

BulkActionWithFilter creates a typed bulk action that supports both explicit IDs and filtered selections.

func BulkFilterAction

func BulkFilterAction[ListOpts any, R any](name string, fn func(opts ListOpts, flags map[string]string) (R, error)) *bulkActionSpec[R]

BulkFilterAction creates a typed custom operation that runs against a typed filtered list selection instead of explicit IDs.

func Button

func Button(label, href string, options ...func(*api.Button)) api.Button

func ButtonGroup

func ButtonGroup(buttons ...api.Button) api.ButtonGroup

func ButtonID

func ButtonID(id string) func(*api.Button)

func ButtonPayload

func ButtonPayload(payload string) func(*api.Button)

func ButtonVariant

func ButtonVariant(variant string) func(*api.Button)

func CancelAllGlobalTasks

func CancelAllGlobalTasks()

CancelAllGlobalTasks cancels all running global tasks

func ClearFormatCallbacks

func ClearFormatCallbacks()

ClearFormatCallbacks removes all registered format callbacks. This is primarily useful in tests.

func ClearGlobalTasks

func ClearGlobalTasks()

ClearGlobalTasks removes completed tasks from the global TaskManager

func ClickyText

func ClickyText(text api.Textable) formatters.ClickyText

func Collapsed

func Collapsed(label string, content api.Textable, styles ...string) api.Collapsed

func Comment

func Comment(text string) api.Comment

func CompactList

func CompactList[T any](items []T) api.Textable

func CompleteGlobalPhase

func CompleteGlobalPhase()

CompleteGlobalPhase marks the current phase as completed

func Debugf

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

func Diff

func Diff(before, after, fromLabel, toLabel string) api.Diff

func Errorf

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

func ExitWithGlobalTaskSummary

func ExitWithGlobalTaskSummary()

ExitWithGlobalTaskSummary displays task summary and exits with appropriate code

func Format

func Format(o any, opts ...FormatOptions) (string, error)

func FormatToContentType

func FormatToContentType(format string) string

FormatToContentType converts a format string to HTTP Content-Type

func FormatToFile

func FormatToFile(o any, opts FormatOptions, file string) error

func FormatToFileWithContext

func FormatToFileWithContext(ctx any, o any, opts FormatOptions, file string) error

FormatToFileWithContext formats using the shared clicky formatter, writes the output to file, and forwards ctx to registered format callbacks.

func FormatWithContext

func FormatWithContext(ctx any, o any, opts ...FormatOptions) (string, error)

FormatWithContext formats using the shared clicky formatter while forwarding ctx to registered format callbacks.

func Fprintln

func Fprintln(w io.Writer, args ...any)

Fprintln writes args separated by spaces and terminated by a newline to the supplied writer. Use this when you need to target a specific writer (e.g. a tab writer, a string builder, a capture buffer) — for the common case of "print a line to the terminal", prefer Println.

func GenerateCLI

func GenerateCLI(parent *cobra.Command)

GenerateCLI creates cobra subcommands for all registered entities under parent. Admin entities are nested under a shared "admin" parent command. Entities with a Parent set are nested under a shared parent cobra command, created lazily if it does not already exist.

func GetDataFunc

func GetDataFunc(cmd *cobra.Command) func(flags map[string]string, args []string) (any, error)

GetDataFunc returns the direct data function registered for a command, if any. Used by the RPC converter to wire DataFunc on RPCOperation.

func GetGlobalTaskManagerStats

func GetGlobalTaskManagerStats() (total, running, completed, failed int)

GetGlobalTaskManagerStats returns stats about the global TaskManager

func GetLookupFunc

func GetLookupFunc(cmd *cobra.Command) func(flags map[string]string, args []string) (any, error)

GetLookupFunc returns the direct lookup function registered for a command, if any.

func GetResultTyped

func GetResultTyped[T any](t *Task) (T, error)

GetResultTyped returns the stored result with type assertion

func HTMLElement

func HTMLElement(tag, content string, attrs ...map[string]string) api.HtmlElement

func Infof

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

func LabelBadge

func LabelBadge(label, value string, options ...func(*api.LabelBadge)) api.LabelBadge

func LabelBadgeColor

func LabelBadgeColor(color string) func(*api.LabelBadge)

func LabelBadgeIcon

func LabelBadgeIcon(icon string) func(*api.LabelBadge)

func LabelBadgeShape

func LabelBadgeShape(shape string) func(*api.LabelBadge)

func LabelBadgeTextColor

func LabelBadgeTextColor(color string) func(*api.LabelBadge)
func Link(href string) api.Link

func LinkCommand

func LinkCommand(command string) api.LinkCommand

func List

func List(items ...api.Textable) api.List

func ListCustomFormatters

func ListCustomFormatters() []string

ListCustomFormatters returns a sorted list of all registered custom formatter names.

func Map

func Map[T any](m map[string]T, styles ...string) api.DescriptionList

func MustFormat

func MustFormat(o any, opts ...FormatOptions) string

func MustFormatWithContext

func MustFormatWithContext(ctx any, o any, opts ...FormatOptions) string

MustFormatWithContext formats using the shared clicky formatter and panics on error.

func MustParseArgumentsAsMap

func MustParseArgumentsAsMap(args []string) map[string]any

MustParseArgumentsAsMap is like ParseArgumentsAsMap but panics on error

func MustPrint

func MustPrint(o any, opts ...FormatOptions)

func MustPrintWithContext

func MustPrintWithContext(ctx any, o any, opts ...FormatOptions)

MustPrintWithContext formats using the shared clicky formatter, writes the output to stdout, and forwards ctx to registered format callbacks.

func ParseArgumentsAsMap

func ParseArgumentsAsMap(args []string) (map[string]any, error)

ParseArgumentsAsMap parses HTTPie-style command line arguments into a map Supports:

key=value     - String values
key:=value    - JSON values (numbers, booleans, arrays, objects)
key==value    - Query parameters (returned in separate map)
key@file      - Read value from file
key:=@file    - Read JSON from file
Header:value  - HTTP headers (ignored in this function)
key[sub]=val  - Nested JSON structures

func ParseArgumentsComplete

func ParseArgumentsComplete(args []string) (map[string]any, map[string]string, map[string]string, error)

ParseArgumentsComplete parses all argument types and returns separated results

func ParseArgumentsWithHeaders

func ParseArgumentsWithHeaders(args []string) (map[string]any, map[string]string, error)

ParseArgumentsWithHeaders parses arguments and separates headers

func ParseArgumentsWithQuery

func ParseArgumentsWithQuery(args []string) (data map[string]any, query map[string]string, err error)

ParseArgumentsWithQuery parses arguments and separates query parameters (backward compatibility)

func ParseJSON

func ParseJSON(data []byte) (interface{}, error)

ParseJSON parses JSON in a lenient way, allowing for various formats

func PrintAndWriteSinks

func PrintAndWriteSinks(o any, opts FormatOptions)

PrintAndWriteSinks renders o for each sink in opts.Sinks.

Stdout sinks (File == "") go through MustPrint, preserving existing pretty/stdout behaviour. File sinks call Formatter.FormatToFile, which renders in the sink's format and writes to the given path.

Per-sink errors are logged via Errorf but do NOT abort other sinks, so a broken HTML template cannot eat the JSON artifact that CI depends on. If opts.Sinks is empty the function falls back to MustPrint(o, opts) for back-compat with call sites that haven't run ParseFormatSpec.

func Printf

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

Printf formats and writes to the currently-active logger output. See Println for the serialization guarantees.

func Println

func Println(args ...any)

Println writes args separated by spaces and terminated by a newline to the currently-active logger output. While a task renderer is active that destination is the renderer's serializer, so the line is interleaved cleanly with progress frames. Off-renderer it falls through to os.Stderr.

Prefer this (or Printf / Fprintln) over bare fmt.Println / fmt.Fprintln on os.Stdout or os.Stderr in library code: direct writes bypass the renderer's tracking and leave stale frame lines stacked in the output. The clickylint rule `direct-stdout-stderr` flags the bypasses.

func Prompt

func Prompt[T any](items []T, opts PromptSelectOptions[T]) (T, bool)

Prompt is the shared ANSI list prompt runner used by PromptChoose and PromptSelect.

func PromptChoose

func PromptChoose[T any](items []T) (T, bool)

PromptChoose renders a minimal arrow-key choice prompt.

func PromptMultiSelect

func PromptMultiSelect[T any](items []T, opts PromptMultiSelectOptions[T]) ([]T, bool)

PromptMultiSelect renders a configurable ANSI multi-select prompt.

func PromptSelect

func PromptSelect[T any](items []T, opts PromptSelectOptions[T]) (T, bool)

PromptSelect renders a configurable arrow-key choice prompt.

func PromptText

func PromptText(opts PromptTextOptions) (string, bool)

PromptText renders an ANSI text entry prompt.

func RedactSecretValues

func RedactSecretValues(val ...string)

func RegisterEntity

func RegisterEntity[T EntityItem, ListOpts any, R any](e Entity[T, ListOpts, R])

RegisterEntity registers a CRUD entity. Call during init(). CLI commands and HTTP routes are generated later via GenerateCLI/GenerateRoutes.

func RegisterFormatter

func RegisterFormatter(name string, fn func(data interface{}, options FormatOptions) (string, error))

RegisterFormatter registers a custom formatter function that can be used with Format() by specifying the format name in FormatOptions. Custom formatters take precedence over built-in formatters with the same name.

Example:

clicky.RegisterFormatter("upper", func(data interface{}, opts clicky.FormatOptions) (string, error) {
    s := fmt.Sprintf("%v", data)
    return strings.ToUpper(s), nil
})

result, _ := clicky.Format(myData, clicky.FormatOptions{Format: "upper"})

func RegisterGlobalExit

func RegisterGlobalExit()

RegisterGlobalExit ensures tasks are displayed when the program exits

func RegisterSubCommand

func RegisterSubCommand(parentName string, cmd *cobra.Command)

RegisterSubCommand defers attaching cmd as a child of a parent cobra command identified by parentName. The attachment is performed by GenerateCLI after all entity parents have been created. If no command at parentName exists after entity generation, a thin parent command is created to host cmd.

parentName may be a bare command name ("policy") or a slash-delimited path ("billing/policy"). A path is resolved one segment at a time beneath root; missing intermediates are created as thin grouping commands, and existing nodes (including entity-generated parents) are reused.

Use this for non-entity cobra commands that should live under an entity-generated parent (or under an arbitrary grouping command).

func RegisterSubCommandFn

func RegisterSubCommandFn(parentName string, build func(parent *cobra.Command))

RegisterSubCommandFn defers running build against a parent cobra command identified by parentName. Use this when the subcommand needs to be constructed lazily — e.g. AddNamedCommand which both builds and attaches in one call.

parentName accepts the same bare-name-or-slash-path form as RegisterSubCommand.

Example:

clicky.RegisterSubCommandFn("correspondence", func(parent *cobra.Command) {
    clicky.AddNamedCommand("validate", parent, ValidateOptions{}, runValidate)
})

func SQL

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

func SetCommandResponseMeta

func SetCommandResponseMeta(cmd *cobra.Command, meta ResponseOpenAPIMeta)

SetCommandResponseMeta attaches static response metadata to a command.

func SetGlobalInterruptHandler

func SetGlobalInterruptHandler(fn func())

SetGlobalInterruptHandler sets the interrupt handler for the global TaskManager

func SetGlobalMaxConcurrency

func SetGlobalMaxConcurrency(max int)

SetGlobalMaxConcurrency sets the maximum concurrency for the global TaskManager

func SetGlobalSignalTimeout

func SetGlobalSignalTimeout(timeout time.Duration)

SetGlobalSignalTimeout configures the graceful shutdown timeout

func SetGlobalVerbose

func SetGlobalVerbose(verbose bool)

SetGlobalVerbose enables/disables verbose output for the global TaskManager

func SetGroupedUsage

func SetGroupedUsage(cmd *cobra.Command)

SetGroupedUsage installs a usage function on cmd that renders flags in sections grouped by their FlagCategoryAnnotation. Flags without a category fall under a generic "Flags" heading. The function is also propagated as the usage template inheritance chain expects, so subcommands display the same grouping for inherited flags.

func StackTrace

func StackTrace(input string, opts ...api.StackTraceOption) api.StackTrace

StackTrace parses a free-form runtime stack-trace string and returns a styled, render-ready trace. The default parser is language-agnostic and auto-detects Java traces; pass clicky.StackTraceJava (or another language-specific parser) when the language is known up front.

Pass options like clicky.WithSourceResolver(r), clicky.WithStackContext(5), or clicky.WithStackInclude("com.example.admin.") to attach inline source context and filter frames.

func StartCapturingOutput

func StartCapturingOutput()

StartCapturingOutput replaces os.Stdout / os.Stderr with internal pipes so that bare fmt.Print / os.Stderr writes are buffered instead of interleaving with the live task renderer. The live renderer keeps drawing on the real terminal because it captured the original file descriptors at manager init. Loggers that captured os.Stderr before this call keep writing live, too.

Pair with StopCapturingOutput at end-of-run; the buffered content is flushed in stream order onto the restored streams.

func StartGroup

func StartGroup[T any](name string, opts ...task.TaskGroupOption) task.TypedGroup[T]

func StartTask

func StartTask[T any](name string, taskFunc task.TaskFunc[T], opts ...TaskOption) task.TypedTask[T]

func StartWithResultTyped

func StartWithResultTyped[T any](tm *TaskManager, name string, taskFunc task.TaskFunc[T], opts ...TaskOption) *task.Task

StartWithResultTyped creates and starts tracking a new task with generic typed result handling

func StopCapturingOutput

func StopCapturingOutput()

StopCapturingOutput restores os.Stdout / os.Stderr and flushes every buffered line to the real terminal in write order, tagged by stream. Safe to call when capture wasn't started.

func StopTask

func StopTask(id string) bool

StopTask cancels a specific global task by immutable task ID.

func Table

func Table(headers ...string) api.TextTable

func Text

func Text(content string, tailwindClasses ...string) api.Text

func TextList

func TextList(items ...api.Textable) api.TextList

func Textf

func Textf(content string, args ...any) api.Text

func Tracef

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

func Tree

func Tree(node api.Textable, children ...api.TextTree) api.TextTree

func UpdateGlobalPhaseProgress

func UpdateGlobalPhaseProgress(message string)

UpdateGlobalPhaseProgress updates the progress of the current phase

func UseFormatter

func UseFormatter(opts FormatOptions)

func WaitForGlobalCompletion

func WaitForGlobalCompletion() int

WaitForGlobalCompletion waits for all global tasks to complete and returns exit code

func WaitForGlobalCompletionSilent

func WaitForGlobalCompletionSilent() int

WaitForGlobalCompletionSilent waits for global tasks without displaying results

func Warnf

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

func WithHttpRequest

func WithHttpRequest(r *http.Request) formatters.FormatOptions

WithHttpRequest extracts format options from an HTTP request Priority: query param > path extension > Accept header > default

func WithKey

func WithKey(key string, value api.Textable) api.Keyed

WithKey wraps a Textable with a data key. The result renders identically to value in every format but serializes to JSON as {key: value}. Callers reading the key for their own serialization can type-assert to api.Keyed.

Types

type ActionFlags

type ActionFlags interface {
	ClickyActionFlags()
}

ActionFlags is a marker interface implemented by options structs that declare typed cobra flags for a clicky Action. When an Action's Flags field is non-nil, the concrete type of the value is reflected for its `flag:"..."` struct tags and those flags are bound to the generated action cobra command.

Implementers attach a no-op `ClickyActionFlags()` method to an options struct, then pass a zero value of that struct in `Action.Flags`.

type ActionInfo

type ActionInfo struct {
	Name     string
	Short    string
	Method   string
	DataFunc func(flags map[string]string, args []string) (any, error)
	// ContextDataFunc, when set, is preferred over DataFunc by both the CLI run
	// path (fed cmd.Context()) and the RPC executor (fed r.Context()), mirroring
	// the entity CRUD seam. Lets an action resolve request-scoped state instead
	// of process globals.
	ContextDataFunc ContextDataFunc
	// FlagsType, if non-nil, is the struct type whose `flag:"..."` tagged
	// fields are registered as cobra flags on the generated action command
	// and populated into the flag map passed to DataFunc.
	FlagsType    reflect.Type
	ResponseType reflect.Type
	// OptionalID, when true, makes the positional <id> argument optional on
	// the generated action command — the action is invokable with no
	// argument (and the `id` passed to the run func is empty). Use for
	// actions whose target is supplied entirely through flags.
	OptionalID bool
}

ActionInfo is the type-erased representation of a single-entity action.

type AfterFormatFunc

type AfterFormatFunc = formatters.AfterFormatFunc

type AllFlags

type AllFlags struct {
	TaskManagerOptions
	FormatOptions
	logger.Flags
}
var Flags *AllFlags = &AllFlags{
	FormatOptions:      FormatOptions{},
	TaskManagerOptions: *DefaultTaskManagerOptions(),
	Flags: logger.Flags{
		Level:        "info",
		LevelCount:   0,
		JsonLogs:     false,
		ReportCaller: false,
		LogToStderr:  true,
	},
}

func BindAllFlags

func BindAllFlags(flags *pflag.FlagSet, filters ...string) *AllFlags

BindAllFlags adds clicky's logging, task and format flags to the given pflag set. Each flag is annotated with a category so SetGroupedUsage can render them in titled sections.

func BindAllFlagsToCommand

func BindAllFlagsToCommand(cmd *cobra.Command, filters ...string) *AllFlags

BindAllFlagsToCommand binds clicky's flags to cmd's persistent flag set and installs a grouped usage template so --help renders flags in titled sections (Logging, Tasks, Format, then any uncategorized flags under "Flags").

func (*AllFlags) String

func (a *AllFlags) String() string

func (*AllFlags) UseFlags

func (a *AllFlags) UseFlags()

type Args

type Args map[string]any

Args is a custom map type for parsed arguments with helper methods

func MustParseArguments

func MustParseArguments(args []string) Args

MustParseArguments is like ParseArguments but panics on error

func ParseArguments

func ParseArguments(args []string) (Args, error)

ParseArguments parses HTTPie-style arguments and returns an Args type

func (Args) GetString

func (a Args) GetString(key string) string

GetString returns the string value for a key, or empty string if not found or wrong type

func (Args) GetStringSlice

func (a Args) GetStringSlice(key string) []string

GetStringSlice returns the string slice value for a key, or empty slice if not found

func (Args) MarshalJSON

func (a Args) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler interface

func (*Args) UnmarshalJSON

func (a *Args) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler interface

type BeforeFormatFunc

type BeforeFormatFunc = formatters.BeforeFormatFunc

type BulkActionInfo

type BulkActionInfo struct {
	Name              string
	Short             string
	DataFunc          func(flags map[string]string, args []string) (any, error)
	FilterFunc        func(flags map[string]string, args []string) (any, error)
	LookupFunc        func(flags map[string]string, args []string) (any, error)
	ContextLookupFunc ContextLookupFunc
	ListType          reflect.Type
	BindCompletions   func(cmd *cobra.Command)
	ResponseType      reflect.Type
}

BulkActionInfo is the type-erased representation of a bulk action.

type CommandOpenAPIMeta

type CommandOpenAPIMeta struct {
	Entity             string
	Parent             string
	Aliases            []string
	Admin              bool
	Verb               string
	Method             string
	Scope              string
	ActionName         string
	IDParam            string
	SupportsLookup     bool
	SupportsFilterMode bool
	// OptionalID is true when the operation's positional id is optional
	// (WithOptionalID). Such operations are invocable without an id, so the
	// generated REST path must NOT carry an {id} segment — otherwise the no-id
	// call collides with the entity's get-by-id route.
	OptionalID bool
}

CommandOpenAPIMeta is the clicky-specific metadata attached to generated Cobra commands so the RPC/OpenAPI layer can expose entity semantics without guessing from paths or operationIds.

func GetCommandOpenAPIMeta

func GetCommandOpenAPIMeta(cmd *cobra.Command) *CommandOpenAPIMeta

type Context

type Context = flanksourceContext.Context

type ContextDataFunc

type ContextDataFunc = func(ctx context.Context, flags map[string]string, args []string) (any, error)

ContextDataFunc is the context-aware data closure stored for a command. Its signature matches rpc.ContextDataFunc structurally; the RPC converter converts it when wiring RPCOperation.ContextDataFunc. Defined here (the root package) to avoid a clicky -> clicky/rpc import cycle.

func GetContextDataFunc

func GetContextDataFunc(cmd *cobra.Command) ContextDataFunc

GetContextDataFunc returns the context-aware data function registered for a command, if any. Used by the RPC converter to wire ContextDataFunc.

type ContextFilter

type ContextFilter[ListOpts any] interface {
	OptionsWithContext(ctx context.Context, opts ListOpts) map[string]api.Textable
}

ContextFilter is an OPTIONAL extension a Filter may implement when its option set is resolved from request-scoped state (e.g. a per-request database handle) rather than a process global. When the lookup handler runs with a context (the RPC path feeds r.Context(), the CLI feeds cmd.Context()) it prefers OptionsWithContext over Options; filters that don't implement it fall back to the plain Options() path unchanged.

type ContextLookupFunc

type ContextLookupFunc = func(ctx context.Context, flags map[string]string, args []string) (any, error)

ContextLookupFunc is the context-aware variant of a filter lookup closure. When present, the RPC executor prefers it over LookupFunc and feeds the request's context.Context (r.Context() over HTTP, cmd.Context() on the CLI) so a filter's Options/OptionsWithQuery can resolve request-scoped state (e.g. the per-request database handle) instead of a process global.

func GetContextLookupFunc

func GetContextLookupFunc(cmd *cobra.Command) ContextLookupFunc

GetContextLookupFunc returns the context-aware lookup function registered for a command, if any. Used by the RPC converter to wire ContextLookupFunc.

type ContextSearchableFilter

type ContextSearchableFilter[ListOpts any] interface {
	OptionsWithQueryAndContext(ctx context.Context, opts ListOpts, query string, limit int) (options map[string]api.Textable, total int)
}

ContextSearchableFilter is the context-aware counterpart of SearchableFilter: a large/searchable filter whose head and server-side search both need request-scoped state. The lookup handler prefers it over OptionsWithQuery when a context is available.

type Entity

type Entity[T EntityItem, ListOpts any, R any] struct {
	Name string
	// Parent, when set, nests the entity's command under a parent cobra command
	// with that name. The parent command is created lazily by GenerateCLI if it
	// does not already exist.
	Parent string
	// Aliases applied to the generated entity cobra command.
	Aliases []string
	List    func(opts ListOpts) ([]T, error)
	Get     func(id string) (R, error)
	// ListWithContext / GetWithContext / GetWithFlagsAndContext are context-aware
	// variants of List / Get / GetWithFlags. When set they take precedence over
	// their non-context counterparts and receive the request-scoped
	// context.Context (r.Context() over HTTP, cmd.Context() on the CLI). Use them
	// to resolve per-request state (e.g. a database/config bundle) instead of
	// reaching for process globals.
	ListWithContext        func(ctx context.Context, opts ListOpts) ([]T, error)
	ListPaged              func(opts ListOpts) (PagedResult[T], error)
	ListPagedWithContext   func(ctx context.Context, opts ListOpts) (PagedResult[T], error)
	GetWithContext         func(ctx context.Context, id string) (R, error)
	GetWithFlagsAndContext func(ctx context.Context, id string, flags map[string]string) (R, error)
	// GetFlags, when non-nil, is a zero-value struct value implementing
	// ActionFlags whose `flag:"..."` tagged fields are registered as
	// CLI flags on the generated `get` subcommand. The parsed values are
	// passed into GetWithFlags.
	//
	// GetWithFlags is mutually exclusive with Get: when both are set,
	// GetWithFlags wins. Set GetFlags to declare the flag schema and
	// GetWithFlags to receive the typed values.
	GetFlags     ActionFlags
	GetWithFlags func(id string, flags map[string]string) (R, error)
	Create       func(body map[string]any) (R, error)
	Update       func(id string, body map[string]any) (R, error)
	Delete       func(id string) error
	// CreateWithContext / UpdateWithContext / DeleteWithContext are context-aware
	// variants of Create / Update / Delete, mirroring the read-side seam above.
	// When set they take precedence and receive the request-scoped context, so
	// writes target the request's environment rather than a process global.
	CreateWithContext func(ctx context.Context, body map[string]any) (R, error)
	UpdateWithContext func(ctx context.Context, id string, body map[string]any) (R, error)
	DeleteWithContext func(ctx context.Context, id string) error
	Filters           []Filter[ListOpts]

	Actions     []EntityAction
	BulkActions []EntityBulkAction

	// Admin groups admin-only operations (inspect, configure, etc.)
	// that produce different views/columns from the main CRUD operations.
	// Generates subcommands under an "admin" subgroup and routes like /entity/admin/{verb}.
	Admin *Entity[T, ListOpts, R]

	// ValidArgs provides shell completion for the ID argument.
	ValidArgs func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)
}

Entity configures a CRUD resource. All function fields are optional. T is the type returned by List and must implement EntityItem. R is the type returned by Get/Create/Update.

type EntityAction

type EntityAction interface {
	// contains filtered or unexported methods
}

EntityAction is the type-erased registration surface for custom entity actions. Use Action or ActionWithFlags to construct values.

type EntityBuilder

type EntityBuilder[T EntityItem, ListOpts any, R any] struct {
	// contains filtered or unexported fields
}

EntityBuilder provides a fluent API for registering typed entities.

func NewEntity

func NewEntity[T EntityItem, ListOpts any, R any](name string) *EntityBuilder[T, ListOpts, R]

NewEntity starts a typed entity registration.

func (*EntityBuilder[T, ListOpts, R]) Admin

func (b *EntityBuilder[T, ListOpts, R]) Admin(admin Entity[T, ListOpts, R]) *EntityBuilder[T, ListOpts, R]

func (*EntityBuilder[T, ListOpts, R]) Aliases

func (b *EntityBuilder[T, ListOpts, R]) Aliases(aliases ...string) *EntityBuilder[T, ListOpts, R]

func (*EntityBuilder[T, ListOpts, R]) Build

func (b *EntityBuilder[T, ListOpts, R]) Build() Entity[T, ListOpts, R]

func (*EntityBuilder[T, ListOpts, R]) Create

func (b *EntityBuilder[T, ListOpts, R]) Create(fn func(map[string]any) (R, error)) *EntityBuilder[T, ListOpts, R]

func (*EntityBuilder[T, ListOpts, R]) Delete

func (b *EntityBuilder[T, ListOpts, R]) Delete(fn func(string) error) *EntityBuilder[T, ListOpts, R]

func (*EntityBuilder[T, ListOpts, R]) Filters

func (b *EntityBuilder[T, ListOpts, R]) Filters(filters ...Filter[ListOpts]) *EntityBuilder[T, ListOpts, R]

func (*EntityBuilder[T, ListOpts, R]) Get

func (b *EntityBuilder[T, ListOpts, R]) Get(fn func(string) (R, error)) *EntityBuilder[T, ListOpts, R]

func (*EntityBuilder[T, ListOpts, R]) GetWithFlags

func (b *EntityBuilder[T, ListOpts, R]) GetWithFlags(flags ActionFlags, fn func(string, map[string]string) (R, error)) *EntityBuilder[T, ListOpts, R]

func (*EntityBuilder[T, ListOpts, R]) List

func (b *EntityBuilder[T, ListOpts, R]) List(fn func(ListOpts) ([]T, error)) *EntityBuilder[T, ListOpts, R]

func (*EntityBuilder[T, ListOpts, R]) ListPaged

func (b *EntityBuilder[T, ListOpts, R]) ListPaged(fn func(ListOpts) (PagedResult[T], error)) *EntityBuilder[T, ListOpts, R]

func (*EntityBuilder[T, ListOpts, R]) ListPagedWithContext

func (b *EntityBuilder[T, ListOpts, R]) ListPagedWithContext(fn func(context.Context, ListOpts) (PagedResult[T], error)) *EntityBuilder[T, ListOpts, R]

func (*EntityBuilder[T, ListOpts, R]) ListWithContext

func (b *EntityBuilder[T, ListOpts, R]) ListWithContext(fn func(context.Context, ListOpts) ([]T, error)) *EntityBuilder[T, ListOpts, R]

func (*EntityBuilder[T, ListOpts, R]) Parent

func (b *EntityBuilder[T, ListOpts, R]) Parent(parent string) *EntityBuilder[T, ListOpts, R]

func (*EntityBuilder[T, ListOpts, R]) Register

func (b *EntityBuilder[T, ListOpts, R]) Register()

func (*EntityBuilder[T, ListOpts, R]) Update

func (b *EntityBuilder[T, ListOpts, R]) Update(fn func(string, map[string]any) (R, error)) *EntityBuilder[T, ListOpts, R]

func (*EntityBuilder[T, ListOpts, R]) ValidArgs

func (b *EntityBuilder[T, ListOpts, R]) ValidArgs(fn func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective)) *EntityBuilder[T, ListOpts, R]

func (*EntityBuilder[T, ListOpts, R]) WithAction

func (b *EntityBuilder[T, ListOpts, R]) WithAction(action EntityAction) *EntityBuilder[T, ListOpts, R]

func (*EntityBuilder[T, ListOpts, R]) WithBulkAction

func (b *EntityBuilder[T, ListOpts, R]) WithBulkAction(action EntityBulkAction) *EntityBuilder[T, ListOpts, R]

type EntityBulkAction

type EntityBulkAction interface {
	// contains filtered or unexported methods
}

EntityBulkAction is the type-erased registration surface for custom bulk actions. Use BulkAction or BulkFilterAction to construct values.

type EntityInfo

type EntityInfo struct {
	Name        string
	Parent      string
	Aliases     []string
	Type        reflect.Type
	ListType    reflect.Type
	Operations  []EntityOperation
	Actions     []ActionInfo
	BulkActions []BulkActionInfo
	ValidArgs   func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)
	IsAdmin     bool
}

EntityInfo is the type-erased representation stored in the registry.

func GetEntities

func GetEntities() []EntityInfo

GetEntities returns all registered entities.

type EntityItem

type EntityItem interface {
	GetID() string
	GetName() string
}

EntityItem is the interface that all entity types must implement.

type EntityOperation

type EntityOperation struct {
	Verb     string // "list", "get", "create", "update", "delete"
	Method   string // Optional explicit HTTP method for generated RPC/OpenAPI routes.
	DataFunc func(flags map[string]string, args []string) (any, error)
	// ContextDataFunc, when set, is preferred over DataFunc by both the CLI run
	// path (fed cmd.Context()) and the RPC executor (fed r.Context()). Lets the
	// operation resolve request-scoped state instead of process globals.
	ContextDataFunc ContextDataFunc
	// FlagsType, when non-nil, binds typed flags from the given struct type
	// onto the generated cobra command and collects their values into the
	// flag map passed to DataFunc. Used by actions that implement
	// ActionFlags; ignored for the built-in CRUD verbs.
	FlagsType  reflect.Type
	LookupFunc func(flags map[string]string, args []string) (any, error)
	// ContextLookupFunc, when set, is the context-aware filter lookup closure.
	// The RPC converter wires it onto RPCOperation.ContextLookupFunc and the
	// executor prefers it over LookupFunc, feeding the request context.
	ContextLookupFunc ContextLookupFunc
	BindCompletions   func(cmd *cobra.Command)
	ResponseType      reflect.Type
	ResponseArray     bool
	ResponsePaged     bool
	ResponseEntityID  bool
}

EntityOperation represents a single CRUD operation.

type FileSystemOption

type FileSystemOption func(*FileTreeOptions)

FileSystemOption configures NewFileSystem behavior

func WithHiddenFiles

func WithHiddenFiles(show bool) FileSystemOption

WithHiddenFiles controls whether to show hidden files (starting with .)

func WithMaxDepth

func WithMaxDepth(depth int) FileSystemOption

WithMaxDepth sets the maximum directory depth to traverse

type FileTreeNode

type FileTreeNode struct {
	Name     string          `json:"name" pretty:"label"`
	Path     string          `json:"path"`
	Size     int64           `json:"size"`
	Modified time.Time       `json:"modified"`
	IsDir    bool            `json:"is_dir"`
	Children []*FileTreeNode `json:"children,omitempty" pretty:"format=tree"`
	// contains filtered or unexported fields
}

FileTreeNode represents a file or directory with metadata

func NewFileSystem

func NewFileSystem(path string, opts ...FileSystemOption) *FileTreeNode

NewFileSystem creates a FileTreeNode from a directory path

func (FileTreeNode) GetChildren

func (f FileTreeNode) GetChildren() []api.TreeNode

GetChildren implements TreeNode interface

func (FileTreeNode) Pretty

func (f FileTreeNode) Pretty() api.Text

Pretty returns a formatted Text with file info

type FileTreeOptions

type FileTreeOptions struct {
	MaxDepth     int  `flag:"depth" json:"depth,omitempty"`
	ShowHidden   bool `flag:"hidden" json:"hidden,omitempty"`
	ShowSize     bool `flag:"size" json:"size,omitempty"`
	ShowModified bool `flag:"modified" json:"modified,omitempty"`
	ShowAge      bool `flag:"age" json:"age,omitempty"`
}

func (FileTreeOptions) Pretty

func (f FileTreeOptions) Pretty() api.Text

type Filter

type Filter[ListOpts any] interface {
	Key() string
	Label() string
	Lookup(opts *ListOpts) (map[string]api.Textable, error)
	Options(opts ListOpts) map[string]api.Textable
}

Filter resolves raw entity option values into the backend-specific shape and exposes UI metadata for the currently selected and available values.

func LiftFilters

func LiftFilters[Outer any, Inner any](
	filters []Filter[Inner],
	project func(*Outer) *Inner,
) []Filter[Outer]

LiftFilters adapts a Filter[Inner] slice so the same picker definitions work against an outer struct that embeds (or otherwise reaches) the inner filter struct. The project func extracts a *Inner from any *Outer the filter system hands us; lookup keys, labels, options, and selected-value reads/writes flow through unchanged. Use this to keep picker constructors scoped to the inner filter type while letting subcommand options structs — which also carry positional args, behaviour flags, etc. — satisfy Filterable[Outer].

type Filterable

type Filterable[T any] interface {
	Filters() []Filter[T]
}

Filterable is implemented by AddNamedCommand options structs that want to expose typed filter lookups (dropdowns/typeaheads on the web UI, shell completions on the CLI) on the subcommand itself rather than inheriting only the parent entity's Filters slice. The same Filter[T] values that back an Entity's Filters slice work here; AddNamedCommand stores a LookupFunc in the lookupFuncRegistry and binds completions whenever an opts struct satisfies this interface.

Use this whenever a subcommand's flag surface diverges from its parent list view — typically when a positional argument pins one or more identifier filters and the subcommand only exposes the orthogonal (status, type, date range) lenses.

type FormatCallback

type FormatCallback = formatters.FormatCallback

type FormatManager

type FormatManager = formatters.FormatManager

type FormatOptions

type FormatOptions = formatters.FormatOptions

type Help

type Help interface {
	Help() api.Textable
}

type JSONParser

type JSONParser struct{}

JSONParser handles lenient JSON parsing

func NewJSONParser

func NewJSONParser() *JSONParser

NewJSONParser creates a new JSON parser

func (*JSONParser) Parse

func (p *JSONParser) Parse(data []byte) (interface{}, error)

Parse is an alias for ParseJSON for consistency with other parsers

type MultiFilter

type MultiFilter []string

MultiFilter is a string-list flag whose values are interpreted with collections.MatchItems semantics: plain values include, !value excludes.

type Name

type Name interface {
	GetName() string
}

type PageInfo

type PageInfo struct {
	Limit  int   `json:"limit"`
	Offset int   `json:"offset"`
	Total  int64 `json:"total"`
}

PageInfo carries the effective paging window for a list response.

type Paged

type Paged interface {
	PageMetadata() PageInfo
	PageRows() any
}

Paged is implemented by list results that carry total-count metadata.

type PagedResult

type PagedResult[T any] struct {
	Data []T      `json:"data"`
	Page PageInfo `json:"page"`
}

PagedResult is a typed list response with paging metadata.

func NewPagedResult

func NewPagedResult[T any](rows []T, limit, offset int, total int64) PagedResult[T]

NewPagedResult returns a paged result with a stable non-nil data array.

func (PagedResult[T]) PageMetadata

func (p PagedResult[T]) PageMetadata() PageInfo

func (PagedResult[T]) PageRows

func (p PagedResult[T]) PageRows() any

type PrettyParser

type PrettyParser struct {
	*formatters.PrettyFormatter
}

PrettyParser is a wrapper around formatters.PrettyFormatter for backwards compatibility

func NewPrettyParser

func NewPrettyParser() *PrettyParser

NewPrettyParser creates a new parser with adaptive theme

func NewPrettyParserWithTheme

func NewPrettyParserWithTheme(theme api.Theme) *PrettyParser

NewPrettyParserWithTheme creates a new parser with a specific theme

type PromptMultiSelectOptions

type PromptMultiSelectOptions[T any] struct {
	Title    string
	PageSize int
	Limit    int
	Ordered  bool
	Render   func(T) api.Textable
}

PromptMultiSelectOptions configures an ANSI multi-select prompt.

type PromptSelectOptions

type PromptSelectOptions[T any] struct {
	Title        string
	InitialIndex int
	PageSize     int
	Render       func(T) api.Textable
}

PromptSelectOptions configures an ANSI list prompt.

type PromptTextOptions

type PromptTextOptions struct {
	Title       string
	Default     string
	Placeholder string
	Secret      bool
	Validate    func(string) error
}

PromptTextOptions configures an ANSI text prompt.

type ResponseOpenAPIMeta

type ResponseOpenAPIMeta struct {
	Type     reflect.Type
	Array    bool
	Paged    bool
	EntityID bool
}

ResponseOpenAPIMeta describes the static response type for a generated command. It is consumed by the RPC/OpenAPI layer without executing handlers.

func GetCommandResponseMeta

func GetCommandResponseMeta(cmd *cobra.Command) *ResponseOpenAPIMeta

GetCommandResponseMeta returns static response metadata attached to a command.

type RetryConfig

type RetryConfig = task.RetryConfig

Type aliases for backward compatibility

type SearchableFilter

type SearchableFilter[ListOpts any] interface {
	OptionsWithQuery(opts ListOpts, query string, limit int) (options map[string]api.Textable, total int)
}

SearchableFilter is an OPTIONAL extension a Filter may implement when its option set is too large to enumerate in one shot (e.g. a SQL DISTINCT column with thousands of values). The lookup handler type-asserts to it; filters that don't implement it keep the plain Options() behaviour unchanged.

OptionsWithQuery returns at most limit options. An empty query means "the head set": the first limit options plus total = the true distinct count, so the UI can show "… and N more". A non-empty query returns up to limit options matching it (server-side search), letting the UI surface values that sort beyond the head. total is only meaningful for the head (query == "") call.

type SourceResolver

type SourceResolver = api.SourceResolver

SourceResolver is the extension point a StackTrace consults to populate each frame with surrounding source lines. See api.SourceResolver for the interface contract.

type SourceResolverFunc

type SourceResolverFunc = api.SourceResolverFunc

SourceResolverFunc adapts a plain function to SourceResolver.

type Task

type Task = task.Task

Type aliases for backward compatibility

func StartGlobalPhase

func StartGlobalPhase(phaseName string) *Task

StartGlobalPhase starts a new phase tracking task

type TaskFunc

type TaskFunc = task.TaskFunc[any]

Type aliases for backward compatibility

type TaskGroup

type TaskGroup = task.Group

Type aliases for backward compatibility

type TaskManager

type TaskManager = task.Manager

Type aliases for backward compatibility

type TaskManagerOptions

type TaskManagerOptions = task.ManagerOptions

Type aliases for backward compatibility

type TaskOption

type TaskOption = task.Option

Type aliases for backward compatibility

type TaskResult

type TaskResult = task.TaskResult[any]

Type aliases for backward compatibility

type TaskStatus

type TaskStatus = task.Status

Type aliases for backward compatibility

type TypedFilter

type TypedFilter[ListOpts any] interface {
	LookupType() string
}

TypedFilter is an OPTIONAL extension a Filter may implement when the underlying flag type is intentionally broader than the UI control type. For example, date-math flags often remain strings at the CLI layer while the web lookup response should still advertise a from/to date-range control.

type TypedTask

type TypedTask = task.TypedTask[any]

Type aliases for backward compatibility

type WaitResult

type WaitResult = task.WaitResult

Type aliases for backward compatibility

type Waitable

type Waitable = task.Waitable

Type aliases for backward compatibility

Directories

Path Synopsis
ai
api
Package api provides fluent builders for creating styled Text objects.
Package api provides fluent builders for creating styled Text objects.
Package cache defines clicky's generic cache-browser contract: a read/admin API over a key-value cache keyspace (valkey/redis or anything shaped like it) that groups keys into a prefix tree, serves per-key detail, search, whole-keyspace stats, and key/prefix deletion.
Package cache defines clicky's generic cache-browser contract: a read/admin API over a key-value cache keyspace (valkey/redis or anything shaped like it) that groups keys into a prefix tree, serves per-key detail, search, whole-keyspace stats, and key/prefix deletion.
cmd
clicky command
clickylint command
Package docs provides a reusable cobra command group that generates a markdown CLI reference and a clicky-ui surface catalog from a CLI's command tree, as one markdown file per high-level command controller.
Package docs provides a reusable cobra command group that generates a markdown CLI reference and a clicky-ui surface catalog from a CLI's command tree, as one markdown file per high-level command controller.
Package formatters provides a comprehensive data formatting system with support for multiple output formats, Tailwind CSS styling, and fluent text composition.
Package formatters provides a comprehensive data formatting system with support for multiple output formats, Tailwind CSS styling, and fluent text composition.
pdf
internal
gumchoose
Package gumchoose vendors the choose implementation from charmbracelet/gum.
Package gumchoose vendors the choose implementation from charmbracelet/gum.
Package metrics provides a generic timeseries store for recording and querying (timestamp, value) points behind a thin Timeseries interface.
Package metrics provides a generic timeseries store for recording and querying (timestamp, value) points behind a thin Timeseries interface.
Package middleware provides a comprehensive, configurable middleware system for Echo v4.
Package middleware provides a comprehensive, configurable middleware system for Echo v4.
Package task provides a comprehensive concurrent task execution system with progress tracking, status management, and visual rendering capabilities.
Package task provides a comprehensive concurrent task execution system with progress tracking, status management, and visual rendering capabilities.
ui
valkey module

Jump to

Keyboard shortcuts

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