Documentation
ΒΆ
Index ΒΆ
- type AppInfo
- type BuildSetting
- type CLI
- func (c *CLI[T]) Execute(fn func(ctx context.Context, cli *CLI[T], logger *slog.Logger) error)
- func (cli *CLI[T]) GenerateMarkdown() (string, error)
- func (c *CLI[T]) GetLogHandler() slog.Handler
- func (c *CLI[T]) GetLogger() *slog.Logger
- func (cli *CLI[T]) GetVersion() *Version
- func (cli *CLI[T]) NewContext(ctx context.Context) context.Context
- func (cli *CLI[T]) NewHTTPContext(next http.Handler) http.Handler
- type Link
- type LoggingPlugin
- type MarkdownCommand
- type Module
- type NonSensitiveVersion
- type Option
- func Defaults[T any]() []Option[T]
- func WithAppInfo[T any](app AppInfo) Option[T]
- func WithEnvFiles[T any](paths ...string) Option[T]
- func WithGithubDebug[T any]() Option[T]
- func WithKongOptions[T any](opts ...kong.Option) Option[T]
- func WithLoggingHandlerOptions[T any](opts *slog.HandlerOptions) Option[T]
- func WithLoggingPlugin[T any](global bool, opts *slog.HandlerOptions) Option[T]
- func WithMarkdownPlugin[T any]() Option[T]
- func WithVersionPlugin[T any]() Option[T]
- type Version
- type VersionFlag
- type VersionJSONFlag
- type VersionPlugin
Constants ΒΆ
This section is empty.
Variables ΒΆ
This section is empty.
Functions ΒΆ
This section is empty.
Types ΒΆ
type AppInfo ΒΆ
type AppInfo struct {
Name string `json:"name"` // Application name. Defaults to the main module path.
Description string `json:"description"` // Application description.
Version string `json:"build_version"` // Build version. Uses VCS info if available.
Commit string `json:"build_commit"` // VCS commit SHA. Uses VCS info if available.
Date string `json:"build_date"` // VCS commit date. Uses VCS info if available.
Links []Link `json:"links,omitempty"` // Links to the project's website, support, issues, security, etc.
}
func (*AppInfo) IsModuleName ΒΆ
IsModuleName returns true if the name looks like a module path-style format, otherwise false.
type BuildSetting ΒΆ
type BuildSetting struct {
// Key and Value describe the build setting.
// Key must not contain an equals sign, space, tab, or newline.
// Value must not contain newlines ('\n').
Key string `json:"key"`
Value string `json:"value"`
}
BuildSetting describes a setting that may be used to understand how the binary was built. For example, VCS commit and dirty status is stored here.
func (BuildSetting) String ΒΆ
func (s BuildSetting) String() string
type CLI ΒΆ
type CLI[T any] struct { kong.Plugins // Kong-specific plugins. // Context is the context returned by kong after initial parsing. Context *kong.Context `kong:"-"` // Flags are the user-provided flags. Flags *T `embed:""` // Debug can be used to enable/disable debugging as a global flag. Also // sets the log level to debug. Debug bool `short:"D" name:"debug" env:"DEBUG" help:"enables debug mode"` // contains filtered or unexported fields }
CLI is the main construct for clix, obtained via New or NewWithDefaults.
func FromContext ΒΆ
FromContext returns the CLI[T] from the context, or nil if it is not present.
func New ΒΆ
New executes the cli parser, with the provided options (no defaults are configured). Order of options is important. See also NewWithDefaults.
Supported struct tags: https://github.com/alecthomas/kong#supported-tags
func NewWithDefaults ΒΆ
NewWithDefaults executes the cli parser, with the provided options and associated recommended defaults. Order of options is important. See also New and Defaults.
Supported struct tags: https://github.com/alecthomas/kong#supported-tags
Initialize a new CLI like so:
type Flags struct {
// Normal kong flags.
SomeFlag string `env:"SOME_FLAG" help:"some flag"`
}
var cli = clix.NewWithDefaults[Flags]() // Where Flags is a user-provided type (struct).
func main() {
// [...]
}
func (*CLI[T]) Execute ΒΆ added in v2.0.6
Execute is an optional helper for wrapping the body of an application's main() function, so it can exit cleanly. It is only useful as the last call in main(), as it never returns (unless the exit function was overridden via kong.Exit). Usage:
func main() {
cli.Execute(run)
}
func run(ctx context.Context, cli *clix.CLI[Flags], logger *slog.Logger) error {
db, err := openDB(ctx)
if err != nil {
return err
}
defer db.Close() // Runs even if run() returns an error or panics.
// [...]
}
Behavior:
- The provided context is canceled when SIGINT or SIGTERM is received (see signal.NotifyContext). After the first signal, default signal handling is restored, so a second signal forcefully terminates the application. The context also contains the CLI (see FromContext).
- The provided CLI is the CLI that Execute was called on.
- The provided logger is the logger from CLI.GetLogger, or slog.Default if the logging plugin is disabled.
- If fn returns nil, or returns context.Canceled after a signal was received, the application exits with code 0.
- If fn returns an error, it is logged and the application exits with code 1, or the code from the error if it implements kong.ExitCoder.
- If fn panics, the panic and its stack trace are logged and the application exits with code 2. Note that only panics from the goroutine running fn can be recovered.
Log entries from Execute use the location of the panic as their source, or otherwise the location where Execute was called, rather than Execute itself.
Because fn returns rather than calling os.Exit directly, deferred calls in fn always run before the application exits, unlike with log.Fatal-style helpers.
Alternatively, kong has built-in ways of achieving something similar:
- Command structs can implement a Run(...) error method, which is invoked through kong.Context.Run (using cli.Context.Run(...)) for the selected command. Its arguments are injected from bound values (see kong.Bind, kong.BindTo, and kong.Context.Bind), and the logger is already bound by the logging plugin. Hooks like AfterApply can also be used to run logic before any Run method.
- kong.Kong.FatalIfErrorf (using cli.Context.FatalIfErrorf(err)) prints the error to stderr (not through the logger), and exits with code 1, or the code from kong.ExitCoder. Deferred calls are skipped, and panics are not handled.
These can be combined with Execute, by returning the result of cli.Context.Run from fn.
func (*CLI[T]) GenerateMarkdown ΒΆ
func (*CLI[T]) GetLogHandler ΒΆ
GetLogHandler returns the generated logger handler if enabled, nil otherwise. Usually don't need to use this directly. Not used if logging configuration is disabled.
func (*CLI[T]) GetLogger ΒΆ
GetLogger returns the generated logger if enabled, nil otherwise. If global logging is enabled, you can also use log/slog.Default.
func (*CLI[T]) GetVersion ΒΆ
GetVersion returns the version information for the CLI, which will be populated after parsing.
func (*CLI[T]) NewContext ΒΆ
NewContext returns a new context with the CLI[T] injected. It can be accessed from the context with FromContext.
type Link ΒΆ
Link allows you to define a link to be included in the version and usage output.
func GithubLinks ΒΆ
GithubLinks return an opinonated set of links for the project, using common Github layout conventions.
type LoggingPlugin ΒΆ
type LoggingPlugin struct {
// Level is the minimum level of log messages to output, must be one of none|debug|info|warn|error.
Level string `` /* 127-byte string literal not displayed */
// JSON enables JSON logging.
JSON bool `name:"log.json" env:"LOG_JSON" help:"output logs in JSON format"`
// Path is the path to the log file.
Path string `name:"log.path" env:"LOG_PATH" type:"path" help:"path to log file (disables stderr logging)"`
}
LoggingPlugin are the flags that define how log entries are processed/returned.
func (*LoggingPlugin) CreateHandler ΒΆ
func (l *LoggingPlugin) CreateHandler(isDebug, setGlobal bool, opts *slog.HandlerOptions) (handler slog.Handler, err error)
CreateHandler creates a new log/slog.Handler with the provided configuration.
func (*LoggingPlugin) GetLevel ΒΆ
func (l *LoggingPlugin) GetLevel() slog.Level
type MarkdownCommand ΒΆ
type MarkdownCommand struct {
DisableExit bool `kong:"-"`
}
func (*MarkdownCommand) BeforeReset ΒΆ
func (m *MarkdownCommand) BeforeReset( ctx *kong.Kong, version *Version, ) error
func (*MarkdownCommand) GenerateMarkdown ΒΆ
func (m *MarkdownCommand) GenerateMarkdown( model *kong.Application, tmpl *template.Template, version *Version, ) (string, error)
GenerateMarkdown generates the markdown documentation for the CLI, returning the markdown as a string.
type Module ΒΆ
type Module struct {
Path string `json:"path,omitempty"` // module path
Version string `json:"version,omitempty"` // module version
Sum string `json:"sum,omitempty"` // checksum
Replace *Module `json:"replaces,omitempty"` // replaced by this module
}
Module represents a module.
type NonSensitiveVersion ΒΆ
type NonSensitiveVersion struct {
AppInfo *AppInfo `json:"app_info,omitempty"` // Application information.
Command string `json:"command"` // Executable name where the command was called from.
GoVersion string `json:"go_version"` // Version of Go that produced this binary.
OS string `json:"os"` // Operating system for this build.
Arch string `json:"arch"` // CPU Architecture for build build.
}
NonSensitiveVersion represents the version information for the CLI.
type Option ΒΆ
Option is a function that can be used to configure the CLI.
func WithAppInfo ΒΆ
WithAppInfo adds the provided application information to the CLI.
func WithEnvFiles ΒΆ
WithEnvFiles loads environment variables from ".env" style files from the provided paths. If no paths are provided, it will load from the current working directory as ".env", but will not return an error if the file has access issues/doesn't exist. For variables defined in multiple sources, the precedence is: command-line flags, existing environment variables, then values from the env files. Loading can be disabled with --no-dot-env or NO_DOT_ENV=true.
func WithGithubDebug ΒΆ
WithGithubDebug enables debug mode if the RUNNER_DEBUG environment variable is set, which is set when running a Github Action in debug mode.
func WithKongOptions ΒΆ
WithKongOptions adds the provided kong options to the CLI.
func WithLoggingHandlerOptions ΒΆ
func WithLoggingHandlerOptions[T any](opts *slog.HandlerOptions) Option[T]
WithLoggingHandlerOptions allows customizing how slog handlers are created. This only applies when using the WithLoggingPlugin plugin. By default, the handler options are set to:
- Level: values passed from --log.level flag.
- AddSource: true
- ReplaceAttr: nil
func WithLoggingPlugin ΒΆ
func WithLoggingPlugin[T any](global bool, opts *slog.HandlerOptions) Option[T]
WithLoggingPlugin adds the logging plugin to the CLI. This includes flags for controlling log/slog logging levels, logging to files, JSON output, and supports setting the global slog logger. You can access the resulting log/slog.Handler via CLI.GetLogHandler and the log/slog.Logger via CLI.GetLogger. opts is optional, and can also be set using WithLoggingHandlerOptions.
func WithMarkdownPlugin ΒΆ
WithMarkdownPlugin adds a hidden "generate-markdown" command that allows generating markdown documentation for the CLI. To make it so this command ignores any other required flags, it's invoked before kong applies additional restrictions, which means it does not support special flags. To adjust the behavior, you can use environment variables:
- CLIX_TEMPLATE_PATH: optional path to a directory containing template files to use for the markdown.
- CLIX_OUTPUT_PATH: path to write the markdown to, or '-' to write to stdout (defaults to stdout).
func WithVersionPlugin ΒΆ
WithVersionPlugin adds the version plugin to the CLI. This includes flags for --version, --version-json, etc.
type Version ΒΆ
type Version struct {
AppInfo *AppInfo `json:"app_info,omitempty"` // Application information.
Settings []BuildSetting `json:"build_settings,omitempty"` // Other information about the build.
Dependencies []Module `json:"dependencies,omitempty"` // Module dependencies.
Command string `json:"command"` // Executable name where the command was called from.
GoVersion string `json:"go_version"` // Version of Go that produced this binary.
OS string `json:"os"` // Operating system for this build.
Arch string `json:"arch"` // CPU Architecture for build build.
}
Version represents the version information for the CLI.
func GetVersionInfo ΒΆ
GetVersionInfo returns the version information for the CLI.
func (*Version) GetSetting ΒΆ
GetSetting returns the value of the setting with the given key, otherwise defaults to defaultValue.
func (*Version) NonSensitive ΒΆ
func (v *Version) NonSensitive() *NonSensitiveVersion
NonSensitive returns a copy of Version with sensitive information removed.
type VersionFlag ΒΆ
type VersionFlag bool
func (VersionFlag) BeforeReset ΒΆ
func (v VersionFlag) BeforeReset(ver *Version) error
type VersionJSONFlag ΒΆ
type VersionJSONFlag bool
func (VersionJSONFlag) BeforeReset ΒΆ
func (v VersionJSONFlag) BeforeReset(ver *Version) error
type VersionPlugin ΒΆ
type VersionPlugin struct {
Version VersionFlag `short:"v" name:"version" help:"prints version information and exits"`
VersionJSON VersionJSONFlag `name:"version-json" help:"prints version information in JSON format and exits"`
}