clix

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 17 Imported by: 5 modules, 6 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

clix

CI Go Reference

clix is a Go module of CLI scaffolding for frostyard command-line tools: it wraps charm.land/fang/v2 and spf13/cobra, so a tool defines only its own commands and business logic and gets standardized version strings, 4 common flags, JSON output helpers and a reporter factory.

Status: pre-release. Releases are v0 tags, and the API can change between minor releases.

Documentation: pkg.go.dev/github.com/frostyard/clix

What it does

Piece What it gives you
App, Run, RunContext Build-time version, commit, date and builder metadata, and the entry point that registers the flags and executes the command tree.
The 4 common flags --json, --verbose/-v, --dry-run/-n and --silent/-s, reserved across the whole command tree, with a package-level variable each.
OutputJSON, OutputJSONError The result document on stdout under --json, and the error, message, details envelope for a failure.
NewReporter Progress output as text (stderr), JSON (stdout) or nothing, by flag priority.
BindViper The 4 flags bound to viper keys, with command line > viper > default precedence.
Error rendering A multi-line error on its own lines, a flag kept in lower case, and plain text off a terminal.
Stdout, Stderr Writer seams so a test captures output in a bytes.Buffer instead of swapping os.Stdout.

Install

go get github.com/frostyard/clix

Use

package main

import (
	"os"

	"github.com/frostyard/clix"
	"github.com/spf13/cobra"
)

var version = "dev" // set with -ldflags "-X main.version=1.2.3"

func main() {
	rootCmd := &cobra.Command{Use: "mytool", RunE: func(cmd *cobra.Command, args []string) error {
		clix.NewReporter().Message("doing work")
		_, err := clix.OutputJSON(map[string]string{"status": "ok"})
		return err
	}}
	app := clix.App{Version: version}
	if err := app.Run(rootCmd); err != nil {
		os.Exit(1)
	}
}

App.Run returns the command error, so the caller owns the process exit code. Build with the version injected (App also takes Commit, Date and BuiltBy):

go build -ldflags "-X main.version=1.2.3"

The flags, the reserved-flag rule, reporter priority, error rendering and the Viper binding are in spec: consumer API.

Develop

mise install   # golangci-lint
make ci        # the canonical gate (what CI's Unit Tests job runs)

Design and invariants: docs/design/overview.md.

Where to go next

Documentation

Overview

Package clix provides CLI convenience functions for Frostyard tools, wrapping charm.land/fang/v2 and spf13/cobra with standardized version injection, common flags, JSON output helpers, and reporter factory.

Index

Constants

This section is empty.

Variables

View Source
var (
	JSONOutput bool // --json flag value
	Verbose    bool // --verbose / -v flag value
	DryRun     bool // --dry-run / -n flag value
	Silent     bool // --silent / -s flag value
)

Common flag values, populated when Run() registers persistent flags.

View Source
var Stderr io.Writer

Stderr, when non-nil, replaces the process's standard error for the text reporter returned by NewReporter. Same contract as Stdout: nil means "use the current os.Stderr at call time".

View Source
var Stdout io.Writer

Stdout, when non-nil, replaces the process's standard output for every clix output path (OutputJSON, OutputJSONError, and the JSON reporter from NewReporter). It exists so tests — in clix and in consuming CLIs — can capture output with a bytes.Buffer instead of swapping os.Stdout. It defaults to nil, which means "use the current os.Stdout at call time", so consumers that already swap os.Stdout keep working unchanged.

Functions

func BindViper

func BindViper(cmd *cobra.Command) error

BindViper binds the common flags (--json, --verbose, --dry-run, --silent) to viper keys of the same names. Call it from a PersistentPreRunE if your app uses viper for config management. cobra runs the root's PersistentPreRunE with cmd set to the command actually executing, so BindViper resolves each flag through that command's local, persistent, and inherited flag sets — it is safe to call from any command in the tree, root or subcommand. It returns a clix-namespaced error when a flag is not registered on cmd, which means App.Run has not registered the flags on the root command yet. A nil cmd returns `clix: BindViper: command is nil` rather than panicking, so a mis-wired PersistentPreRunE surfaces as an ordinary error.

func NewReporter

func NewReporter() reporter.Reporter

NewReporter returns the appropriate reporter based on the Silent and JSONOutput flags. Silent mode: NoopReporter (suppresses all output). Silent takes priority over JSON. JSON mode: JSONReporter writing to stdout (for piping/parsing). Text mode: TextReporter writing to stderr (keeps stdout clean for data). The writers are resolved through Stdout / Stderr when set, otherwise the current os.Stdout / os.Stderr.

func OutputJSON

func OutputJSON(data any) (bool, error)

OutputJSON writes data as indented JSON to stdout if JSONOutput is true. Returns (false, nil) when JSON mode is not active. The boolean means "a document reached the writer": data is encoded before the writer is touched, and

  • if encoding fails, a fallback error envelope {"error": true, "message": "failed to encode JSON: …"} is written instead and the encoding error is returned alongside true; if that fallback write fails or is short, false is returned with both errors;
  • if the write itself fails or reports a short write (closed pipe, full disk, a failing Stdout seam), the complete document did not reach the writer: no fallback is attempted and (false, "write JSON output: …") is returned.

Output goes to Stdout when set, otherwise to os.Stdout.

func OutputJSONError

func OutputJSONError(message string, err error) error

OutputJSONError writes a structured error object as JSON to stdout and returns a wrapped error for the caller to propagate. If err is nil, the message alone is used as the error text. If writing the JSON envelope fails, the returned error preserves both the caller's error and the output failure.

Types

type App

type App struct {
	Version string
	Commit  string
	Date    string
	BuiltBy string
}

App holds build-time metadata for a CLI application. Create one in main() and call Run() to execute the root command.

func (*App) Run

func (a *App) Run(cmd *cobra.Command) error

Run registers common persistent flags on cmd, then executes the command via fang.Execute with the formatted version string and signal handling.

The flags --json, --verbose/-v, --dry-run/-n, and --silent/-s are reserved by clix across the entire command tree: the check covers the root command and every descendant at any depth, on both persistent and local flag sets. If cmd or any subcommand already defines one of those names or shorthands, Run returns an error naming the collision before executing anything, rather than letting pflag panic.

Run is a thin wrapper around RunContext using context.Background(); use RunContext directly when the caller needs to bound execution with a deadline or let a supervising process cancel the run.

func (*App) RunContext added in v0.5.0

func (a *App) RunContext(ctx context.Context, cmd *cobra.Command) error

RunContext is Run with a caller-supplied context: it registers common persistent flags on cmd, then executes the command via fang.Execute with the formatted version string and signal handling, running under ctx.

Prefer RunContext over Run when the caller wants to bound execution with a deadline or timeout, or let a supervising process (a test, a parent command, an orchestrator) cancel the run instead of relying solely on the OS signal handling fang.Execute installs for SIGINT/SIGTERM.

RunContext renders a command error with clix's own fang error handler (errors.go): on a terminal each line of a multi-line error, such as an errors.Join error, keeps its own line and a leading flag keeps its lower case; a writer that is not a terminal (a pipe, a journal, a redirected stderr) gets the plain err.Error() and one newline, with no header, style, closing period or usage hint.

The flags --json, --verbose/-v, --dry-run/-n, and --silent/-s are reserved by clix across the entire command tree: the check covers the root command and every descendant at any depth, on both persistent and local flag sets. If cmd or any subcommand already defines one of those names or shorthands, RunContext returns an error naming the collision before executing anything, rather than letting pflag panic.

func (*App) VersionString

func (a *App) VersionString() string

VersionString returns a formatted version string including commit, date, and builder info. Example: "1.2.3 (Commit: abc) (Date: 2026-01-01) (Built by: ci)"

Directories

Path Synopsis
tests
e2e/exampletool command
Command exampletool is the consumer program clix's end-to-end suite builds and runs as a subprocess.
Command exampletool is the consumer program clix's end-to-end suite builds and runs as a subprocess.

Jump to

Keyboard shortcuts

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