conga

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 44 Imported by: 0

README ¶

CONGA

check release Go Reference Go 1.27 docs

CONGA is a batteries-included CLI framework for Go. Model the command line with Go structs, and CONGA derives the flags, environment bindings, configuration, validation, and autocompletion.

CONGA is experimental and pre-1.0: breaking changes increment the minor version. Pin a tag in production. See CHANGELOG.md for release notes.

Features

  • Declarative command schemas: flags, positional arguments, and subcommands defined as Go struct fields.
  • Value resolution across command-line flags, environment variables, configuration files, and defaults, with origin tracking.
  • Multi-format configuration decoding for JSON, YAML, TOML, and HCL, with directory search paths and cascading file merges.
  • Built-in autocompletion for Bash, Zsh, Fish, PowerShell, Elvish, and NuShell.
  • Rich validation constraints (range, len, enum, xor, and) evaluated at startup and parse time.
  • Opt-in modular architecture keeping unreferenced subsystems pruned at link time.

Installation

Requires Go 1.27+.

go get github.com/conga-sh/conga@latest

Pin a specific release with @v0.x.y when you need reproducible builds.

Quickstart

package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/conga-sh/conga"
)

type CLI struct {
	Name conga.OptionalFlag[string] `default:"World" help:"Name of the person to greet" short:"n"`
	Loud conga.OptionalFlag[bool]   `help:"Print greeting in uppercase"           short:"l"`
}

func (c *CLI) Run(ctx context.Context, session *conga.Session) error {
	greeting := fmt.Sprintf("Hello, %s!", c.Name.Get())
	if c.Loud.Get() {
		greeting = strings.ToUpper(greeting)
	}

	fmt.Fprintln(session.Stdout(), greeting)

	return nil
}

func main() {
	app := conga.New[CLI]().
		Name("hello").
		Description("Minimal single-command hello world CLI").
		Version("1.0.0")

	if err := app.Run(); err != nil {
		app.Exit(err)
	}
}
go run . --name conga --loud
HELLO, CONGA!

Fields become flags, and Run reads their resolved values with Get().

Value Precedence

Flags resolve through a deterministic 4-tier precedence ladder:

  1. Command-line flags
  2. Environment variables
  3. Configuration files
  4. Struct field defaults

Positional arguments bind only to command-line tokens, falling back to default.

Struct Tags

Common metadata and validation tags:

Tag Example Description
short short:"p" Single-character flag alias (-p)
default default:"8080" Fallback value if no other source supplies one
env env:"PORT" Environment variable binding
help help:"Port to bind" Usage description shown in --help
range range:"1..65535" Inclusive bounds for numbers, durations, and byte sizes
enum enum:"json,yaml,text" Restricts accepted values to a fixed set
xor xor:"auth" Mutual exclusivity group (only one flag in group allowed)
config config:"listen_port" Configuration file key name (or "-" to ignore)

For advanced constraints (len, items, and, conga directives) and per-container applicability, see the Struct Tag Reference.

Subcommands

Define subcommands by nesting struct types inside conga.Command[T]:

type RootCLI struct {
	Deploy conga.Command[DeployCmd] `summary:"Deploy artifacts to a target cluster"`
}

type DeployCmd struct {
	Target conga.RequiredFlag[string] `short:"t" help:"Deployment target"`
}

func (d *DeployCmd) Run(ctx context.Context, session *conga.Session) error {
	fmt.Fprintf(session.Stdout(), "Deploying to %s\n", d.Target.Get())
	return nil
}

Built-ins

Every CONGA application includes built-in operational flags:

  • --help: Prints command syntax and flag descriptions.
  • --version: Prints version and build information.
  • --why: Debugging flag that prints a provenance report explaining where every flag value came from (CLI, env, config, or default) and which competing sources were overridden. Enable the text report with app.EnableWhy(); pass conga.WhyJSON() (app.EnableWhy(conga.WhyJSON())) to also enable the machine-readable --why=json document.

For subcommand-based CLIs, CONGA provides HelpCommand, VersionCommand, and CompletionCommand. See the Built-ins Reference.

Modular Architecture

CONGA isolates heavier dependencies—such as configuration decoders (decoder/{json,yaml,toml,hcl}) and shell completion drivers—into opt-in packages so unused features are pruned at link time.

Documentation

License

CONGA is released under the MIT License.

Documentation ¶

Overview ¶

Package conga builds command-line applications from Go structs.

An application is a Go struct whose fields declare its flags, positional arguments, and subcommands. CONGA inspects the struct once at startup, then populates the fields from command-line arguments, environment variables, and configuration files.

Declaring a command ¶

Fields use container types to define the CLI interface:

Struct tags declare names, help text, fallback values, feature-gating (feature), and constraints such as range, len, enum, xor, and and. For the full tag specification, see https://docs.conga.sh/reference/struct-tags/.

Commands execute by implementing Runner. Lifecycle hooks can be added with Validator, PreRunner, PostRunner, and Finalizer.

Example ¶

type ServerCLI struct {
	Host conga.OptionalFlag[string] `short:"H" default:"127.0.0.1" help:"Address to bind"`
	Port conga.RequiredFlag[int]    `short:"p" env:"PORT" range:"1..65535" help:"Port number"`
}

func (s *ServerCLI) Run(ctx context.Context, session *conga.Session) error {
	fmt.Fprintf(session.Stdout(), "Listening on %s:%d\n", s.Host.Get(), s.Port.Get())
	return nil
}

func main() {
	app := conga.New[ServerCLI]()

	if err := app.Run(); err != nil {
		app.Exit(err)
	}
}

Value resolution ¶

Flags resolve through four sources in order of precedence:

  1. Command-line flags
  2. Environment variables
  3. Configuration files
  4. Struct field default tags

Positional arguments resolve only from command-line arguments and default tags. OptionalFlag.Source reports where a resolved value originated.

For scalar and slice flags, the winning tier replaces lower-precedence sources entirely. In contrast, map flags and Features merge key by key across tiers in ascending precedence (default < config < env < CLI): each source overlays only the keys it specifies, preserving lower-tier entries for unmentioned keys.

See https://docs.conga.sh/explanation/value-precedence/.

Built-ins ¶

CONGA provides built-in flags for standard operational tasks:

  • --help: prints command syntax and flag descriptions. Enabled by default; disable with App.DisableHelpFlag.
  • --version: prints version and build information. Enabled by default; disable with App.DisableVersionFlag.
  • --why: prints a provenance report showing where every flag resolved from (CLI flag, environment variable, configuration file, or default tag) and which competing values were overridden. Useful when debugging complex configurations. Enable with App.EnableWhy.

When a built-in flag is passed, CONGA prints the output to standard output and exits immediately without running command logic; App.Run returns nil.

For applications that prefer subcommands over flags, CONGA also provides HelpCommand, VersionCommand, and CompletionCommand. Declare them directly as struct fields on the command. These subcommands bypass lifecycle hooks and render their output to standard output.

See https://docs.conga.sh/reference/builtins/.

Execution and streams ¶

App.Run executes with a default context that cancels on SIGINT and SIGTERM; App.RunContext executes with the caller's context. An App executes exactly once; a second call panics. A zero-value App is usable and installs the same defaults as New on first use.

Commands receive a *Session providing invocation metadata and configured I/O streams (Session.Stdout, Session.Stderr, Session.Stdin). Streams default to the standard process streams (os.Stdout, os.Stderr, os.Stdin), and can be redirected on the builder via App.Stdout, App.Stderr, or App.Stdin for testing or embedded execution.

App.Exit reports errors and exits with status 2 for usage errors or status 1 for runtime failures. A nil error exits with status 0.

See https://docs.conga.sh/explanation/lifecycle/.

Optional subsystems ¶

Several features are opt-in:

  • Shell completion: call App.EnableCompletion to generate completion scripts for Bash, Zsh, Fish, PowerShell, Elvish, and Nushell.
  • Configuration decoders: import and register decoders such as decoder/yaml using App.RegisterDecoder.
  • Dotenv files: call App.Dotenv to load variables from .env files.
  • Feature toggles: call App.EnableFeatures to activate feature toggles declared with Features and gate execution behind feature tags.

Requirements ¶

CONGA requires Go 1.27 or newer. Tooling such as conga-lint and conga-reorder likewise requires a Go 1.27+ toolchain to parse and analyze method-level generic type parameters.

Index ¶

Examples ¶

Constants ¶

View Source
const (
	// SourceNone indicates no value was supplied and the container holds
	// its zero value.
	SourceNone = container.SourceNone

	// SourceDefault indicates the container value originated from a struct field's
	// default tag. Changed() reports false for defaulted values.
	SourceDefault = container.SourceDefault

	// SourceConfig indicates the container value was resolved from a configuration file.
	SourceConfig = container.SourceConfig

	// SourceEnv indicates the container value was resolved from an environment variable.
	SourceEnv = container.SourceEnv

	// SourceCLI indicates the container value was explicitly passed on the command line
	// as a flag or positional argument.
	SourceCLI = container.SourceCLI
)
View Source
const (
	// TagKindBool declares a strict boolean struct tag.
	//
	// Absence evaluates to false. Only "", "true", and "false" are accepted values;
	// typos and invalid strings fail during schema compilation rather than silently
	// misconfiguring the application.
	TagKindBool = spec.TagKindBool

	// TagKindString declares a raw string struct tag.
	//
	// Absence leaves the tag undeclared. An all-whitespace value fails during schema
	// compilation. A custom Validate hook can be attached to [TagSpec] to enforce
	// domain-specific syntax during schema compilation.
	TagKindString = spec.TagKindString
)

Variables ¶

View Source
var (
	// ErrSchema indicates the command schema could not be constructed from the struct definition.
	//
	// This occurs when a struct tag is unrecognized, a tag combination is invalid,
	// a field type is unsupported, or ancestor flag shadowing is detected.
	// ErrSchema represents a developer defect detected during schema compilation.
	ErrSchema = spec.ErrSchema

	// ErrParse indicates command-line tokens could not be parsed.
	//
	// This category includes unknown flags, missing flag arguments, unexpected positional
	// arguments, and unrecognized subcommand names. All parse errors classify as usage
	// errors ([IsUsageError] reports true).
	ErrParse = errors.New("parse error")

	// ErrCoerce indicates a raw string value could not be converted to its target type.
	//
	// This category includes numeric parsing failures, unparseable durations, malformed
	// URLs, and errors returned by [encoding.TextUnmarshaler] or [ContextAwareTextUnmarshaler].
	// All coercion errors classify as usage errors ([IsUsageError] reports true).
	ErrCoerce = coerce.ErrCoerce

	// ErrValidation indicates a flag or argument constraint was violated.
	//
	// This category covers violations of struct tags such as range, len, enum,
	// xor, and and, as well as failures returned by [SelfValidator.Validate].
	// All validation errors classify as usage errors ([IsUsageError] reports true).
	ErrValidation = errors.New("validation error")

	// ErrConfig indicates a configuration file or .env file could not be loaded.
	//
	// This category includes missing explicit configuration files, file read permission
	// errors, file size limit violations (exceeding the 16MB DoS threshold), and
	// syntax errors returned by configuration decoders.
	ErrConfig = sentinel.ErrConfig
)

Base error categories classifying execution and configuration failures.

Functions ¶

func IsCompletionError ¶

func IsCompletionError(err error) bool

IsCompletionError reports whether err was caused by an internal failure during shell completion evaluation.

func IsUsageError ¶

func IsUsageError(err error) bool

IsUsageError reports whether err was caused by invalid command-line input.

Returns true if err implements UsageError and reports true, or if err wraps ErrParse, ErrCoerce, or ErrValidation. Returns false for developer schema errors (ErrSchema), configuration file failures (ErrConfig), runtime errors returned by Runner.Run, or nil errors.

Types ¶

type App ¶

type App[T any] struct {
	// contains filtered or unexported fields
}

App manages the configuration, parsing, and execution lifecycle of a command-line application rooted in struct T.

The command struct T (or its selected subcommand) executes by implementing Runner.

An App is constructed with New, configured through chained builder methods, and executed with App.Run (passing the default signal-canceling context to Runner.Run) or App.RunContext (passing the caller's context).

An App executes once; calling App.Run or App.RunContext a second time panics. Builder methods must be called before execution begins.

See https://docs.conga.sh/explanation/lifecycle/.

func New ¶

func New[T any](root ...*T) *App[T]

New returns an App builder for the root command struct T.

Calling New[T]() without arguments is the standard pattern. CONGA manages the root struct lifecycle: it instantiates T, binds flags and arguments to its fields, and executes its Runner.Run method.

Passing an existing root instance binds that instance instead of allocating a fresh one, so callers can inspect bound container values after execution completes.

Panics:

  • If root contains more than one pointer.
  • If the supplied pointer is nil.
Example ¶

Declare flags as typed fields, implement conga.Runner, and call conga.App.Run.

package main

import (
	"context"
	"fmt"

	"github.com/conga-sh/conga"
)

// CLI is a minimal single-command application.
type CLI struct {
	Name conga.OptionalFlag[string] `default:"world" help:"Who to greet"`
}

func (c *CLI) Run(_ context.Context, session *conga.Session) error {
	_, err := fmt.Fprintf(session.Stdout(), "Hello, %s!\n", c.Name.Get())

	return err
}

func main() {
	app := conga.New[CLI]().
		Args([]string{"--name", "gopher"})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}
}
Output:
Hello, gopher!
Example (Inspect) ¶

Pass an existing struct pointer to inspect bound values after execution.

package main

import (
	"context"
	"fmt"

	"github.com/conga-sh/conga"
)

// InspectCLI is an application whose bound fields are read after execution.
type InspectCLI struct {
	Port conga.OptionalFlag[int] `help:"Port"`
}

func (c *InspectCLI) Run(_ context.Context, _ *conga.Session) error {
	return nil
}

func main() {
	cli := &InspectCLI{}
	app := conga.New(cli).
		Args([]string{"--port", "9000"})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}

	fmt.Println(cli.Port.Get())
}
Output:
9000

func (*App[T]) AllowTags ¶

func (a *App[T]) AllowTags(tags ...string) *App[T]

AllowTags adds struct tag keys that tag validation accepts.

CONGA inspects all struct tags on command fields when the schema is compiled. Unknown tag keys (such as misspelled hlp or deflt), invalid constraint combinations, or tags applied to unsupported field types cause App.Run or App.RunContext to return an error wrapping ErrSchema.

Common third-party tags (json, yaml, validate, db, and others listed in the package documentation) are permitted out of the box; register any others your structs carry (for example bson or a custom annotation):

type ServerCLI struct {
	Port  conga.OptionalFlag[int]    `default:"8080" help:"Listening port" short:"p"`
	Token conga.RequiredFlag[string] `help:"API access token" audit:"mask"`
}

app := conga.New[ServerCLI]().AllowTags("audit")

Registered keys are ignored by the schema builder on all commands, subcommands, and nested structs; multiple calls append to the permitted tag set. Keys are matched exactly, so a misspelling of a registered key is still rejected.

func (*App[T]) Args ¶

func (a *App[T]) Args(args []string) *App[T]

Args overrides the command-line argument slice parsed by the application. Defaults to os.Args[1:].

app.Args([]string{"--port", "9000", "server"})

See https://docs.conga.sh/how-to/test-a-command/.

func (*App[T]) ConfigOptions ¶

func (a *App[T]) ConfigOptions(options ...ConfigOption) *App[T]

ConfigOptions sets how CONGA discovers and merges config files. Options come from the ConfigOption constructors: ConfigPaths, ConfigExplicit, ConfigCascading, and ConfigLoader, each declaring one resolution rule.

Config files also require a registered decoder (see App.RegisterDecoder), unless a ConfigLoader supplies the configuration document programmatically instead. See https://docs.conga.sh/how-to/manage-config-files/.

func (*App[T]) Deprecated ¶

func (a *App[T]) Deprecated(reason string) *App[T]

Deprecated marks the entire application as deprecated.

Each run that reaches the command lifecycle first prints a warning containing the reason text to standard error. Execution continues normally; deprecation warnings are non-fatal. Requests that render a built-in and return early, such as --help, --version, and --why, print no warning.

Declare the deprecation with this method, not a Deprecated method on the root struct, which fails schema compilation with ErrSchema. To deprecate an individual optional flag or subcommand, use the deprecated struct tag.

Example ¶

A deprecated application warns on standard error, then runs normally.

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/conga-sh/conga"
)

// DeprecatedCLI is an application that warns when it runs.
type DeprecatedCLI struct{}

func (c *DeprecatedCLI) Run(_ context.Context, session *conga.Session) error {
	_, err := fmt.Fprintln(session.Stdout(), "running")

	return err
}

func main() {
	app := conga.New[DeprecatedCLI]().
		Name("oldtool").
		Deprecated("use newtool").
		Stderr(os.Stdout).
		Args([]string{})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}
}
Output:
WARNING: oldtool is deprecated: use newtool
running

func (*App[T]) Description ¶

func (a *App[T]) Description(desc string) *App[T]

Description sets the long-form application overview, rendered at the top of the root command's help screen below the usage header.

A subcommand supplies its own long-form overview by implementing DescriptionProvider, and its one-line synopsis with the summary tag.

See https://docs.conga.sh/how-to/customize-help-screens/.

func (*App[T]) DisableHelpFlag ¶

func (a *App[T]) DisableHelpFlag() *App[T]

DisableHelpFlag stops CONGA from injecting the built-in --help flag, freeing that name for your own flags. Session.Help, error-driven usage summaries, and an explicit HelpCommand still work.

See https://docs.conga.sh/reference/builtins/.

func (*App[T]) DisableVersionFlag ¶

func (a *App[T]) DisableVersionFlag() *App[T]

DisableVersionFlag stops CONGA from injecting the built-in --version flag, freeing that name for your own flags. Session.Version, version metadata in --why reports, and an explicit VersionCommand still work.

See https://docs.conga.sh/reference/builtins/.

func (*App[T]) Dotenv ¶

func (a *App[T]) Dotenv(paths ...string) *App[T]

Dotenv enables loading environment variables from .env files into the process environment.

When called without arguments, Dotenv probes for .env followed by .env.local in the current working directory, loading both if present. When explicit paths are supplied, CONGA loads only the specified files in the given order.

Files apply in order: a key defined in more than one file takes the value from the last file that defines it, so .env.local overrides .env. Variables already present in the process environment are never overwritten and outrank every file.

Files must use KEY=VALUE syntax. Empty lines and lines starting with # are ignored; optional export prefixes and surrounding single or double quotes are stripped.

Variables are written into the process environment through the setenv function configured by App.SetenvFunc, which defaults to os.Setenv.

Dotenv files enforce a strict 16MB file size limit to prevent unbounded memory allocation. Files exceeding the limit or missing explicit paths cause execution to halt with an error wrapping ErrConfig.

See https://docs.conga.sh/how-to/load-env-files/.

func (*App[T]) EnableCompletion ¶

func (a *App[T]) EnableCompletion() *App[T]

EnableCompletion activates shell completion: script generation for Bash, Zsh, Fish, PowerShell, Elvish, and Nushell, plus the hidden __complete wire protocol. A mounted CompletionCommand requires it.

See https://docs.conga.sh/how-to/enable-shell-completion/.

func (*App[T]) EnableFeatures ¶

func (a *App[T]) EnableFeatures() *App[T]

EnableFeatures activates feature toggles and gated command/flag execution. Applications declaring a conga.Features container or feature struct tags require it.

Example:

app := conga.New[CLI]().
	EnableFeatures()

See https://docs.conga.sh/how-to/feature-flags/.

Example ¶

EnableFeatures activates feature toggles and gated flags.

package main

import (
	"context"
	"fmt"

	"github.com/conga-sh/conga"
)

// BuildExperiments declares feature toggles for ExampleFeatures and ExampleApp_EnableFeatures.
type BuildExperiments struct {
	RemoteCache      bool `help:"Experimental distributed CAS artifact cache"`
	SandboxIsolation int  `enum:"1,2"                                         help:"Experimental build sandbox isolation: 1=chroot, 2=rootless-container"`
}

// BuildCLI is an application with feature toggles and gated flags.
type BuildCLI struct {
	Features       conga.Features[BuildExperiments] `flag:"feature-gates"`
	Target         conga.RequiredArg[string]        `help:"Build target"`
	CacheEndpoint  conga.OptionalFlag[string]       `feature:"remote-cache"      help:"CAS server gRPC endpoint"`
	ContainerImage conga.OptionalFlag[string]       `feature:"sandbox-isolation" help:"OCI build container image"`
}

func (c *BuildCLI) Run(_ context.Context, session *conga.Session) error {
	experiments := c.Features.Get()
	_, err := fmt.Fprintf(session.Stdout(),
		"remote-cache=%t sandbox=%d endpoint=%s image=%s target=%s\n",
		experiments.RemoteCache,
		experiments.SandboxIsolation,
		c.CacheEndpoint.Get(),
		c.ContainerImage.Get(),
		c.Target.Get(),
	)

	return err
}

func main() {
	app := conga.New[BuildCLI]().
		EnableFeatures().
		Args([]string{"main"})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}

}
Output:
remote-cache=false sandbox=0 endpoint= image= target=main

func (*App[T]) EnableWhy ¶

func (a *App[T]) EnableWhy(opts ...WhyOption) *App[T]

EnableWhy activates the built-in --why flag. When passed, CONGA skips command execution and prints a provenance report to standard output showing where every flag value originated (CLI, environment, configuration file, or struct default) and why competing sources were overridden.

By default, App.EnableWhy links only the human-readable text table renderer, keeping the binary footprint lean and dead-code eliminating the RFC 8259 JSON serialization pipeline. Pass WhyJSON to opt into machine-readable provenance reports:

app.EnableWhy(conga.WhyJSON())

See https://docs.conga.sh/how-to/inspect-value-provenance/.

func (*App[T]) EnvPrefix ¶

func (a *App[T]) EnvPrefix(prefix string) *App[T]

EnvPrefix sets the global environment variable prefix applied to derived flag bindings.

CONGA appends a trailing underscore when the prefix lacks one, so the prefix MYAPP becomes MYAPP_. Flags without an explicit env tag derive their variable name from the prefix and the uppercase flag name, with hyphens replaced by underscores. A field declaring an env tag uses that name verbatim and ignores the prefix:

EnvPrefix("MYAPP")  --database-url  =>  MYAPP_DATABASE_URL
EnvPrefix("MYAPP")  env:"PORT"      =>  PORT

Environment variable bindings outrank configuration file values and defaults, but yield to explicit command-line flags.

See https://docs.conga.sh/how-to/bind-environment-variables/.

func (*App[T]) Examples ¶

func (a *App[T]) Examples(examples string) *App[T]

Examples sets application usage examples displayed on the root help screen.

Examples appear in a dedicated "Examples:" section on --help. Indented lines are preserved as formatted code or command lines:

app.Examples(`  # Start server on custom port
  myapp --port 9000

  # Run with verbose logging
  myapp -v`)

See https://docs.conga.sh/how-to/customize-help-screens/.

func (*App[T]) Exit ¶

func (a *App[T]) Exit(err error)

Exit terminates the process with an exit status mapped from err, using the configured exit function (see App.ExitFunc, defaults to os.Exit).

Exit accepts the error returned by App.Run or App.RunContext.

All post-run cleanup (PostRunner.PostRun and Finalizer.Finally hooks) completes before App.Run returns, so Exit runs only after teardown finishes.

Exit code conventions:

  • A nil err exits with status 0 and no output.
  • Exit code 1: runtime errors from command execution (Runner.Run or lifecycle hooks), developer schema defects (ErrSchema), and configuration failures (ErrConfig, including .env loading).
  • Exit code 2: usage errors (IsUsageError reports true for parse, coercion, and validation failures) and internal completion failures.

Usage error rendering follows UsageOnErrorMode, except for self-describing value errors (coercion failures and value-constraint violations), which always print the error line alone.

See https://docs.conga.sh/explanation/error-reporting/.

func (*App[T]) ExitFunc ¶

func (a *App[T]) ExitFunc(exitHandler func(code int)) *App[T]

ExitFunc overrides the function App.Exit calls to terminate the process. Defaults to os.Exit. Passing a nil handler is a no-op.

var exitCode int
app.ExitFunc(func(code int) { exitCode = code })

func (*App[T]) HelpFooter ¶

func (a *App[T]) HelpFooter(footer string) *App[T]

HelpFooter sets text rendered at the bottom of every help screen, after the flags, arguments, and subcommands. It applies to the root command and all subcommands.

See https://docs.conga.sh/how-to/customize-help-screens/.

func (*App[T]) Name ¶

func (a *App[T]) Name(name string) *App[T]

Name sets the root application binary name.

The configured name appears in generated usage syntax, help headers, version strings, and error prefixes. When omitted, CONGA falls back to the invoked binary name derived from os.Args[0].

func (*App[T]) Predictor ¶

func (a *App[T]) Predictor(name string, predictor predict.Predictor) *App[T]

Predictor registers a named completion predictor for shell autocompletion.

Command struct fields reference registered predictors using the predictor struct tag.

Panics:

  • If name is empty.
  • If name matches a reserved built-in predictor name or alias (file, dirs, executables, symlinks, none).
  • If a predictor with the same name has already been registered.

See https://docs.conga.sh/how-to/wire-custom-completion/.

Example ¶

Register a named predictor and reference it from a flag's predictor tag; shells complete the flag's values from the registered predictor.

package main

import (
	"context"

	"github.com/conga-sh/conga"
	"github.com/conga-sh/conga/predict"
)

// RegionCLI is an application whose flag completes from a registered predictor.
type RegionCLI struct {
	Region conga.OptionalFlag[string] `help:"Deployment region" predictor:"regions"`
}

func (c *RegionCLI) Run(_ context.Context, _ *conga.Session) error {
	return nil
}

func main() {
	app := conga.New[RegionCLI]().
		EnableCompletion().
		Predictor("regions", predict.Values("eu-west-1", "us-east-1", "us-west-2")).
		Args([]string{"__complete", "fish", "--region", ""})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}

}
Output:
eu-west-1
us-east-1
us-west-2

func (*App[T]) RegisterDecoder ¶

func (a *App[T]) RegisterDecoder(extension string, decoder ConfigDecoder) *App[T]

RegisterDecoder registers a decoder for a configuration file extension:

app.RegisterDecoder(".yaml", yaml.Decode)

The extension is normalized automatically: leading asterisks and dots are stripped, whitespace is trimmed, and characters are converted to lowercase. For example, ".yaml", "yaml", and "*.YAML" are all equivalent.

The decoder callback receives the raw file bytes and unmarshals them into a nested map[string]any with string keys. Registering an extension that was previously registered overwrites the earlier registration.

Decoders for JSON, YAML, TOML, and HCL ship with CONGA in the decoder/json, decoder/yaml, decoder/toml, and decoder/hcl packages.

See https://docs.conga.sh/reference/decoders/.

Example ¶

Register a configuration decoder so flags resolve from a file named with --config-file.

package main

import (
	"context"
	"fmt"

	"github.com/conga-sh/conga"
	"github.com/conga-sh/conga/decoder/toml"
)

// ConfigCLI is an application whose flags resolve from a configuration file.
type ConfigCLI struct {
	Config conga.ConfigFile           `help:"Configuration file"`
	Host   conga.OptionalFlag[string] `help:"Bind host"`
	Port   conga.OptionalFlag[int]    `help:"Listen port"`
}

func (c *ConfigCLI) Run(_ context.Context, session *conga.Session) error {
	_, err := fmt.Fprintf(session.Stdout(), "port=%d host=%s\n", c.Port.Get(), c.Host.Get())

	return err
}

func main() {
	app := conga.New[ConfigCLI]().
		RegisterDecoder(".toml", toml.Decode).
		Args([]string{"--config-file", "testdata/fixtures/example_config.toml"})

	if err := app.Run(); err != nil {
		panic(err)
	}

}
Output:
port=8080 host=localhost

func (*App[T]) RegisterMap ¶

func (a *App[T]) RegisterMap[M ~map[K]V, K ~string, V any](opts ...RegisterTypeOption) *App[T]

RegisterMap registers a parser and optional completion predictor for a map type with string-compatible keys. It supports both standard map[K]V types and custom named types whose underlying type is map[K]V.

Key types must have an underlying type of string (~string). Value types (V) can be any type supported by conga's coercion system, including types with custom text unmarshalers or types registered via App.RegisterType. Maps with both a string key and a string value bind natively and need no registration.

Example:

type PortMap map[string]int
app := conga.New[CLI]().
	RegisterMap[PortMap]().
	RegisterMap[map[string]time.Duration]()

Flags accept repeated or comma-separated pairs:

--flag k1=v1 --flag k2=v2
--flag k1=v1,k2=v2

Panics:

  • If the receiver App is nil.

See https://docs.conga.sh/how-to/add-custom-flag-types/.

Example ¶

Register a map type so flags and arguments accept key=value pairs.

package main

import (
	"context"
	"fmt"

	"github.com/conga-sh/conga"
)

// ReplicasCLI is an application whose flag accepts a map of counts.
type ReplicasCLI struct {
	Replicas conga.OptionalFlag[map[string]int] `help:"Replica counts"`
}

func (c *ReplicasCLI) Run(_ context.Context, session *conga.Session) error {
	replicas := c.Replicas.Get()
	_, err := fmt.Fprintf(session.Stdout(), "api=%d web=%d\n", replicas["api"], replicas["web"])

	return err
}

func main() {
	app := conga.New[ReplicasCLI]().
		RegisterMap[map[string]int]().
		Args([]string{"--replicas", "api=2,web=3"})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}

}
Output:
api=2 web=3

func (*App[T]) RegisterType ¶

func (a *App[T]) RegisterType[U any](parser func(string) (U, error), opts ...RegisterTypeOption) *App[T]

RegisterType registers a parser and optional completion predictor for custom type U on the application builder.

The parser callback converts raw string input from flags, arguments, or environment variables into an instance of type U. A returned error is wrapped in ErrCoerce.

If type U was previously registered, the new parser and predictor overwrite the existing registration.

Panics:

  • If the receiver App is nil.
  • If parser is nil.

See https://docs.conga.sh/how-to/add-custom-flag-types/.

Example ¶

Register a parser so flags and arguments of a custom type accept its text form.

package main

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	"github.com/conga-sh/conga"
)

// Percent is a whole-number percentage between 0% and 100%, parsed from flag
// values such as "75%" or "75".
type Percent int

// String returns the percentage in its canonical flag form, for example "75%".
func (p Percent) String() string {
	return strconv.Itoa(int(p)) + "%"
}

// PercentCLI is an application whose flag accepts a percentage threshold.
type PercentCLI struct {
	Threshold conga.OptionalFlag[Percent] `default:"50%" help:"Alert threshold"`
}

func (c *PercentCLI) Run(_ context.Context, session *conga.Session) error {
	_, err := fmt.Fprintf(session.Stdout(), "threshold=%v\n", c.Threshold.Get())

	return err
}

func main() {
	app := conga.New[PercentCLI]().
		RegisterType(parsePercent).
		Args([]string{"--threshold", "75%"})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}
}

// parsePercent parses a "0%".."100%" flag value, with or without the trailing
// percent sign, for App.RegisterType.
func parsePercent(raw string) (Percent, error) {
	digits := strings.TrimSuffix(raw, "%")

	value, err := strconv.ParseUint(digits, 10, 8)
	if err != nil || value > 100 {
		return 0, fmt.Errorf("invalid percentage %q: want 0%%-100%%", raw)
	}

	return Percent(value), nil
}
Output:
threshold=75%
Example (External) ¶

Register a parser for a type CONGA cannot parse natively, such as a standard library type that does not implement encoding.TextUnmarshaler.

package main

import (
	"context"
	"fmt"
	"net"

	"github.com/conga-sh/conga"
)

// NetworkCLI is an application whose flag accepts a CIDR network.
type NetworkCLI struct {
	Network conga.OptionalFlag[*net.IPNet] `help:"Allowed network in CIDR notation" placeholder:"CIDR"`
}

func (c *NetworkCLI) Run(_ context.Context, session *conga.Session) error {
	_, err := fmt.Fprintf(session.Stdout(), "network=%s\n", c.Network.Get())

	return err
}

func main() {
	app := conga.New[NetworkCLI]().
		RegisterType(parseCIDR).
		Args([]string{"--network", "192.168.1.7/24"})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}
}

// parseCIDR adapts net.ParseCIDR to the App.RegisterType parser signature.
// net.ParseCIDR itself returns three values (net.IP, *net.IPNet, error), so it
// cannot be passed to RegisterType, which takes func(string) (U, error).
func parseCIDR(raw string) (*net.IPNet, error) {
	_, network, err := net.ParseCIDR(raw)
	if err != nil {
		return nil, fmt.Errorf("invalid CIDR %q: %w", raw, err)
	}

	return network, nil
}
Output:
network=192.168.1.0/24

func (*App[T]) Run ¶

func (a *App[T]) Run() error

Run executes the application, passing a default context to the command's Runner.Run method and lifecycle hooks. The default context cancels when an os.Interrupt (SIGINT) or syscall.SIGTERM signal is received.

For callers supplying their own context, use App.RunContext.

Panics:

  • If the App has already been executed: an App instance runs exactly once.

See https://docs.conga.sh/explanation/lifecycle/.

func (*App[T]) RunContext ¶

func (a *App[T]) RunContext(ctx context.Context) error

RunContext executes the application lifecycle using the provided context.

Resolution and binding run first: dotenv loading (if configured via App.Dotenv), tokenization, configuration file resolution, then flag and argument coercion from the CLI, environment, and configuration sources. Constraints are then enforced in this order: struct tag constraints, the leaf command's Runner contract, and domain-type SelfValidator checks.

The lifecycle runs in five stages on the matched leaf command:

  1. Validate: Validator.Validate hooks run top-down. A failure returns an error immediately; no PreRun, Run, PostRun, or Finally hook executes, because no command has been initialized yet.
  2. PreRun: PreRunner.PreRun hooks run top-down to initialize resources.
  3. Run: Runner.Run executes on the leaf.
  4. PostRun: PostRunner.PostRun hooks run bottom-up, only after Run succeeds.
  5. Finally: Finalizer.Finally hooks run bottom-up unconditionally for every initialized command, receiving the halting error or nil.

An error from any stage between PreRun and PostRun skips the remaining stages and jumps straight to Finally. An error from a Finally hook is joined with the halting error and returned alongside it.

RunContext propagates the provided context to every lifecycle hook but does not itself poll for cancellation; a hook that observes cancellation can return ctx.Err(), which then flows through Finally cleanup like any other error. Standard streams are snapshotted when execution begins; subsequent builder mutations do not affect the running session.

The built-in subcommands (HelpCommand, VersionCommand, CompletionCommand) bypass the lifecycle, so ancestor hooks never execute for them.

Returns:

  • nil on successful execution or when handling built-in flags (--help, --version, --why).
  • An error wrapping ErrSchema if the struct tags or command schema are invalid.
  • An error wrapping ErrParse, ErrCoerce, or ErrValidation if user input is invalid.
  • An error wrapping ErrConfig if configuration or .env loading fails.
  • The error returned by Runner.Run or lifecycle hooks, or ctx.Err() on cancellation.

RunContext never terminates the process; it returns every failure to the caller. App.Exit maps a returned error to an exit code.

Panics:

  • If ctx is nil.
  • If the App has already been executed: an App instance runs exactly once.

func (*App[T]) SetenvFunc ¶ added in v0.2.0

func (a *App[T]) SetenvFunc(setenv func(key, value string)) *App[T]

SetenvFunc overrides the function App.Dotenv calls to set environment variables loaded from .env files. Defaults to os.Setenv. Passing a nil function is a no-op.

Pass testing.T.Setenv in tests so variables loaded from .env files are restored automatically when the test completes:

app := conga.New[CLI]().
	Dotenv(envPath).
	SetenvFunc(t.Setenv)

func (*App[T]) Stderr ¶

func (a *App[T]) Stderr(writer io.Writer) *App[T]

Stderr redirects the standard error stream writer for the application.

The stream defaults to os.Stderr. It is passed to commands via Session.Stderr and is used for diagnostics, deprecation notices, syntax usage summaries, and App.Exit.

The stream writer is snapshotted when App.Run or App.RunContext begins; mutations made after execution starts do not affect the active session. Passing a nil writer is a no-op.

func (*App[T]) Stdin ¶

func (a *App[T]) Stdin(reader io.Reader) *App[T]

Stdin redirects the standard input stream reader for the application.

The stream defaults to os.Stdin. It is passed to commands via Session.Stdin and feeds File containers declaring the stdin tag and FileContent containers reading from the - path.

The stream reader is snapshotted when App.Run or App.RunContext begins; mutations made after execution starts do not affect the active session. Passing a nil reader is a no-op.

func (*App[T]) Stdout ¶

func (a *App[T]) Stdout(writer io.Writer) *App[T]

Stdout redirects the standard output stream writer for the application.

The stream defaults to os.Stdout. It is passed to commands via Session.Stdout and is used by built-in help, version, and --why renderers, as well as File containers declaring the stdout tag and writing to the - path.

The stream writer is snapshotted when App.Run or App.RunContext begins; mutations made after execution starts do not affect the active session. Passing a nil writer is a no-op.

func (*App[T]) UsageOnError ¶

func (a *App[T]) UsageOnError(mode UsageOnErrorMode) *App[T]

UsageOnError configures how command syntax and help guidance are formatted on standard error when command-line input parsing or validation fails.

By default, CONGA uses UsageSummary. See UsageOnErrorMode for details on available presentation modes.

See https://docs.conga.sh/explanation/error-reporting/.

func (*App[T]) Use ¶

func (a *App[T]) Use(bindings ...func(*App[T])) *App[T]

Use mounts one or more builder bindings onto the app.

Bindings are functions with signature func(*App[T]). Each runs immediately in the given order, registering types and predictors through the App builder (RegisterLocation, for example, calls App.RegisterType with a completion predictor), and nil bindings are skipped:

app.Use(network.RegisterInterface, timezone.RegisterLocation)

See https://docs.conga.sh/reference/domain-types/.

Example ¶

Use mounts timezone.RegisterLocation, which registers a parser and completion predictor for *time.Location through App.RegisterType.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/conga-sh/conga"
	"github.com/conga-sh/conga/timezone"
)

// UseCLI is an application whose flag type is registered through a mounted binding.
type UseCLI struct {
	Zone conga.OptionalFlag[*time.Location] `help:"Server timezone"`
}

func (c *UseCLI) Run(_ context.Context, session *conga.Session) error {
	_, err := fmt.Fprintln(session.Stdout(), c.Zone.Get())

	return err
}

func main() {
	app := conga.New[UseCLI]().
		Use(timezone.RegisterLocation).
		Args([]string{"--zone", "America/New_York"})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}

}
Output:
America/New_York

func (*App[T]) Version ¶

func (a *App[T]) Version(version string) *App[T]

Version sets the application version string.

The version renders when the user passes the built-in --version flag, when running a mounted VersionCommand, or when calling Session.Version. The --version flag prefers the invoked binary's name over the configured application name.

When omitted, CONGA falls back to the Go module version recorded in the binary, or "dev" when the module version is unavailable. An embedded VCS commit hash and timestamp are appended to the rendered summary when present.

The summary line takes the form

<app> has version <version> built with <goversion>

For example:

Version("2.1.0")  --version  =>  myapp has version 2.1.0 built with go1.24.0

type ByteSize ¶

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

ByteSize represents human-readable data volumes.

Accepted formats ¶

Input is strict and case-sensitive. Exact byte counts, SI metric units ending in B, and IEC binary units are accepted:

1024                 exact bytes
500B                 exact bytes
kB MB GB TB PB       powers of 1000
KiB MiB GiB TiB PiB  powers of 1024

The numeric prefix is digits with an optional fraction whose contribution resolves exactly to bytes (1.5GB, 0.5GiB); a sub-byte remainder such as 0.1GiB is rejected. Naked unit suffixes without B (10G, 512Mi) and lowercase casings (mb, kib) are rejected to prevent ambiguity. KB is rejected as ambiguous: it denotes 1000 bytes in SI usage and 1024 bytes in legacy usage. kB is always 1000 bytes; KiB is always 1024. Text input is non-negative.

Rendering ¶

A value renders in its display family: a display field tag of binary or decimal forces that family, and input (the default) uses the family of the unit the value was decoded from. ByteSize.String is deterministic and lossless, and shows the full input-to-output mapping.

Comparison ¶

The byte count is available through ByteSize.Bytes. ByteSize values are deliberately non-comparable and cannot be used as map keys: the captured render family is not part of a size's identity. Express equality and ordering through ByteSize.Equal, ByteSize.Compare, or ByteSize.Bytes.

Field tags ¶

Fields may declare the units tag to restrict the accepted unit families and the display tag to force the render family:

units:"binary"    accept only IEC binary units (KiB..PiB)
units:"decimal"   accept only SI metric units (kB..PB)
units:"both"      accept every unit family (default)
display:"binary"  render in binary units
display:"decimal" render in decimal units
display:"input"   render in the unit family the input used (default)

Exact byte counts (a bare count or the B suffix) are family-neutral and accepted under either units value. A parsed unit outside the allowed family is a coercion error, and an unrecognized tag value is a schema error. The tags reach the type through field binding, tailor the default help text, and select the grammar used to parse range bounds (a decimal bound on a units:"binary" field is a schema error).

type Cache struct {
	Memory conga.ByteSize `units:"binary" display:"input"`
}

See https://docs.conga.sh/reference/domain-types/.

Example ¶

ByteSize parses human-readable byte sizes and provides the raw byte count.

package main

import (
	"context"
	"fmt"

	"github.com/conga-sh/conga"
)

// ByteSizeCLI is an application whose flag accepts human-readable data volumes.
type ByteSizeCLI struct {
	Limit conga.OptionalFlag[conga.ByteSize] `default:"512MiB" help:"Memory limit"`
}

func (c *ByteSizeCLI) Run(_ context.Context, session *conga.Session) error {
	_, err := fmt.Fprintf(session.Stdout(), "limit=%s bytes=%d\n", c.Limit.Get(), c.Limit.Get().Bytes())

	return err
}

func main() {
	app := conga.New[ByteSizeCLI]().
		Args([]string{"--limit", "1.5GB"})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}

}
Output:
limit=1500MB bytes=1500000000

func (ByteSize) Bytes ¶

func (b ByteSize) Bytes() int64

Bytes returns the size in bytes.

func (ByteSize) Compare ¶

func (b ByteSize) Compare(other ByteSize) int

Compare compares b and other by byte count and returns -1, 0, or +1.

func (ByteSize) Equal ¶

func (b ByteSize) Equal(other ByteSize) bool

Equal reports whether b and other represent the same number of bytes, independent of the unit family used to render them.

func (ByteSize) Help ¶

func (b ByteSize) Help(tags FieldTags) string

Help returns the default value syntax description for byte size flags, tailored to the declared units and display tags.

The engine renders this text in the flag's help column when the field declares no help tag; a field with a help tag shows that text instead. Shells also show it as the description of the flag's completion candidates.

Field            Rendered text
conga.ByteSize   Byte size (e.g., 10MiB, 1.5GB, 500KiB)
units:"binary"   Byte size in binary units (e.g., 10KiB, 512MiB)
units:"decimal"  Byte size in decimal units (e.g., 10kB, 512MB)

The display tag appends a clause to the base text selected by units:

display:"binary"   Byte size ..., shown in binary units
display:"decimal"  Byte size ..., shown in decimal units
display:"input"    Byte size ..., shown in the entered unit family

The "..." stands for whichever base text units selected, so every units value pairs with every display value; for example units:"binary" with display:"input" renders "Byte size in binary units (e.g., 10KiB, 512MiB), shown in the entered unit family". An absent or unrecognized display value appends nothing.

func (ByteSize) MarshalText ¶

func (b ByteSize) MarshalText() ([]byte, error)

MarshalText returns the byte size formatted as UTF-8 text using ByteSize.String.

func (ByteSize) String ¶

func (b ByteSize) String() string

String formats the byte size into a deterministic, lossless human-readable string.

Rendering picks the largest unit of the value's family that divides the byte count exactly, formatting it as an integer without spaces or decimal points; a count no unit divides is emitted as exact bytes. The input-to-output mapping, including the display tag families:

input             display tag   output
1.5GB             input         1500MB
0.5GiB            input         512MiB
1024              input         1024B
1.000000001GB     input         1000000001B
1.5GB             binary        1500000000B
1024kB            binary        1000KiB
1000KiB           decimal       1024kB
1073741824        binary        1GiB
zero value        any           0B

Parsed exact-byte input (a B suffix or a bare count) always echoes as exact bytes, and String returns 0B for zero.

func (*ByteSize) TagSpecs ¶

func (b *ByteSize) TagSpecs() []TagSpec

TagSpecs registers the custom struct tags accepted by ByteSize fields: units and display.

func (*ByteSize) UnmarshalText ¶

func (b *ByteSize) UnmarshalText(text []byte) error

UnmarshalText parses a strict, case-sensitive byte size string without field tags, via ByteSize.UnmarshalTextWithContext with a zero DecodeContext. The input's unit suffix fixes the value's render family; the accepted formats are listed on ByteSize.

func (*ByteSize) UnmarshalTextWithContext ¶

func (b *ByteSize) UnmarshalTextWithContext(text []byte, decodeContext DecodeContext) error

UnmarshalTextWithContext parses a strict, case-sensitive byte size string using the field's declared tags: units restricts the accepted unit family (binary, decimal, or both) and display forces the render family (binary, decimal, or input).

The value captures the parsed unit's family so it renders back in the family the input used (Kubernetes-Quantity style). Bare counts and the B suffix capture the exact-bytes family and echo as exact bytes. Absent tags accept every unit and echo the input family.

type Command ¶

type Command[T any] struct {
	// contains filtered or unexported fields
}

Command represents a subcommand container holding struct type T.

In parent commands and lifecycle hooks, call Command.IsSelected to check whether execution was routed to this subcommand. Call Command.Get to access the inner command struct T.

type RootCLI struct {
	Serve conga.Command[ServeCLI] `summary:"Start HTTP server"`
	Migrate conga.Command[MigrateCLI] `summary:"Run database migrations"`
}

See https://docs.conga.sh/how-to/declare-subcommands/.

func (*Command[T]) Get ¶

func (c *Command[T]) Get() *T

Get returns a pointer to the inner command struct instance of type T.

func (*Command[T]) IsSelected ¶

func (c *Command[T]) IsSelected() bool

IsSelected reports whether the engine routed execution to this subcommand. Use this in parent lifecycle hooks (PreRunner, PostRunner, Finalizer) to determine which child branch is active.

type CompletionCommand ¶

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

CompletionCommand provides an opt-in completion subcommand.

Declare a CompletionCommand field directly on a command struct:

type CLI struct {
	Completion conga.CompletionCommand `summary:"Generate shell completion scripts"`
}

The field requires App.EnableCompletion; declaring it without that call fails schema build with an ErrSchema error naming the missing opt-in.

The completion subcommand is a meta-command: it bypasses the execution lifecycle, so ancestor PreRunner, PostRunner, and Finalizer hooks do not run for it.

See https://docs.conga.sh/reference/builtins/.

func (*CompletionCommand) Run ¶

func (c *CompletionCommand) Run(ctx context.Context, session *Session) error

Run generates and outputs the shell completion script for the requested shell to Session.Stdout.

Panics:

  • If ctx is nil.

func (*CompletionCommand) Shell ¶

func (c *CompletionCommand) Shell() string

Shell returns the target shell name.

type CompletionError ¶

type CompletionError interface {
	error

	// IsCompletionError reports whether the error represents an internal completion failure.
	IsCompletionError() bool
}

CompletionError is an interface implemented by errors that represent an internal failure during shell completion evaluation.

type ConfigContext ¶

type ConfigContext interface {
	// CommandPath returns the selected invocation path, for example
	// "cloudctl deploy worker".
	CommandPath() string
	// LookupEnv returns the environment visible to this invocation, like
	// os.LookupEnv. Normal executions and completion invocations both include
	// .env values because dotenv runs before resolution; completion tolerates
	// dotenv loading failures the same way it tolerates loader failures.
	LookupEnv(key string) (string, bool)
}

ConfigContext exposes the invocation facts CONGA knows when the configuration loader runs: the selected command path and the run's environment view. Bootstrap-tagged fields are bound on the root struct before the loader runs, so the loader reads their typed containers directly.

The engine supplies the implementation; application tests may implement the interface to exercise a loader in isolation.

type ConfigDecoder ¶

type ConfigDecoder = configengine.Decoder

ConfigDecoder parses raw configuration bytes into a generic key-value map.

Application code supplies decoders to App.RegisterDecoder, which associates one with a file extension. A decoder unmarshals the file into a nested map with string keys, for example:

func Decode(data []byte) (map[string]any, error) {
	var parsed map[string]any
	if err := json.Unmarshal(data, &parsed); err != nil {
		return nil, fmt.Errorf("decode json config: %w", err)
	}

	return parsed, nil
}

Decoders for JSON, YAML, TOML, and HCL ship with CONGA in the decoder/json, decoder/yaml, decoder/toml, and decoder/hcl packages.

type ConfigDocument ¶

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

ConfigDocument is a programmatically built configuration document: values in the same key space a configuration decoder produces, each remembering the origin it was set from. The zero value is ready to use.

Keys address top-level document entries — a flag name, a config key, a subcommand section, or a namespace section — and values accept the shapes a decoder returns:

document := &conga.ConfigDocument{}
document.Set("port", 8080, "embedded defaults")
document.SetKey("headers", "X-Region", "eu", "taskrc")
document.SetScoped("log-level", "debug", "pipeline.yaml", "pipeline deploy")
document.Set("deploy", map[string]any{"replicas": 3}, "taskrc")

Scalar values stringify the same way decoded-file values do, and list values comma-join before binding; supply a pre-joined string when the target flag declares a custom sep. Map flags accept a nested map[string]any or map[string]string section, a []string or []any of key=value tokens, or a flat token string. ConfigDocument.SetKey records a single map entry and merges it key by key with earlier writes.

The origin is a free-form label CONGA never parses; it surfaces in the --why report and attributes each merged map key to the source that last wrote it. ConfigDocument.SetScoped and ConfigDocument.SetKeyScoped add an optional scope within the origin; value attribution renders it as origin › scope while the Config paths table lists the origin path once.

Do not set nil values: like a null in a decoded file, a nil value stringifies rather than being dropped.

func (*ConfigDocument) Set ¶

func (d *ConfigDocument) Set(key string, value any, origin string) *ConfigDocument

Set records value under key with the given origin and returns the document for chaining. A later Set of the same key replaces the earlier entry, including every ConfigDocument.SetKey contribution recorded for it.

Panics:

  • If the receiver is nil; mutate the zero value instead.

func (*ConfigDocument) SetKey ¶

func (d *ConfigDocument) SetKey(key, entryKey string, value any, origin string) *ConfigDocument

SetKey records value under entryKey within the map entry named key with the given origin and returns the document for chaining. It is the per-key counterpart of ConfigDocument.Set: a later layer overlays a single map entry without re-supplying the whole map.

A SetKey entry merges key by key with a map recorded by Set: the later call wins for the entry keys it names, while keys set by an earlier call survive. A later Set of the same key replaces the whole entry and clears every SetKey contribution recorded for it. Each entry key keeps the origin it was last written with, so the --why report attributes map keys individually.

Panics:

  • If the receiver is nil; mutate the zero value instead.

func (*ConfigDocument) SetKeyScoped ¶

func (d *ConfigDocument) SetKeyScoped(key, entryKey string, value any, origin, scope string) *ConfigDocument

SetKeyScoped records value under entryKey within the map entry named key with the given origin and scope and returns the document for chaining. It behaves like ConfigDocument.SetKey; value attribution in the --why report renders the pair as origin › scope, while the Config paths table lists the origin once.

An empty scope is equivalent to ConfigDocument.SetKey. An empty origin records no provenance detail and ignores the scope.

Panics:

  • If the receiver is nil; mutate the zero value instead.

func (*ConfigDocument) SetScoped ¶

func (d *ConfigDocument) SetScoped(key string, value any, origin, scope string) *ConfigDocument

SetScoped records value under key with the given origin and scope and returns the document for chaining. It behaves like ConfigDocument.Set; the scope names a region within the origin, such as a section of a configuration file. Value attribution in the --why report renders the pair as origin › scope, while the Config paths table lists the origin once.

An empty scope is equivalent to ConfigDocument.Set. An empty origin records no provenance detail and ignores the scope.

Panics:

  • If the receiver is nil; mutate the zero value instead.

type ConfigFile ¶

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

ConfigFile represents a root-level flag for loading configuration files.

By default the flag holds a single file path (last provided value wins). Declaring the multi tag enables repeated --config-file flags and comma-separated paths to accumulate in ConfigFile.Paths for multi-file cascading merges:

type ServerCLI struct {
	Config conga.ConfigFile `multi:"true" short:"c"`
}

app -c base.toml -c prod.toml

The invocation above loads both files in order (later files override earlier ones on key conflicts) and reports both through ConfigFile.Paths.

Probed candidate paths that were absent on disk are reported by Session.CandidateConfigFiles.

See https://docs.conga.sh/how-to/manage-config-files/.

func (*ConfigFile) Changed ¶

func (c *ConfigFile) Changed() bool

Changed reports whether configuration file paths were supplied by any source: a CLI flag, an environment variable, or the probed search tier. It mirrors ConfigFile.IsSet; a ConfigFile field accepts no default tag, so there is no default-only state.

func (*ConfigFile) IsSet ¶

func (c *ConfigFile) IsSet() bool

IsSet reports whether any configuration file path resolved: from a CLI flag, an environment variable, or the probed search tier.

func (*ConfigFile) Path ¶

func (c *ConfigFile) Path() string

Path returns the effective configuration file path: the highest-precedence loaded file, or an empty string if no configuration file was loaded.

func (*ConfigFile) Paths ¶

func (c *ConfigFile) Paths() []string

Paths returns a copy of the configuration files actually loaded for this flag, ordered from lowest to highest precedence.

To inspect probed candidate paths that were absent on disk, call Session.CandidateConfigFiles.

func (*ConfigFile) Source ¶

func (c *ConfigFile) Source() ValueSource

Source reports the configuration tier from which the configuration file paths resolved. See ValueSource for the tiers and their precedence.

func (*ConfigFile) SourceDetail ¶

func (c *ConfigFile) SourceDetail() string

SourceDetail returns the concrete origin recorded with ConfigFile.Source.

app --config-file prod.toml

records SourceCLI with the detail "--config-file"; paths loaded from the search tier record SourceConfig with the comma-joined loaded paths.

func (*ConfigFile) String ¶

func (c *ConfigFile) String() string

String returns the comma-separated list of loaded configuration file paths. Returns an empty string if the receiver is nil.

type ConfigLoaderFunc ¶

type ConfigLoaderFunc[T any] func(ctx ConfigContext, root *T) (*ConfigDocument, error)

ConfigLoaderFunc supplies the run's configuration document. Returning a nil document with a nil error leaves the configuration tier inactive; a returned error fails the run and is classified under ErrConfig.

The function runs at most once per execution, after command-line tokenization and bootstrap-field binding, and before configuration resolution, full flag binding, and feature pruning. Fields declared with the bootstrap tag are already bound on root; every other field holds its zero or caller-seeded value. Loader applications that enable features may have it run for --help and --why rendering, and shell completion invocations run it as well, so it must be deterministic and may perform only bounded local I/O and updates to app-owned non-schema state.

type ConfigOption ¶

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

ConfigOption declares one slot of the application's configuration resolution settings for App.ConfigOptions. Options compose and are independent of call order; repeating an option replaces its slot. ConfigOption is a sealed interface: values are produced exclusively by the constructors ConfigPaths, ConfigExplicit, ConfigCascading, and ConfigLoader, and cannot be implemented by other packages.

func ConfigCascading ¶

func ConfigCascading() ConfigOption

ConfigCascading merges every existing configuration file found in the search tier (author-declared via ConfigPaths, otherwise the built-in conventional tier) instead of stopping at the first existing file. The first-listed tier path has the highest precedence on key conflicts; later files still supply keys the earlier ones omit. A declared root ConfigFile flag must accept multiple values (the multi tag); the schema rejects the combination otherwise.

func ConfigExplicit ¶

func ConfigExplicit(path string) ConfigOption

ConfigExplicit names one concrete configuration file with fatal-if-missing semantics for App.ConfigOptions: the file must exist and be readable. It outranks the configuration environment variable (<PREFIX>_CONFIG) and the search tier, and bypasses the built-in conventional tier.

Panics:

  • If path is empty or whitespace-only.

func ConfigLoader ¶

func ConfigLoader[T any](load ConfigLoaderFunc[T]) ConfigOption

ConfigLoader declares the application's programmatic configuration document source for App.ConfigOptions, replacing configuration file resolution (decoders, search tiers, and probing) for every run:

type ServerCLI struct {
	Profile conga.OptionalFlag[string] `bootstrap:"true"`
	Host    conga.OptionalFlag[string]
}

app.ConfigOptions(conga.ConfigLoader(func(ctx conga.ConfigContext, root *ServerCLI) (*conga.ConfigDocument, error) {
	document := &conga.ConfigDocument{}
	document.Set("host", "localhost", "embedded defaults")

	if root.Profile.IsSet() {
		document.Set("host", root.Profile.Get()+"-host", "flag --profile")
	}

	return document, nil
}))

The document is validated exactly like a decoded configuration file: unknown keys fail with ErrConfig and a did-you-mean hint, config:"-" exclusions are honored, and nested sections, subcommand namespaces, and map flags resolve the same way. Values keep the configuration tier rank (CLI > environment > document > default), and OptionalFlag.Source reports SourceConfig for document-supplied values. The application-supplied origins surface in the --why report.

A loader application must not register decoders (App.RegisterDecoder), declare file resolution options (ConfigPaths, ConfigExplicit, ConfigCascading), or declare a root ConfigFile field: schema build rejects the combination with an ErrSchema error.

Panics:

  • If load is nil.
Example ¶

Supply the configuration tier from code with ConfigLoader: the returned document is validated like a decoded config file, outranks defaults, and still loses to command-line and environment values.

package main

import (
	"context"
	"fmt"

	"github.com/conga-sh/conga"
)

// LoaderCLI is an application whose configuration document comes from code.
type LoaderCLI struct {
	Host conga.OptionalFlag[string] `default:"localhost"`
	Port conga.OptionalFlag[int]    `default:"8000"`
}

func (c *LoaderCLI) Run(_ context.Context, session *conga.Session) error {
	_, err := fmt.Fprintf(session.Stdout(), "port=%d host=%s\n", c.Port.Get(), c.Host.Get())

	return err
}

func main() {
	app := conga.New[LoaderCLI]().
		ConfigOptions(conga.ConfigLoader(func(_ conga.ConfigContext, _ *LoaderCLI) (*conga.ConfigDocument, error) {
			document := &conga.ConfigDocument{}
			document.Set("host", "document.example.com", "embedded defaults")
			document.Set("port", 9200, "embedded defaults")

			return document, nil
		})).
		Args([]string{"--host", "cli.example.com"})

	if err := app.Run(); err != nil {
		panic(err)
	}

}
Output:
port=9200 host=cli.example.com

func ConfigPaths ¶

func ConfigPaths(paths ...string) ConfigOption

ConfigPaths declares the author configuration search tier for App.ConfigOptions: the paths are probed in precedence order and the first existing configuration file wins unless ConfigCascading is also declared. Declaring paths replaces the built-in conventional configuration tier:

${XDG_CONFIG_HOME:-~/.config}/<app-name>

Panics:

  • If called with no paths.
  • If any path entry is empty or whitespace-only.

type ContextAwareTextUnmarshaler ¶

type ContextAwareTextUnmarshaler interface {
	// UnmarshalTextWithContext decodes raw text using ambient field tags and streams.
	UnmarshalTextWithContext(text []byte, decodeContext DecodeContext) error
}

ContextAwareTextUnmarshaler is implemented by custom domain types that require the owning field's declared custom tags and/or engine standard streams during decoding.

The coercion pipeline prefers ContextAwareTextUnmarshaler over encoding.TextUnmarshaler. The passed DecodeContext contains custom tags parsed and validated at schema build (see TagSpecProvider) and the standard streams configured via App.Stdin and App.Stdout.

Direct invocations with a zero DecodeContext behave identically to standard text unmarshaling.

type Counter ¶

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

Counter represents a repeatable boolean flag that counts its occurrences.

Each occurrence on the command line increments the count by 1. With no occurrences and no other source, Counter.Get returns 0.

Counters count command-line occurrences starting at 0, so a default tag is rejected at schema build. An environment or configuration file binding seeds a base level that command-line occurrences override; use OptionalFlag with an integer type for a counted value that needs a numeric default.

Example ¶

Counter counts repeated occurrences of a boolean flag on the command line.

package main

import (
	"context"
	"fmt"

	"github.com/conga-sh/conga"
)

// CounterCLI is an application with a verbosity counter flag.
type CounterCLI struct {
	Verbose conga.Counter `help:"Increase verbosity" short:"v"`
}

func (c *CounterCLI) Run(_ context.Context, session *conga.Session) error {
	_, err := fmt.Fprintf(session.Stdout(), "verbosity=%d\n", c.Verbose.Get())

	return err
}

func main() {
	app := conga.New[CounterCLI]().
		Args([]string{"-vvv"})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}

}
Output:
verbosity=3

func (*Counter) Changed ¶

func (c *Counter) Changed() bool

Changed reports whether the count was explicitly supplied by a CLI flag, environment variable, or configuration file. It mirrors Counter.IsSet; a Counter field accepts no default tag, so there is no default-only state.

func (*Counter) Get ¶

func (c *Counter) Get() int

Get returns the resolved count: command-line occurrences take precedence, then an environment or configuration file binding, then 0 when no source supplied one. See Counter.

func (*Counter) GetOr ¶

func (c *Counter) GetOr(fallback int) int

GetOr returns the occurrence count if Counter.IsSet is true, or fallback otherwise.

func (*Counter) IsSet ¶

func (c *Counter) IsSet() bool

IsSet reports whether the counter flag received a count from any source.

func (*Counter) Source ¶

func (c *Counter) Source() ValueSource

Source reports the configuration tier from which the count was resolved. See ValueSource for the tiers and their precedence.

func (*Counter) SourceDetail ¶

func (c *Counter) SourceDetail() string

SourceDetail returns the concrete origin recorded with Counter.Source: the flag token, the environment variable name, or the contributing configuration origin (a file path for file-loaded values, or the loader's label). It is empty when the counter is unset.

func (*Counter) String ¶

func (c *Counter) String() string

String returns the count formatted as a decimal string. Returns "0" if the receiver is nil.

type DashArgs ¶

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

DashArgs captures trailing arguments passed explicitly after the -- token.

All arguments following -- are captured verbatim without flag parsing.

A DashArgs field accepts only the name and conga tags.

Example ¶

DashArgs captures arguments passed after the '--' delimiter without flag parsing.

package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/conga-sh/conga"
)

// DashCLI is an application that captures trailing arguments after '--'.
type DashCLI struct {
	Target conga.RequiredArg[string] `help:"Target package" name:"target"`
	Flags  conga.DashArgs            `name:"flags"`
}

func (c *DashCLI) Run(_ context.Context, session *conga.Session) error {
	_, err := fmt.Fprintf(session.Stdout(), "%s: %s\n", c.Target.Get(), strings.Join(c.Flags.Get(), " "))

	return err
}

func main() {
	app := conga.New[DashCLI]().
		Args([]string{"testpkg", "--", "-v", "--run", "TestFoo"})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}

}
Output:
testpkg: -v --run TestFoo

func (*DashArgs) Get ¶

func (raw *DashArgs) Get() []string

Get returns a slice of the captured trailing arguments.

func (*DashArgs) GetOr ¶

func (raw *DashArgs) GetOr(fallback []string) []string

GetOr returns the captured arguments if set and non-empty, or fallback if empty.

func (*DashArgs) IsSet ¶

func (raw *DashArgs) IsSet() bool

IsSet reports whether trailing arguments were captured for the container.

func (*DashArgs) Len ¶

func (raw *DashArgs) Len() int

Len returns the number of captured arguments.

func (*DashArgs) String ¶

func (raw *DashArgs) String() string

String returns the captured dash arguments formatted as a space-separated string. Returns an empty string if the receiver is nil.

type DecodeContext ¶

type DecodeContext = coerce.DecodeContext

DecodeContext carries ambient metadata for coercing a raw string into a domain type: the owning field's declared custom tags and the engine-configured standard streams (App.Stdin / App.Stdout).

The zero value selects no tags and standard process streams (os.Stdin / os.Stdout). Unlike context.Context, DecodeContext carries no cancellation or deadlines.

type DescriptionProvider ¶

type DescriptionProvider interface {
	// Description returns the long-form overview for the subcommand's help screen.
	Description() string
}

DescriptionProvider is implemented by subcommand structs to supply a detailed, multi-line overview for their generated help screen.

type Dir ¶

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

Dir represents a filesystem directory path with an optional existence constraint declared via the existing struct tag.

Directory paths automatically expand tilde prefixes (~ to the user's home directory) and environment variables ($VAR or ${VAR}) during value decoding.

type OutputCLI struct {
	OutputDir conga.RequiredFlag[conga.Dir] `short:"o" existing:"true" help:"Output directory"`
}

func (o *OutputCLI) Run(ctx context.Context, session *conga.Session) error {
	dir := o.OutputDir.Get()
	return os.WriteFile(filepath.Join(dir.String(), "result.json"), []byte("{}\n"), 0o644)
}

See https://docs.conga.sh/reference/domain-types/.

func (Dir) Help ¶

func (d Dir) Help(tags FieldTags) string

Help returns the default value syntax description for directory flags, tailored to the declared existing tag.

The engine renders this text in the flag's help column when the field declares no help tag; a field with a help tag shows that text instead. Shells also show it as the description of the flag's completion candidates:

Field            Rendered text
conga.Dir        Path to a directory
existing:"true"  Path to an existing directory

func (Dir) MarshalText ¶

func (d Dir) MarshalText() ([]byte, error)

MarshalText returns the resolved directory path as UTF-8 bytes.

func (Dir) Predict ¶

func (d Dir) Predict() predict.Predictor

Predict returns filesystem directory autocompletion candidates.

func (Dir) String ¶

func (d Dir) String() string

String returns the resolved directory path string.

func (*Dir) TagSpecs ¶

func (d *Dir) TagSpecs() []TagSpec

TagSpecs registers the custom struct tags accepted by Dir fields (existing).

func (*Dir) UnmarshalText ¶

func (d *Dir) UnmarshalText(text []byte) error

UnmarshalText unmarshals a directory path via Dir.UnmarshalTextWithContext with a zero DecodeContext.

func (*Dir) UnmarshalTextWithContext ¶

func (d *Dir) UnmarshalTextWithContext(text []byte, decodeContext DecodeContext) error

UnmarshalTextWithContext decodes a directory path, expanding environment variables and tilde prefixes, and captures declared capability tags from DecodeContext.

func (*Dir) Validate ¶

func (d *Dir) Validate(ctx context.Context) error

Validate enforces the declared directory tags. With the existing tag, the path must exist and be a directory; without it, Validate always succeeds.

type ExampleProvider ¶

type ExampleProvider interface {
	// Examples returns usage examples formatted for the subcommand's help screen.
	Examples() string
}

ExampleProvider is implemented by subcommand structs to supply usage examples for their generated help screen.

type Features ¶

type Features[T any] struct {
	// contains filtered or unexported fields
}

Features declares the application's feature toggles through the fields of T.

Each exported field of T declares one feature: the field name, converted to kebab-case (or overridden with the name tag), is the feature name. A bool field is an on/off toggle; an integer field is a leveled toggle where 0 means off and any other value must be listed in the enum tag.

type Experiments struct {
	RemoteCache      bool `help:"Experimental distributed CAS artifact cache"`
	SandboxIsolation int  `enum:"1,2" help:"Experimental build sandbox isolation: 1=chroot, 2=rootless-container"`
}

type CLI struct {
	Features conga.Features[Experiments] `flag:"feature-gates" env:"APP_FEATURES" config:"experiments"`
}

app := conga.New[CLI]().EnableFeatures()

Declare the Features field on the root command struct only. Activating feature toggles requires calling App.EnableFeatures on the application builder; declaring a Features field or a feature tag without it fails schema build with ErrSchema.

Every feature is carried by a single key=value map surface: the map flag named by the flag tag (omitted when the tag is absent), the environment surface declared on the container, and the configuration section named by config. The env surface is one of two exclusive shapes: env names a combined map variable carrying name=value pairs, and envprefix derives one variable per feature (<PREFIX>_<UPPER_SNAKE(feature name)>), with each field's env tag overriding its derived variable and env:"-" excluding the field. A container without either tag binds no environment variable, and the app EnvPrefix never reaches features. A key may use any spelling of a declared feature name (kebab-case, snake_case, or camelCase); keys are canonicalized before the merge, so precedence follows the tier rather than the spelling. The field defaults form the base set; config, environment, and command line sources merge over it key by key in ascending precedence (config < env < CLI), each source overlaying only the keys it lists (Kubernetes-style sparse overrides), so a config file can enable one feature while the command line enables another. Read the resolved values through Features.Get:

if cli.Features.Get().GentleForce { ... }

The root help screen renders an automatic Features section listing every toggle: its help tag text, its stage tag maturity (alpha, beta, ga, or deprecated — optional, but all features must declare one when any does), and its default. Features staged ga or deprecated are omitted from the section.

Flags and subcommands gated by the feature tag are pruned from help, why, and completion when their feature is inactive, and invoking them is a usage error.

Gating enforcement is symmetric for explicit inputs: a gated flag supplied on the command line is a usage error even when only help was requested, and a configuration key naming a gated flag whose feature is inactive is rejected with ErrConfig. Environment variables are the exception: pruning removes the flag from the schema before environment binding, so a variable targeting an inactive gated flag is ignored rather than rejected, keeping ambient environment state from breaking runs it does not control.

See https://docs.conga.sh/how-to/feature-flags/.

Example ¶

Features declares feature toggles evaluated through field defaults, configuration, environment, and CLI flags. Enable with conga.App.EnableFeatures.

package main

import (
	"context"
	"fmt"

	"github.com/conga-sh/conga"
)

// BuildExperiments declares feature toggles for ExampleFeatures and ExampleApp_EnableFeatures.
type BuildExperiments struct {
	RemoteCache      bool `help:"Experimental distributed CAS artifact cache"`
	SandboxIsolation int  `enum:"1,2"                                         help:"Experimental build sandbox isolation: 1=chroot, 2=rootless-container"`
}

// BuildCLI is an application with feature toggles and gated flags.
type BuildCLI struct {
	Features       conga.Features[BuildExperiments] `flag:"feature-gates"`
	Target         conga.RequiredArg[string]        `help:"Build target"`
	CacheEndpoint  conga.OptionalFlag[string]       `feature:"remote-cache"      help:"CAS server gRPC endpoint"`
	ContainerImage conga.OptionalFlag[string]       `feature:"sandbox-isolation" help:"OCI build container image"`
}

func (c *BuildCLI) Run(_ context.Context, session *conga.Session) error {
	experiments := c.Features.Get()
	_, err := fmt.Fprintf(session.Stdout(),
		"remote-cache=%t sandbox=%d endpoint=%s image=%s target=%s\n",
		experiments.RemoteCache,
		experiments.SandboxIsolation,
		c.CacheEndpoint.Get(),
		c.ContainerImage.Get(),
		c.Target.Get(),
	)

	return err
}

func main() {
	app := conga.New[BuildCLI]().
		EnableFeatures().
		Args([]string{
			"--feature-gates", "remote-cache=true,sandbox-isolation=2",
			"--cache-endpoint", "cas.internal:9092",
			"--container-image", "alpine:latest",
			"main",
		})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}

}
Output:
remote-cache=true sandbox=2 endpoint=cas.internal:9092 image=alpine:latest target=main

func (*Features[T]) Changed ¶

func (f *Features[T]) Changed() bool

Changed reports whether a feature value came from the command line, the environment, or a configuration file rather than exclusively from defaults.

func (*Features[T]) Get ¶

func (f *Features[T]) Get() *T

Get returns a pointer to the inner feature struct with every resolved value bound.

func (*Features[T]) IsSet ¶

func (f *Features[T]) IsSet() bool

IsSet reports whether any feature source contributed a value.

func (*Features[T]) Source ¶

func (f *Features[T]) Source() ValueSource

Source reports the highest configuration tier that contributed a key to the feature map.

func (*Features[T]) SourceDetail ¶

func (f *Features[T]) SourceDetail() string

SourceDetail returns the concrete origin recorded with Features.Source.

func (*Features[T]) String ¶

func (f *Features[T]) String() string

String returns the string representation of the features struct. Returns an empty string if the receiver is nil.

type FieldTags ¶

type FieldTags = spec.FieldTags

FieldTags holds the custom tag values declared on the field owning a resolved value. Only tags registered by the field's domain type through TagSpecProvider appear; boolean values are canonicalized to "true" and "false", and string values are stored verbatim.

The map is read with Has (was the tag declared at all), Bool (was it declared "true"), and String (its raw value, or "" when absent).

type File ¶

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

File represents a filesystem path with optional capability constraints declared through struct tags on command fields:

  • existing: requires the path to exist and not be a directory.
  • stdin: permits - to bind to standard input (App.Stdin or os.Stdin).
  • stdout: permits - to bind to standard output (App.Stdout or os.Stdout).
  • executable: requires the path to exist, not be a directory, have execute permission, and resolves PATH-relative names to their absolute location at decode time.
  • symlink: requires the path to be a symbolic link.
  • glob: shell autocompletion filter using comma-separated glob patterns (for example *.yaml,*.yml or Dockerfile*).

The tags are partly mutually exclusive because they constrain the same path in incompatible ways. Declaring a conflicting pair fails schema compilation:

existing   conflicts with stdout, executable, symlink
stdin      conflicts with stdout, executable, symlink
stdout     conflicts with stdin, existing, executable, symlink
executable conflicts with existing, stdin, stdout, symlink, glob
symlink    conflicts with existing, stdin, stdout, glob, executable
glob       conflicts with executable, symlink

File paths automatically expand tilde prefixes (~ to the user's home directory) and environment variables ($VAR or ${VAR}) during value decoding.

In command handlers, call File.Reader to open the file (or stdin if -) or File.Writer to create/truncate the file (or stdout if -):

type TransformCLI struct {
	Input  conga.RequiredFlag[conga.File] `short:"i" stdin:"true" help:"Input file or - for stdin"`
	Output conga.RequiredFlag[conga.File] `short:"o" stdout:"true" help:"Output file or - for stdout"`
}

func (t *TransformCLI) Run(ctx context.Context, session *conga.Session) error {
	reader, err := t.Input.Get().Reader()
	if err != nil {
		return err
	}
	defer reader.Close()
	// Process reader...
	return nil
}

See https://docs.conga.sh/reference/domain-types/.

func (File) Help ¶

func (f File) Help(tags FieldTags) string

Help returns the default value syntax description for file flags, tailored to declared capability tags.

The engine renders this text in the flag's help column when the field declares no help tag; a field with a help tag shows that text instead. Shells also show it as the description of the flag's completion candidates.

Field                  Rendered text
conga.File             Path to a file
existing:"true"        Path to an existing file
existing:"true" with   Path to an existing file or '-' for stdin
stdin:"true"
Path to a file or '-' for stdin
stdout:"true"          Path to a file or '-' for stdout
glob:"*.log"           Path to a file matching '*.log'
existing:"true" with   Path to an existing file matching '*.log'
glob:"*.log"
executable:"true"      Path to an executable
symlink:"true"         Path to a symbolic link

The clauses compose in a fixed order:

glob       appends " matching '<patterns>'" to the file or existing base text,
           with the patterns comma-joined into one quoted list; it combines
           with existing and the stdin/stdout suffix.
executable returns its fixed text unconditionally, never combining with glob,
           existing, or the stdin/stdout suffix.
symlink    returns its fixed text unconditionally, never combining with glob,
           existing, or the stdin/stdout suffix.

The stdin/stdout suffix (" or '-' for stdin" / " or '-' for stdout") is appended last, after any glob clause (see File for the tag grammar).

func (File) IsStdio ¶

func (f File) IsStdio() bool

IsStdio reports whether the file path is "-" (representing standard input or standard output).

func (File) MarshalText ¶

func (f File) MarshalText() ([]byte, error)

MarshalText returns the resolved filesystem path as UTF-8 bytes.

func (File) Predict ¶

func (f File) Predict(tags FieldTags) predict.Predictor

Predict returns shell autocompletion candidates tailored to the field's declared tags.

Generates executable candidates from $PATH for executable-tagged fields, symlinks for symlink-tagged fields, glob-filtered filenames for glob-tagged fields, and standard filesystem files otherwise.

func (File) Reader ¶

func (f File) Reader() (io.ReadCloser, error)

Reader opens the file for reading.

If the path is "-", Reader returns a non-closing wrapper around App.Stdin (or os.Stdin if unconfigured). Callers can safely call Close() on the returned io.ReadCloser without closing the underlying process standard input stream.

func (File) Stat ¶

func (f File) Stat() (os.FileInfo, error)

Stat returns os.FileInfo for the resolved file path.

func (File) String ¶

func (f File) String() string

String returns the resolved filesystem path string.

func (*File) TagSpecs ¶

func (f *File) TagSpecs() []TagSpec

TagSpecs registers the custom struct tags accepted by File fields.

func (*File) UnmarshalText ¶

func (f *File) UnmarshalText(text []byte) error

UnmarshalText unmarshals a raw path string via File.UnmarshalTextWithContext with a zero DecodeContext.

func (*File) UnmarshalTextWithContext ¶

func (f *File) UnmarshalTextWithContext(text []byte, decodeContext DecodeContext) error

UnmarshalTextWithContext decodes a path string using ambient field tags and configured standard streams (App.Stdin / App.Stdout).

Expands environment variables and tilde prefixes, captures declared capability tags for File.Validate, and resolves PATH-relative names to absolute paths when the executable tag is declared.

func (*File) Validate ¶

func (f *File) Validate(ctx context.Context) error

Validate verifies that the resolved path satisfies the capability tags declared on the owning field. The glob tag is a completion filter and is not validated.

Enforced rules:

  • If the value is -, the field must declare either the stdin or the stdout tag.
  • If the existing tag is declared, the path must exist and cannot be a directory.
  • If the executable tag is declared, the file must exist, cannot be a directory, and must have execute permissions.
  • If the symlink tag is declared, the path must be a symbolic link.

func (File) Writer ¶

func (f File) Writer() (io.WriteCloser, error)

Writer creates or truncates the file for writing.

If the path is "-", Writer returns a non-closing wrapper around App.Stdout (or os.Stdout if unconfigured). Callers can safely call Close() on the returned io.WriteCloser without closing the underlying process standard output stream.

type FileContent ¶

type FileContent string

FileContent represents the in-memory contents of a file read during argument decoding.

If the value is "-", the content is read into memory from App.Stdin (or os.Stdin). FileContent enforces a strict 16MB file size limit to prevent out-of-memory DoS vulnerabilities:

type ConfigCLI struct {
	Cert conga.RequiredFlag[conga.FileContent] `short:"c" help:"TLS certificate file or - for stdin"`
}

func (c *ConfigCLI) Run(ctx context.Context, session *conga.Session) error {
	certBytes := c.Cert.Get().Bytes()
	return loadCertificate(certBytes)
}

See https://docs.conga.sh/reference/domain-types/.

func (FileContent) Bytes ¶

func (f FileContent) Bytes() []byte

Bytes returns the raw bytes of the loaded file content.

func (FileContent) Help ¶

func (f FileContent) Help() string

Help returns the default value syntax description for file content flags.

The engine renders this text in the flag's help column when the field declares no help tag; a field with a help tag shows that text instead. Shells also show it as the description of the flag's completion candidates. The rendered text is always "Path to a file (or '-' for stdin)".

func (FileContent) MarshalText ¶

func (f FileContent) MarshalText() ([]byte, error)

MarshalText returns the loaded file content as UTF-8 bytes.

func (FileContent) Predict ¶

func (f FileContent) Predict() predict.Predictor

Predict returns filesystem file autocompletion candidates.

func (FileContent) String ¶

func (f FileContent) String() string

String returns the loaded file content.

func (*FileContent) UnmarshalText ¶

func (f *FileContent) UnmarshalText(text []byte) error

UnmarshalText loads the file at path into memory via FileContent.UnmarshalTextWithContext with a zero DecodeContext.

func (*FileContent) UnmarshalTextWithContext ¶

func (f *FileContent) UnmarshalTextWithContext(text []byte, decodeContext DecodeContext) error

UnmarshalTextWithContext loads the file at path into memory, enforcing a strict 16MB file size limit. When path is "-", content is read from the engine-configured standard input (App.Stdin), falling back to os.Stdin for unconfigured values.

type Finalizer ¶

type Finalizer interface {
	// Finally releases resources, receiving the halting error or nil.
	Finally(ctx context.Context, session *Session, err error) error
}

Finalizer is implemented by commands that require guaranteed resource cleanup.

Hooks execute bottom-up from leaf to root for all initialized commands, running unconditionally even when PreRun, Run, or PostRun return an error. The err parameter receives the error that halted execution, or nil if all prior stages succeeded.

See https://docs.conga.sh/explanation/lifecycle/.

type HelpCommand ¶

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

HelpCommand provides an opt-in help subcommand.

Declare a HelpCommand field directly on a command struct:

type CLI struct {
	Help conga.HelpCommand `summary:"Show help for any command"`
}

The help subcommand is a meta-command: it bypasses the execution lifecycle, so ancestor PreRunner, PostRunner, and Finalizer hooks do not run for it.

See https://docs.conga.sh/reference/builtins/.

func (*HelpCommand) Path ¶

func (h *HelpCommand) Path() []string

Path returns the subcommand path whose help was requested, or empty when rendering the help screen of the parent command.

func (*HelpCommand) Run ¶

func (h *HelpCommand) Run(ctx context.Context, session *Session) error

Run resolves the requested subcommand path and renders its help screen to Session.Stdout.

Panics:

  • If ctx is nil.

type HelpProvider ¶

type HelpProvider interface {
	// Help returns the value syntax description displayed in help screens.
	//
	// The engine consults the provider when the owning field declares no help
	// tag; a field with a help tag shows that text instead. Shells show the
	// provider's text as the description of the field's completion candidates.
	Help() string
}

HelpProvider is implemented by custom domain types that provide a default help description of their accepted value format on generated help screens.

For types whose help description varies depending on the owning field's custom struct tags (such as File with the existing tag), implement TagAwareHelpProvider instead. Implement exactly one of HelpProvider or TagAwareHelpProvider, not both.

type OptionalArg ¶

type OptionalArg[T any] struct {
	// contains filtered or unexported fields
}

OptionalArg represents an optional positional command-line argument of type T.

Positional arguments resolve strictly from command-line arguments (not environment variables or configuration files) and are evaluated in declaration order after all required positional arguments.

If omitted on the command line, OptionalArg.IsSet reports false and OptionalArg.Get returns the zero value of T.

func (*OptionalArg[T]) Changed ¶

func (a *OptionalArg[T]) Changed() bool

Changed reports whether the argument was explicitly provided on the command line, returning false if populated from a default tag or omitted.

func (*OptionalArg[T]) Get ¶

func (a *OptionalArg[T]) Get() T

Get returns the resolved positional argument value.

If omitted without a default tag, Get returns the zero value of T. Use OptionalArg.GetOr to provide a fallback value.

func (*OptionalArg[T]) GetOr ¶

func (a *OptionalArg[T]) GetOr(fallback T) T

GetOr returns the resolved argument value if OptionalArg.IsSet is true, or fallback otherwise.

func (*OptionalArg[T]) IsSet ¶

func (a *OptionalArg[T]) IsSet() bool

IsSet reports whether a positional argument was supplied on the command line or populated from a struct default tag.

func (*OptionalArg[T]) Source ¶

func (a *OptionalArg[T]) Source() ValueSource

Source reports whether the argument came from SourceCLI, SourceDefault, or SourceNone.

func (*OptionalArg[T]) SourceDetail ¶

func (a *OptionalArg[T]) SourceDetail() string

SourceDetail returns the default tag literal when the value came from a default tag, and an empty string when it came from the command line or is unset.

func (*OptionalArg[T]) String ¶

func (a *OptionalArg[T]) String() string

String returns the string representation of the argument value. Returns an empty string if the receiver is nil.

type OptionalFlag ¶

type OptionalFlag[T any] struct {
	// contains filtered or unexported fields
}

OptionalFlag represents an optional command-line flag of type T.

The value resolves from the command line, the environment, a configuration file, or a default struct tag, in that order of precedence. An omitted flag with no default holds the zero value of T.

Example ¶

A command-line value overrides the default and reports its source.

package main

import (
	"context"
	"fmt"

	"github.com/conga-sh/conga"
)

// FlagStateCLI is an application whose optional flag declares a default.
type FlagStateCLI struct {
	Port conga.OptionalFlag[int] `default:"8080" help:"Listen port"`
}

func (c *FlagStateCLI) Run(_ context.Context, session *conga.Session) error {
	_, err := fmt.Fprintf(session.Stdout(), "value=%d set=%t changed=%t source=%s\n",
		c.Port.Get(), c.Port.IsSet(), c.Port.Changed(), c.Port.Source())

	return err
}

func main() {
	app := conga.New[FlagStateCLI]().
		Args([]string{"--port", "9000"})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}
}
Output:
value=9000 set=true changed=true source=cli
Example (Default) ¶

An omitted flag falls back to its default tag: set, but not changed.

package main

import (
	"context"
	"fmt"

	"github.com/conga-sh/conga"
)

// FlagStateCLI is an application whose optional flag declares a default.
type FlagStateCLI struct {
	Port conga.OptionalFlag[int] `default:"8080" help:"Listen port"`
}

func (c *FlagStateCLI) Run(_ context.Context, session *conga.Session) error {
	_, err := fmt.Fprintf(session.Stdout(), "value=%d set=%t changed=%t source=%s\n",
		c.Port.Get(), c.Port.IsSet(), c.Port.Changed(), c.Port.Source())

	return err
}

func main() {
	app := conga.New[FlagStateCLI]().
		Args([]string{})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}
}
Output:
value=8080 set=true changed=false source=default
Example (MapMerge) ¶

Map flags merge key by key across tiers: the command-line flag overrides retries and adds timeout, while unmentioned keys like env keep their default.

package main

import (
	"context"
	"fmt"

	"github.com/conga-sh/conga"
)

// MapMergeCLI is an application whose map flag merges defaults with CLI inputs.
type MapMergeCLI struct {
	Settings conga.OptionalFlag[map[string]string] `default:"env=prod,retries=3" help:"Runtime settings"`
}

func (c *MapMergeCLI) Run(_ context.Context, session *conga.Session) error {
	settings := c.Settings.Get()
	_, err := fmt.Fprintf(session.Stdout(), "env=%s retries=%s timeout=%s\n",
		settings["env"], settings["retries"], settings["timeout"])

	return err
}

func main() {
	app := conga.New[MapMergeCLI]().
		Args([]string{"--settings", "retries=5,timeout=10s"})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}

}
Output:
env=prod retries=5 timeout=10s

func (*OptionalFlag[T]) Changed ¶

func (f *OptionalFlag[T]) Changed() bool

Changed reports whether the flag value was explicitly supplied by the caller through a CLI flag, an environment variable, or a configuration file.

Returns false if the value was populated exclusively from a struct default tag or if the flag was omitted.

func (*OptionalFlag[T]) Get ¶

func (f *OptionalFlag[T]) Get() T

Get returns the resolved flag value.

If the flag was omitted and declared no struct default tag, Get returns the zero value of T. Use OptionalFlag.GetOr to provide an explicit fallback.

func (*OptionalFlag[T]) GetOr ¶

func (f *OptionalFlag[T]) GetOr(fallback T) T

GetOr returns the resolved flag value if OptionalFlag.IsSet is true, or fallback otherwise.

func (*OptionalFlag[T]) IsSet ¶

func (f *OptionalFlag[T]) IsSet() bool

IsSet reports whether the flag received a value from any source, including explicit CLI arguments, environment variables, configuration files, or a struct default tag.

func (*OptionalFlag[T]) Source ¶

func (f *OptionalFlag[T]) Source() ValueSource

Source reports the configuration tier from which the flag value was resolved. See ValueSource for the tiers and their precedence.

func (*OptionalFlag[T]) SourceDetail ¶

func (f *OptionalFlag[T]) SourceDetail() string

SourceDetail returns the concrete origin recorded with OptionalFlag.Source: the flag token, the environment variable name, the contributing configuration origin (a file path for file-loaded values, or the loader's label), or the default tag literal. For a merged map flag the origin lists every contributing configuration file in load order, separated by commas. It is empty when the flag is unset.

func (*OptionalFlag[T]) String ¶

func (f *OptionalFlag[T]) String() string

String returns the string representation of the resolved value. Returns an empty string if the receiver is nil.

type PostRunner ¶

type PostRunner interface {
	// PostRun executes post-command logic after Run succeeds.
	PostRun(ctx context.Context, session *Session) error
}

PostRunner is implemented by commands that perform follow-up work after successful execution.

Hooks execute bottom-up from leaf to root, but only if Runner.Run succeeded without error. If a PostRun hook returns an error, subsequent PostRun hooks are skipped, jumping directly to Finalizer.Finally cleanup hooks.

See https://docs.conga.sh/explanation/lifecycle/.

type PreRunner ¶

type PreRunner interface {
	// PreRun initializes command resources prior to execution.
	PreRun(ctx context.Context, session *Session) error
}

PreRunner is implemented by commands that initialize shared resources before Runner.Run.

Hooks execute top-down from root to leaf. If PreRun returns an error, execution stops immediately: subsequent PreRun hooks, Run, and PostRun hooks are skipped, jumping directly to Finalizer.Finally cleanup hooks.

See https://docs.conga.sh/explanation/lifecycle/.

type Predictable ¶

type Predictable interface {
	// Predict returns an autocompletion predictor for the domain type.
	Predict() predict.Predictor
}

Predictable is implemented by custom domain types that provide shell autocompletion candidates.

Types whose completion candidates depend on custom field tags (such as File with the glob tag) implement TagAwarePredictable instead.

The engine evaluates Predict during schema compilation; implementations must not depend on runtime parsed values. Implement exactly one of Predictable or TagAwarePredictable, not both.

Example ¶

A flag type supplies its own completion candidates by implementing Predictable; declaring a flag of that type is all the wiring required.

package main

import (
	"context"

	"github.com/conga-sh/conga"
	"github.com/conga-sh/conga/predict"
)

// Cluster is a flag type that completes itself through Predictable.
type Cluster string

func (c Cluster) Predict() predict.Predictor {
	return predict.Values("alpha", "beta", "gamma")
}

// PredictableCLI is an application whose flag completes from its own type.
type PredictableCLI struct {
	Cluster conga.OptionalFlag[Cluster] `help:"Target cluster"`
}

func (c *PredictableCLI) Run(_ context.Context, _ *conga.Session) error {
	return nil
}

func main() {
	app := conga.New[PredictableCLI]().
		EnableCompletion().
		Args([]string{"__complete", "fish", "--cluster", ""})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}

}
Output:
alpha
beta
gamma

type RawArgs ¶

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

RawArgs captures all trailing unparsed command-line arguments without requiring --.

Parsing stops at the first unrecognized flag or argument, forwarding all remaining tokens into the container. This container supports proxy commands and CLI wrappers.

A RawArgs field accepts only the name and conga tags.

Example ¶

RawArgs forwards trailing unparsed command-line arguments to proxy commands.

package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/conga-sh/conga"
)

// RawCLI is an application that forwards trailing unparsed arguments.
type RawCLI struct {
	Command conga.RawArgs `name:"command"`
}

func (c *RawCLI) Run(_ context.Context, session *conga.Session) error {
	_, err := fmt.Fprintf(session.Stdout(), "exec: %s\n", strings.Join(c.Command.Get(), " "))

	return err
}

func main() {
	app := conga.New[RawCLI]().
		Args([]string{"sh", "-c", "echo hello"})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}

}
Output:
exec: sh -c echo hello

func (*RawArgs) Get ¶

func (raw *RawArgs) Get() []string

Get returns a slice of the captured trailing arguments.

func (*RawArgs) GetOr ¶

func (raw *RawArgs) GetOr(fallback []string) []string

GetOr returns the captured arguments if set and non-empty, or fallback if empty.

func (*RawArgs) IsSet ¶

func (raw *RawArgs) IsSet() bool

IsSet reports whether trailing arguments were captured for the container.

func (*RawArgs) Len ¶

func (raw *RawArgs) Len() int

Len returns the number of captured arguments.

func (*RawArgs) String ¶

func (raw *RawArgs) String() string

String returns the captured raw arguments formatted as a space-separated string. Returns an empty string if the receiver is nil.

type RegisterTypeOption ¶

type RegisterTypeOption func(*typeRegistration)

RegisterTypeOption configures a custom type registration on App.RegisterType and App.RegisterMap. WithPredictor is currently the only constructor.

func WithPredictor ¶

func WithPredictor(p predict.Predictor) RegisterTypeOption

WithPredictor attaches a shell autocompletion predictor to a registered custom type.

Flags and positional arguments using this type automatically inherit the predictor for shell autocompletion, unless overridden by an explicit predictor struct tag.

type RequiredArg ¶

type RequiredArg[T any] struct {
	// contains filtered or unexported fields
}

RequiredArg represents a mandatory positional command-line argument of type T.

Required positional arguments must be supplied on the command line in struct declaration order. If omitted and no struct default tag is present, Run returns a usage error before any lifecycle stage, starting with Validator.Validate, executes; IsUsageError reports true and App.Exit exits with status 2.

func (*RequiredArg[T]) Changed ¶

func (a *RequiredArg[T]) Changed() bool

Changed reports whether the argument was explicitly supplied on the command line rather than populated from a struct default tag.

func (*RequiredArg[T]) Get ¶

func (a *RequiredArg[T]) Get() T

Get returns the resolved positional argument value.

func (*RequiredArg[T]) IsSet ¶

func (a *RequiredArg[T]) IsSet() bool

IsSet reports whether the required argument received a value.

func (*RequiredArg[T]) Source ¶

func (a *RequiredArg[T]) Source() ValueSource

Source reports whether the argument came from SourceCLI or SourceDefault.

func (*RequiredArg[T]) SourceDetail ¶

func (a *RequiredArg[T]) SourceDetail() string

SourceDetail returns the default tag literal when the value came from a default tag, and an empty string when it came from the command line.

func (*RequiredArg[T]) String ¶

func (a *RequiredArg[T]) String() string

String returns the string representation of the argument value. Returns an empty string if the receiver is nil.

type RequiredFlag ¶

type RequiredFlag[T any] struct {
	// contains filtered or unexported fields
}

RequiredFlag represents a mandatory command-line flag of type T.

The requirement is satisfied if a value is supplied by a command-line flag, an environment variable, a configuration file, or a struct default tag. If no source provides a value, Run returns a usage error before any lifecycle stage, starting with Validator.Validate, executes; IsUsageError reports true and App.Exit exits with status 2.

When satisfied by explicit input, RequiredFlag.Changed reports true. When satisfied by a struct default tag, RequiredFlag.IsSet reports true while RequiredFlag.Changed stays false.

func (*RequiredFlag[T]) Changed ¶

func (f *RequiredFlag[T]) Changed() bool

Changed reports whether the flag was explicitly provided by the caller via CLI, environment variable, or configuration file, returning false if satisfied exclusively by a struct default tag.

func (*RequiredFlag[T]) Get ¶

func (f *RequiredFlag[T]) Get() T

Get returns the resolved flag value.

func (*RequiredFlag[T]) IsSet ¶

func (f *RequiredFlag[T]) IsSet() bool

IsSet reports whether the required flag received a value from any source.

func (*RequiredFlag[T]) Source ¶

func (f *RequiredFlag[T]) Source() ValueSource

Source reports the configuration tier from which the flag value was resolved. See ValueSource for the tiers and their precedence.

func (*RequiredFlag[T]) SourceDetail ¶

func (f *RequiredFlag[T]) SourceDetail() string

SourceDetail returns the concrete origin recorded with RequiredFlag.Source: the flag token, the environment variable name, the contributing configuration origin (a file path for file-loaded values, or the loader's label), or the default tag literal. For a merged map flag the origin lists every contributing configuration file in load order, separated by commas. It is empty when the flag is unset.

func (*RequiredFlag[T]) String ¶

func (f *RequiredFlag[T]) String() string

String returns the string representation of the resolved value. Returns an empty string if the receiver is nil.

type Runner ¶

type Runner interface {
	// Run executes command logic for the active session.
	Run(ctx context.Context, session *Session) error
}

Runner is implemented by command structs that execute primary application logic.

The engine invokes Run only on the matched leaf command after argument parsing, top-down Validator.Validate, and top-down PreRunner.PreRun hooks succeed. If Run returns an error, post-run hooks are skipped and execution jumps directly to Finalizer.Finally cleanup hooks.

See https://docs.conga.sh/explanation/lifecycle/.

type SelfValidator ¶

type SelfValidator interface {
	// Validate enforces value-level constraints on the resolved domain object.
	Validate(ctx context.Context) error
}

SelfValidator is implemented by custom flag and argument types that validate their resolved value after all configuration sources have been merged.

The engine always passes a non-nil context derived from App.RunContext. Types that accept custom field tags or engine streams capture them at decode time via ContextAwareTextUnmarshaler and validate against that captured state here.

type Session ¶

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

Session provides execution context, command hierarchy inspection, configuration provenance, and configured I/O streams to commands and lifecycle hooks.

Every lifecycle stage (Runner.Run, Validator.Validate, PreRunner.PreRun, PostRunner.PostRun, and Finalizer.Finally) receives a pointer to the active Session.

func (*Session) CandidateConfigFiles ¶

func (s *Session) CandidateConfigFiles() []string

CandidateConfigFiles returns a copy of all candidate configuration file paths evaluated during configuration resolution, including search-tier paths that were absent on disk.

func (*Session) Help ¶

func (s *Session) Help() string

Help returns the formatted help screen for the active command, rendered with the same engine the built-in --help flag uses.

If the session is nil or uninitialized, Help returns an empty string.

func (*Session) LoadedConfigFiles ¶

func (s *Session) LoadedConfigFiles() []string

LoadedConfigFiles returns a copy of all configuration file paths that were successfully loaded and merged for this session, ordered from lowest to highest precedence.

func (*Session) Name ¶

func (s *Session) Name() string

Name returns the leaf command name being executed, or the application name if executing the root command.

func (*Session) Path ¶

func (s *Session) Path() string

Path returns the full space-separated invocation path string for the active command (e.g. "cloudctl cluster deploy").

func (*Session) Root ¶

func (s *Session) Root[T any]() *T

Root returns a pointer to the root application struct of type T: either the instance supplied to New, or the engine-allocated instance created during schema compilation.

In a subcommand's Runner.Run or lifecycle hook, use Root to inspect global flags and shared settings declared on the root command.

Returns nil if the session is nil or if no root command instance exists.

Panics:

  • If T does not match the actual root struct type.
Example ¶

A subcommand reads global flags declared on the root command through conga.Session.Root.

package main

import (
	"context"
	"fmt"

	"github.com/conga-sh/conga"
)

// RootCLI is an application with one subcommand that reads a root flag.
type RootCLI struct {
	Verbose conga.OptionalFlag[bool]  `help:"Verbose output"`
	Migrate conga.Command[MigrateCmd] `summary:"Run database migrations"`
}

// MigrateCmd runs the database migration subcommand.
type MigrateCmd struct{}

func (c *MigrateCmd) Run(_ context.Context, session *conga.Session) error {
	root := session.Root[RootCLI]()
	_, err := fmt.Fprintf(session.Stdout(), "%s verbose=%t\n", session.Path(), root.Verbose.Get())

	return err
}

func main() {
	app := conga.New[RootCLI]().
		Name("tool").
		Args([]string{"--verbose", "migrate"})

	if err := app.Run(); err != nil {
		app.Exit(err)
	}
}
Output:
tool migrate verbose=true

func (*Session) Stderr ¶

func (s *Session) Stderr() io.Writer

Stderr returns the configured standard error writer for this session.

If the session or writer is nil, Stderr returns io.Discard.

func (*Session) Stdin ¶

func (s *Session) Stdin() io.Reader

Stdin returns the configured standard input reader for this session.

If the session or reader is nil, Stdin returns an immediate-EOF reader (the input-side analogue of io.Discard), ensuring commands reading from stdin do not block or panic when unconfigured.

The stream reader is snapshotted when execution begins; changes made to App afterwards do not affect the running session.

func (*Session) Stdout ¶

func (s *Session) Stdout() io.Writer

Stdout returns the configured standard output writer for this session.

The writer is captured when execution begins, so unit tests and embedded execution observe the application's output. If the session or writer is nil, Stdout returns io.Discard.

func (*Session) Usage ¶

func (s *Session) Usage() string

Usage returns the syntax usage summary for the active command.

If the session is nil or uninitialized, Usage returns an empty string.

func (*Session) Version ¶

func (s *Session) Version() string

Version returns the formatted application version summary line.

When no explicit version string was configured via App.Version, the summary falls back to the Go module version recorded in the binary, or "dev" when that is unavailable. An embedded VCS commit hash and date are appended when present.

If the session is nil, Version returns an empty string.

func (*Session) Why ¶

func (s *Session) Why() string

Why returns the formatted value-provenance report for the active command, rendered with the same engine the built-in --why flag uses.

If the session is nil, uninitialized, or Why reporting is not enabled on the application, Why returns an empty string.

func (*Session) WhyJSON ¶

func (s *Session) WhyJSON() string

WhyJSON returns the machine-readable JSON value-provenance report for the active command, rendered with the same engine --why=json uses.

If the session is nil, uninitialized, or WhyJSON is not enabled on the application, WhyJSON returns an empty string.

type TagAwareHelpProvider ¶

type TagAwareHelpProvider interface {
	// Help returns the tailored help description for the field given its declared tags.
	//
	// The engine consults the provider when the owning field declares no help
	// tag; a field with a help tag shows that text instead. Shells show the
	// provider's text as the description of the field's completion candidates.
	Help(tags FieldTags) string
}

TagAwareHelpProvider is implemented by custom domain types whose help description depends on custom struct tags declared on the owning field (see TagSpecProvider).

For example, File describes the field as an existing file, or as a file or stdin, depending on the declared tags.

The engine prefers TagAwareHelpProvider over HelpProvider. Implement exactly one of the pair, not both.

type TagAwarePredictable ¶

type TagAwarePredictable interface {
	// Predict returns a predictor tailored to the field's declared tags.
	Predict(tags FieldTags) predict.Predictor
}

TagAwarePredictable is implemented by custom domain types whose autocompletion candidates are tailored to custom struct tags declared on the owning field.

For example, File returns executable completions when the executable tag is declared, or glob-filtered completions when the glob tag is declared.

The engine evaluates Predict during schema compilation; implementations must not depend on runtime parsed values. Implement exactly one of Predictable or TagAwarePredictable, not both.

type TagKind ¶

type TagKind = spec.TagKind

TagKind describes how a custom field tag's value is parsed and validated.

type TagSpec ¶

type TagSpec = spec.TagSpec

TagSpec declares a single custom struct tag accepted by a domain type.

Domain types register their specs through TagSpecProvider; the specs feed the strict tag-key vocabulary, schema-time value parsing, and combination exclusion checks for every field of that type. The fields are:

  • Name: the struct tag key, without quotes (e.g. "existing").
  • Kind: the value grammar, either TagKindBool or TagKindString.
  • Validate: an optional check of the raw value of a TagKindString tag, run at schema build. Return a self-describing error; it is wrapped as a schema error.
  • Excludes: tag keys that cannot be declared alongside this one. Declaring both is a schema error.

Implementing TagSpecs on a domain type also makes those tags available to TagAwareHelpProvider and TagAwarePredictable through FieldTags.

type TagSpecProvider ¶

type TagSpecProvider = spec.TagSpecProvider

TagSpecProvider is implemented by custom domain types that define custom struct tags accepted on fields of their type (e.g. the existing tag on File and Dir).

Registered specs feed strict tag validation, schema-time value parsing, and tag mutual exclusion checks.

type UsageError ¶

type UsageError interface {
	error

	// IsUsageError reports whether the error represents invalid command-line input.
	IsUsageError() bool

	// CommandPath returns the space-separated command path where the error occurred.
	CommandPath() string

	// Usage returns the syntax usage summary for the command where the error occurred.
	Usage() string
}

UsageError is an interface implemented by errors that represent invalid command-line usage.

When App.Exit receives an error satisfying UsageError, it prints the message to standard error, appends usage guidance as configured by UsageOnErrorMode, and terminates the process with exit code 2. Self-describing value errors (coercion failures and value-constraint violations, whose messages already name the offending flag and value) print the message alone regardless of the configured mode.

type UsageOnErrorMode ¶

type UsageOnErrorMode int

UsageOnErrorMode specifies how command usage and help hints are formatted on standard error when a user supplies invalid command-line input.

When an input error violates a specific value constraint (such as range, length, enum, or type coercion), CONGA treats the failure as self-describing and renders only the specific error message to keep output readable, regardless of the configured mode. Syntax errors, unknown flags, and missing required inputs render contextual guidance according to the active mode.

const (
	// UsageSummary formats usage errors with a concise 1-2 line command syntax
	// guide followed by a hint to run --help. This is the default error display mode.
	UsageSummary UsageOnErrorMode = iota

	// UsageFull formats usage errors with the error message followed by the complete
	// command help screen, including flags, arguments, and subcommands.
	UsageFull

	// UsageHint formats usage errors with only the error message followed by a
	// single-line "Run '<command> --help' for more information." hint, without
	// syntax details.
	UsageHint

	// UsageSilence formats usage errors with only the bare error message, omitting all
	// usage instructions and help hints.
	UsageSilence
)

type Validator ¶

type Validator interface {
	// Validate checks cross-field constraints across the command and its session.
	Validate(ctx context.Context, session *Session) error
}

Validator is implemented by command structs that perform cross-field semantic validation.

Validate is the first lifecycle stage. Hooks run top-down from root to leaf, after struct tag constraints and domain-type SelfValidator checks have already passed, and before any PreRunner, Runner, PostRunner, or Finalizer hook executes. If Validate returns an error, Run returns it without running the remaining stages (no command has been initialized, so no Finally hook runs); IsUsageError reports true and App.Exit exits with status 2. For a built-in subcommand such as HelpCommand, only the leaf command's Validate hook runs.

See https://docs.conga.sh/explanation/lifecycle/.

type ValueSource ¶

type ValueSource = container.Source

ValueSource identifies the configuration tier from which a flag or argument was resolved.

CONGA resolves flags through a four-tier precedence ladder:

  1. SourceCLI: Explicit command-line arguments.
  2. SourceEnv: Environment variables.
  3. SourceConfig: Configuration files.
  4. SourceDefault: Struct tag defaults.

If none of these tiers provide a value, the source is SourceNone.

type VersionCommand ¶

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

VersionCommand provides an opt-in version subcommand.

Declare a VersionCommand field directly on a command struct:

type CLI struct {
	Version conga.VersionCommand `summary:"Show version and build information"`
}

The version subcommand is a meta-command: it bypasses the execution lifecycle, so ancestor PreRunner, PostRunner, and Finalizer hooks do not run for it.

See https://docs.conga.sh/reference/builtins/.

func (*VersionCommand) JSON ¶

func (v *VersionCommand) JSON() bool

JSON reports whether the version output should be rendered as a JSON object.

func (*VersionCommand) Run ¶

func (v *VersionCommand) Run(ctx context.Context, session *Session) error

Run renders detailed application version information to Session.Stdout.

If VersionCommand.JSON is true, Run renders a machine-readable JSON payload.

Panics:

  • If ctx is nil.

type WhyOption ¶

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

WhyOption configures the built-in --why provenance reporting engine on App.EnableWhy.

WhyOption is a sealed interface: values are produced exclusively by CONGA option constructors such as WhyJSON, and cannot be implemented by other packages.

func WhyJSON ¶

func WhyJSON() WhyOption

WhyJSON enables machine-readable JSON output (--why=json) on App.EnableWhy.

By default, App.EnableWhy compiles only the human-readable text table renderer, keeping the binary footprint lean and dead-code eliminating the RFC 8259 JSON serialization pipeline. Pass WhyJSON to opt into machine-readable provenance reports.

Directories ¶

Path Synopsis
_examples
05-domain-types command
26-library-embedding command
This example demonstrates embedding CONGA as a library inside a host process: the host supplies the argument vector, injects its own output streams, intercepts termination via a custom exit handler, and consumes typed errors programmatically instead of letting the framework take over the process.
This example demonstrates embedding CONGA as a library inside a host process: the host supplies the argument vector, injects its own output streams, intercepts termination via a custom exit handler, and consumes typed errors programmatically instead of letting the framework take over the process.
99-kitchen-sink command
internal/inspector
Package inspector renders the resolved configuration state of a CONGA command chain: every flag and argument of every active command from root down to the leaf, with its resolved value and origin.
Package inspector renders the resolved configuration state of a CONGA command chain: every flag and argument of every active command from root down to the leaf, with its resolved value and origin.
internal/testutil
Package testutil provides shared testscript commands used by the example end-to-end test suites.
Package testutil provides shared testscript commands used by the example end-to-end test suites.
cmd
conga-lint command
Command conga-lint runs CONGA's static schema analyzer over Go packages.
Command conga-lint runs CONGA's static schema analyzer over Go packages.
decoder
hcl
Package hcl provides the HCL configuration decoder for CONGA applications.
Package hcl provides the HCL configuration decoder for CONGA applications.
json
Package json provides the JSON configuration decoder for CONGA applications.
Package json provides the JSON configuration decoder for CONGA applications.
toml
Package toml provides the TOML configuration decoder for CONGA applications.
Package toml provides the TOML configuration decoder for CONGA applications.
yaml
Package yaml provides the YAML configuration decoder for CONGA applications.
Package yaml provides the YAML configuration decoder for CONGA applications.
internal
analyzer
Package analyzer implements conga-lint, a static analysis pass that enforces CONGA CLI struct contracts at lint time.
Package analyzer implements conga-lint, a static analysis pass that enforces CONGA CLI struct contracts at lint time.
appname
Package appname derives the invoking binary's display name from os.Args[0].
Package appname derives the invoking binary's display name from os.Args[0].
assertx
Package assertx provides testing assertion extensions augmenting github.com/alecthomas/assert/v2.
Package assertx provides testing assertion extensions augmenting github.com/alecthomas/assert/v2.
casing
Package casing converts identifier strings between common casing styles.
Package casing converts identifier strings between common casing styles.
coerce
Package coerce converts raw CLI values to Go types using built-in and registered parsers.
Package coerce converts raw CLI values to Go types using built-in and registered parsers.
completion
Package completion provides shell script generation adapters for CONGA command line tools.
Package completion provides shell script generation adapters for CONGA command line tools.
completion/bash
Package bash renders completion results in bash's line-oriented framing and generates the bash registration snippet for the wire protocol (docs/completion-wire-protocol.md).
Package bash renders completion results in bash's line-oriented framing and generates the bash registration snippet for the wire protocol (docs/completion-wire-protocol.md).
completion/elvish
Package elvish renders completion results as a single-line JSON object for elvish's edit:complex-candidate consumption and generates the elvish registration snippet for the wire protocol (docs/completion-wire-protocol.md).
Package elvish renders completion results as a single-line JSON object for elvish's edit:complex-candidate consumption and generates the elvish registration snippet for the wire protocol (docs/completion-wire-protocol.md).
completion/export
Package export renders completion results as single-line JSON: the machine-readable test surface and unknown-shell fallback framing of the wire protocol (docs/completion-wire-protocol.md).
Package export renders completion results as single-line JSON: the machine-readable test surface and unknown-shell fallback framing of the wire protocol (docs/completion-wire-protocol.md).
completion/fish
Package fish renders completion results in fish's native completion feed and generates the fish registration snippet for the wire protocol (docs/completion-wire-protocol.md).
Package fish renders completion results in fish's native completion feed and generates the fish registration snippet for the wire protocol (docs/completion-wire-protocol.md).
completion/lex
Package lex implements a clean-room lexer for bash COMP_LINE command lines (docs/completion-wire-protocol.md).
Package lex implements a clean-room lexer for bash COMP_LINE command lines (docs/completion-wire-protocol.md).
completion/nushell
Package nushell renders completion results as a bare JSON array of records for nushell's external completer and generates the nushell registration snippet for the wire protocol (docs/completion-wire-protocol.md).
Package nushell renders completion results as a bare JSON array of records for nushell's external completer and generates the nushell registration snippet for the wire protocol (docs/completion-wire-protocol.md).
completion/powershell
Package powershell renders completion results as the JSON payload consumed by the generated registration snippet and generates the Register-ArgumentCompleter snippets for the wire protocol (docs/completion-wire-protocol.md).
Package powershell renders completion results as the JSON payload consumed by the generated registration snippet and generates the Register-ArgumentCompleter snippets for the wire protocol (docs/completion-wire-protocol.md).
completion/wire
Package wire defines the shell-agnostic completion wire vocabulary shared by the native completion drivers: candidates, directives, per-shell quoting helpers, the RFC 8259 string escaper, and the CONGA_* sideband environment readers.
Package wire defines the shell-agnostic completion wire vocabulary shared by the native completion drivers: candidates, directives, per-shell quoting helpers, the RFC 8259 string escaper, and the CONGA_* sideband environment readers.
completion/zsh
Package zsh renders completion results as the record stream consumed by the generated registration snippet and generates the #compdef registration snippets for the wire protocol (docs/completion-wire-protocol.md).
Package zsh renders completion results as the record stream consumed by the generated registration snippet and generates the #compdef registration snippets for the wire protocol (docs/completion-wire-protocol.md).
cond
Package cond provides lightweight, generic conditional assignment and fallback utilities designed to eliminate temporary variable boilerplate and improve code readability.
Package cond provides lightweight, generic conditional assignment and fallback utilities designed to eliminate temporary variable boilerplate and improve code readability.
configdata
Package configdata holds the resolved configuration tier consumed by the value binder: scalar values and per-key map values keyed by bindable config keys.
Package configdata holds the resolved configuration tier consumed by the value binder: scalar values and per-key map values keyed by bindable config keys.
configengine
Package configengine implements the configuration-file resolution engine shared by the root conga package: decoder registration, search-tier probing, strict content validation, and the per-invocation Resolver that turns those pieces into loaded files.
Package configengine implements the configuration-file resolution engine shared by the root conga package: decoder registration, search-tier probing, strict content validation, and the per-invocation Resolver that turns those pieces into loaded files.
container
Package container defines the source and classification metadata used by CONGA's built-in command-line containers.
Package container defines the source and classification metadata used by CONGA's built-in command-line containers.
dotenv
Package dotenv loads environment variables from .env files.
Package dotenv loads environment variables from .env files.
filex
Package filex provides shared file and stream utilities for size-limited reads and DoS protection limits across CONGA packages.
Package filex provides shared file and stream utilities for size-limited reads and DoS protection limits across CONGA packages.
help
Package help renders command help, usage, version, and completion instructions.
Package help renders command help, usage, version, and completion instructions.
jsonwire
Package jsonwire provides the minimal JSON string encoding used by CONGA's machine-readable outputs (shell completion and version reporting) without pulling in encoding/json.
Package jsonwire provides the minimal JSON string encoding used by CONGA's machine-readable outputs (shell completion and version reporting) without pulling in encoding/json.
levenshtein
Package levenshtein provides edit distance calculation and typo suggestions for commands and flags.
Package levenshtein provides edit distance calculation and typo suggestions for commands and flags.
pathx
Package pathx expands environment variables and tilde prefixes in paths.
Package pathx expands environment variables and tilde prefixes in paths.
scanx
Package scanx provides line-scanning primitives for whitespace-trimmed, comment-aware readers.
Package scanx provides line-scanning primitives for whitespace-trimmed, comment-aware readers.
sentinel
Package sentinel centralizes the error sentinels owned by opt-in subsystems (configuration, .env, shell completion).
Package sentinel centralizes the error sentinels owned by opt-in subsystems (configuration, .env, shell completion).
signals
Package signals provides the platform signal table shared by the signal completion predictors and the syscall.Signal type parser.
Package signals provides the platform signal table shared by the signal completion predictors and the syscall.Signal type parser.
slicex
Package slicex provides generic functional utilities for slices.
Package slicex provides generic functional utilities for slices.
spec
Package spec builds and validates command schemas from application structs.
Package spec builds and validates command schemas from application structs.
stringx
Package stringx provides string formatting and stringification primitives for CLI values.
Package stringx provides string formatting and stringification primitives for CLI values.
style
Package style provides the terminal styling vocabulary for CONGA completion: color and attribute tokens, their ECMA-48 SGR translations, file extension styling, and the default completion palette.
Package style provides the terminal styling vocabulary for CONGA completion: color and attribute tokens, their ECMA-48 SGR translations, file extension styling, and the default completion palette.
tokenizer
Package tokenizer splits command-line input into typed tokens and provides scanners for traversing them.
Package tokenizer splits command-line input into typed tokens and provides scanners for traversing them.
why
Package why assembles and renders the neutral value-provenance report produced by the --why builtin: one row per flag and configuration-file container with its display value, the source tier, and the env/config channels that can set the value.
Package why assembles and renders the neutral value-provenance report produced by the --why builtin: one row per flag and configuration-file container with its display value, the source tier, and the env/config channels that can set the value.
Package network provides domain types and autocompletion predictors for network interfaces, hosts, ports, HTTP status codes, MIME types, and HTTP methods, plus an optional standard library binding for *net.Interface fields.
Package network provides domain types and autocompletion predictors for network interfaces, hosts, ports, HTTP status codes, MIME types, and HTTP methods, plus an optional standard library binding for *net.Interface fields.
Package predict generates shell autocompletion candidates for command-line tools.
Package predict generates shell autocompletion candidates for command-line tools.
Package system provides domain types and autocompletion predictors for system users, groups, running processes, PIDs, POSIX signals, locales, and environment variables, plus optional standard library bindings for *user.User, *user.Group, and syscall.Signal fields.
Package system provides domain types and autocompletion predictors for system users, groups, running processes, PIDs, POSIX signals, locales, and environment variables, plus optional standard library bindings for *user.User, *user.Group, and syscall.Signal fields.
Package timezone provides an autocompletion predictor for IANA timezone identifiers and an optional standard library binding for *time.Location fields.
Package timezone provides an autocompletion predictor for IANA timezone identifiers and an optional standard library binding for *time.Location fields.

Jump to

Keyboard shortcuts

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