clicky

package module
v1.21.29 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2026 License: Apache-2.0 Imports: 35 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 (
	GetEntities            = entity.GetEntities
	GetEntity              = entity.GetEntity
	GenerateCLI            = entity.GenerateCLI
	RegisterDynamicEntity  = entity.RegisterDynamicEntity
	RegisterSubCommand     = entity.RegisterSubCommand
	RegisterSubCommandFn   = entity.RegisterSubCommandFn
	GetDataFunc            = entity.GetDataFunc
	GetContextDataFunc     = entity.GetContextDataFunc
	GetLookupFunc          = entity.GetLookupFunc
	GetContextLookupFunc   = entity.GetContextLookupFunc
	GetCommandOpenAPIMeta  = entity.GetCommandOpenAPIMeta
	GetCommandResponseMeta = entity.GetCommandResponseMeta
	SetCommandResponseMeta = entity.SetCommandResponseMeta
)

--- non-generic function/var aliases ---

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)) *entity.ActionSpec[R]

func ActionWithContext

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

func ActionWithFlags

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

func ActionWithFlagsAndContext

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

func AddCommand

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

func AddCommandWithContext

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

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

func Admonition

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

func Blockquote added in v1.21.29

func Blockquote(content api.Textable) api.Blockquote

func BulkAction

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

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)) *entity.BulkActionSpec[R]

func BulkFilterAction

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

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 Footnote added in v1.21.29

func Footnote(id string, content api.Textable) api.Footnote

func FootnoteRef added in v1.21.29

func FootnoteRef(id string) api.FootnoteRef

func Footnotes added in v1.21.29

func Footnotes(notes ...api.Footnote) api.Footnotes

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 GetGlobalTaskManagerStats

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

GetGlobalTaskManagerStats returns stats about the global TaskManager

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 Header(level int, content api.Textable) api.Heading

func Heading added in v1.21.29

func Heading(level int, content api.Textable) api.Heading

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 LiftFilters

func LiftFilters[Outer any, Inner any](filters []entity.Filter[Inner], project func(*Outer) *Inner) []entity.Filter[Outer]
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 MustParseMarkdown added in v1.21.29

func MustParseMarkdown(source string, opts ...md.Option) *md.Document

MustParseMarkdown parses markdown source and panics on failure.

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 NewEntity

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

func NewPagedResult

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

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 ParseMarkdown added in v1.21.29

func ParseMarkdown(source string, opts ...md.Option) (*md.Document, error)

ParseMarkdown parses markdown source into a structured Clicky document.

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 entity.EntityItem, ListOpts any, R any](e entity.Entity[T, ListOpts, R])

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 SQL

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

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 = entity.ActionFlags

--- non-generic type aliases ---

type ActionInfo

type ActionInfo = entity.ActionInfo

--- non-generic type aliases ---

type ActionSpec added in v1.21.29

type ActionSpec[R any] = entity.ActionSpec[R]

--- generic type aliases (Go 1.24+; go.mod is 1.26.1) ---

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 = entity.BulkActionInfo

--- non-generic type aliases ---

type BulkActionSpec added in v1.21.29

type BulkActionSpec[R any] = entity.BulkActionSpec[R]

--- generic type aliases (Go 1.24+; go.mod is 1.26.1) ---

type CommandOpenAPIMeta

type CommandOpenAPIMeta = entity.CommandOpenAPIMeta

--- non-generic type aliases ---

type Context

type Context = flanksourceContext.Context

type ContextDataFunc

type ContextDataFunc = entity.ContextDataFunc

--- non-generic type aliases ---

type ContextFilter

type ContextFilter[ListOpts any] = entity.ContextFilter[ListOpts]

--- generic type aliases (Go 1.24+; go.mod is 1.26.1) ---

type ContextLookupFunc

type ContextLookupFunc = entity.ContextLookupFunc

--- non-generic type aliases ---

type ContextSearchableFilter

type ContextSearchableFilter[ListOpts any] = entity.ContextSearchableFilter[ListOpts]

--- generic type aliases (Go 1.24+; go.mod is 1.26.1) ---

type DynamicEntitySpec added in v1.21.29

type DynamicEntitySpec = entity.DynamicEntitySpec

--- non-generic type aliases ---

type DynamicFilter added in v1.21.29

type DynamicFilter = entity.DynamicFilter

--- non-generic type aliases ---

type Entity

type Entity[T entity.EntityItem, ListOpts any, R any] = entity.Entity[T, ListOpts, R]

--- generic type aliases (Go 1.24+; go.mod is 1.26.1) ---

type EntityAction

type EntityAction = entity.EntityAction

--- non-generic type aliases ---

type EntityBuilder

type EntityBuilder[T entity.EntityItem, ListOpts any, R any] = entity.EntityBuilder[T, ListOpts, R]

--- generic type aliases (Go 1.24+; go.mod is 1.26.1) ---

type EntityBulkAction

type EntityBulkAction = entity.EntityBulkAction

--- non-generic type aliases ---

type EntityInfo

type EntityInfo = entity.EntityInfo

--- non-generic type aliases ---

type EntityItem

type EntityItem = entity.EntityItem

--- non-generic type aliases ---

type EntityOperation

type EntityOperation = entity.EntityOperation

--- non-generic type aliases ---

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] = entity.Filter[ListOpts]

--- generic type aliases (Go 1.24+; go.mod is 1.26.1) ---

type Filterable

type Filterable[T any] = entity.Filterable[T]

--- generic type aliases (Go 1.24+; go.mod is 1.26.1) ---

type FormatCallback

type FormatCallback = formatters.FormatCallback

type FormatManager

type FormatManager = formatters.FormatManager

type FormatOptions

type FormatOptions = formatters.FormatOptions

type Help

type Help = entity.Help

--- non-generic type aliases ---

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 = entity.MultiFilter

--- non-generic type aliases ---

type Name

type Name = entity.Name

--- non-generic type aliases ---

type PageInfo

type PageInfo = entity.PageInfo

--- non-generic type aliases ---

type Paged

type Paged = entity.Paged

--- non-generic type aliases ---

type PagedResult

type PagedResult[T any] = entity.PagedResult[T]

--- generic type aliases (Go 1.24+; go.mod is 1.26.1) ---

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 = entity.ResponseOpenAPIMeta

--- non-generic type aliases ---

type RetryConfig

type RetryConfig = task.RetryConfig

Type aliases for backward compatibility

type SearchableFilter

type SearchableFilter[ListOpts any] = entity.SearchableFilter[ListOpts]

--- generic type aliases (Go 1.24+; go.mod is 1.26.1) ---

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] = entity.TypedFilter[ListOpts]

--- generic type aliases (Go 1.24+; go.mod is 1.26.1) ---

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
aichat module
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 entity is the canonical home for clicky's entity + operation model: the entity registry and CLI generation (Entity, EntityBuilder, RegisterEntity, GenerateCLI), the command-function registries (AddCommand, the cobra annotation metadata), the RPC operation model (RPCOperation, Schema, …), and named, reusable filter/lookup definitions that work across both static (Go-struct) and dynamic (JSON-Schema) entities.
Package entity is the canonical home for clicky's entity + operation model: the entity registry and CLI generation (Entity, EntityBuilder, RegisterEntity, GenerateCLI), the command-function registries (AddCommand, the cobra annotation metadata), the RPC operation model (RPCOperation, Schema, …), and named, reusable filter/lookup definitions that work across both static (Go-struct) and dynamic (JSON-Schema) entities.
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