Documentation
¶
Overview ¶
Package cmdutil provides support for implementing command line utilities.
Index ¶
- Variables
- func BuildInfoJSON() jsontext.Value
- func CopyAll(fromDir, toDir string, overwrite bool) error
- func CopyFile(from, to string, perms os.FileMode, overwrite bool) (returnErr error)
- func Exit(format string, args ...any)deprecated
- func Exitf(format string, args ...any)
- func HandleInterrupt(ctx context.Context) (context.Context, context.CancelCauseFunc)
- func HandleSignals(fn func(), signals ...os.Signal)
- func IsDir(path string) bool
- func IsExplicitlySet(fs *flag.FlagSet, name string) bool
- func ListDir(dir string) ([]string, error)
- func ListRegular(dir string) ([]string, error)
- func LogBuildInfo(logger *slog.Logger)
- func ReplaceAttrNoTime(_ []string, a slog.Attr) slog.Attr
- func VCSInfo() (goVersion, revision string, lastCommit, execModTime time.Time, dirty, ok bool)
- func WaitForExit(ctx context.Context, funcs ...func() error) error
- func WaitForExitCtx(ctx context.Context, funcs ...func(context.Context) error) error
- type Logger
- type LoggingConfig
- func (c LoggingConfig) Leveler() slog.Leveler
- func (c LoggingConfig) NewLogger(opts ...LoggingOption) (*Logger, error)
- func (c LoggingConfig) NewLoggerMust(opts *slog.HandlerOptions, loggingOpts ...LoggingOption) *Logger
- func (c LoggingConfig) NewLoggerOpts(handlerOpts *slog.HandlerOptions, loggingOpts ...LoggingOption) (*Logger, error)
- func (c LoggingConfig) Options() *slog.HandlerOptions
- func (c LoggingConfig) WithFlagOverrides(fs *flag.FlagSet, lf LoggingFlags) LoggingConfig
- type LoggingFlags
- type LoggingOption
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrInterrupt = errors.New("interrupted")
ErrInterrupt is returned as the cause for HandleInterrupt cancellations.
Functions ¶
func BuildInfoJSON ¶
BuildInfoJSON returns the build information as a JSON raw message or nil if the build information is not available.
func CopyAll ¶
CopyAll will create an exact copy, including permissions, of a local filesystem hierarchy. The arguments must both refer to directories. A trailing slash (/) for the fromDir copies the contents of fromDir rather than fromDir itself. Thus:
CopyAll("a/b", "c") is the same as CopyAll("a/b/", "c/b")
and both create an exact copy of the tree a/b rooted at c/b.
If overwrite is set any existing files will be overwritten. Existing directories will always have their contents updated. It uses os.Root scoped APIs to prevent symlink TOCTOU traversal.
func CopyFile ¶
CopyFile will copy a local file with the option to overwrite an existing file and to set the permissions on the new file. It uses chmod to explicitly set permissions. It is not suitable for very large fles.
func Exitf ¶
Exitf formats and prints the supplied parameters to os.Stderr and then calls os.Exit(1).
func HandleInterrupt ¶
HandleInterrupt returns a context that is cancelled when an interrupt signal is received. The returned CancelCauseFunc should be used to cancel the context and will return ErrInterrupt as the cause.
func HandleSignals ¶
HandleSignals will asynchronously invoke the supplied function when the specified signals are received.
func IsExplicitlySet ¶
IsExplicitlySet returns true if the named flag was explicitly provided on the command line (i.e. after FlagSet.Parse was called). It relies on flag.FlagSet.Visit, which only visits flags that were set during parsing.
func ListDir ¶
ListDir returns the lexicographically ordered directories that lie beneath dir. It uses os.Root scoped APIs to prevent symlink TOCTOU traversal.
func ListRegular ¶
ListRegular returns the lexicographically ordered regular files that lie beneath dir. It uses os.Root scoped APIs to prevent symlink TOCTOU traversal.
func LogBuildInfo ¶
LogBuildInfo logs build information using the provided logger.
func ReplaceAttrNoTime ¶
ReplaceAttrNoTime returns a slog.Attr with the time attribute removed. This is useful for tests where the time is not deterministic.
func VCSInfo ¶
VCSInfo extracts version control system information from the build info, if available. It returns, in order:
- goVersion: the version of Go the executable was built with.
- revision: the vcs.revision recorded at build time.
- lastCommit: the vcs.time recorded at build time, ie. the time of that revision.
- execModTime: the modification time of the executable file. This is an approximation of when the executable was built and no more than that: it is the file's mtime, so it changes if the file is copied, touched or unpacked from an archive, and it is unrelated to the build info.
- dirty: whether vcs.modified was recorded, ie. whether the tree had uncommitted changes when it was built.
- ok: whether any vcs setting was found.
ok reports only on the vcs settings. goVersion and execModTime are determined independently of them and may be set even when ok is false, as happens for an executable built from a directory that is not a repository, or with -buildvcs=false. The zero values of revision, lastCommit and dirty are not distinguishable from values that were genuinely absent, so ok is what should be tested before reporting them.
func WaitForExit ¶
WaitForExit waits for all provided functions to return
Types ¶
type Logger ¶
Logger represents a logger with an optional closer for the log file if one is specified.
func (*Logger) LogBuildInfo ¶
func (l *Logger) LogBuildInfo()
LogBuildInfo logs build information using the logger.
type LoggingConfig ¶
type LoggingConfig struct {
Level int `yaml:"level" doc:"logging level: 0=error, 1=warn, 2=info, 3=debug"`
File string `yaml:"file" doc:"log file path. If not specified logs are written to stderr."`
Format string `yaml:"format" doc:"log format: text or json"`
SourceCode bool `yaml:"source_code" doc:"include source code file and line number in logs"`
}
LoggingConfig represents a logging configuration.
func (LoggingConfig) Leveler ¶
func (c LoggingConfig) Leveler() slog.Leveler
func (LoggingConfig) NewLogger ¶
func (c LoggingConfig) NewLogger(opts ...LoggingOption) (*Logger, error)
NewLogger creates a new logger based on the configuration.
func (LoggingConfig) NewLoggerMust ¶
func (c LoggingConfig) NewLoggerMust(opts *slog.HandlerOptions, loggingOpts ...LoggingOption) *Logger
NewLoggerMust is like NewLogger but panics on error.
func (LoggingConfig) NewLoggerOpts ¶
func (c LoggingConfig) NewLoggerOpts(handlerOpts *slog.HandlerOptions, loggingOpts ...LoggingOption) (*Logger, error)
NewLoggerOpts creates a new logger based on the configuration and custom handler options.
func (LoggingConfig) Options ¶
func (c LoggingConfig) Options() *slog.HandlerOptions
func (LoggingConfig) WithFlagOverrides ¶
func (c LoggingConfig) WithFlagOverrides(fs *flag.FlagSet, lf LoggingFlags) LoggingConfig
WithFlagOverrides returns a new LoggingConfig with fields overridden by the explicitly set flags in the provided FlagSet.
type LoggingFlags ¶
type LoggingFlags struct {
Level int `subcmd:"log-level,0,'logging level: 0=error, 1=warn, 2=info, 3=debug'"`
File string `subcmd:"log-file,,'log file path. If not specified logs are written to stderr, if set to - logs are written to stdout'"`
Format string `subcmd:"log-format,json,'log format: text or json'"`
SourceCode bool `subcmd:"log-source-code,false,'include source code file and line number in logs'"`
}
LoggingFlags represents common logging related command line flags.
Example ¶
package main
import (
"log/slog"
"cloudeng.io/cmdutil"
)
func main() {
// Typically these flags would be parsed from command line arguments.
flags := cmdutil.LoggingFlags{
Level: 2, // Info
Format: "text",
}
cfg := flags.LoggingConfig()
logger, err := cfg.NewLogger()
if err != nil {
panic(err)
}
slog.SetDefault(logger.Logger)
slog.Info("hello world")
}
Output:
func (LoggingFlags) LoggingConfig ¶
func (lf LoggingFlags) LoggingConfig() LoggingConfig
LoggingConfig returns the logging configuration represented by the flags.
type LoggingOption ¶
type LoggingOption func(*loggingOptions)
LoggingOption represents an option for configuring a logger beyond the slog.HandlerOptions provided by the LoggingConfig.
func WithWriteCloser ¶
func WithWriteCloser(wr io.WriteCloser) LoggingOption
WithWriteCloser sets the io.Writer for the slog.Logger to use and the Closer to return. It is intended to allow for setting a writer that supports log rotation or other logging destinations. If set, the File field of the LoggingConfig is ignored and the WriteCloser passed here is used instead.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package boolexpr provides a boolean expression evaluator and parser.
|
Package boolexpr provides a boolean expression evaluator and parser. |
|
Package cmdexec provides a means of executing multiple subcommands with the ability to expand the command line arguments using Go's text/template package and environment variables.
|
Package cmdexec provides a means of executing multiple subcommands with the ability to expand the command line arguments using Go's text/template package and environment variables. |
|
Package cmdtypes provides types that are shared by the configuration and command line packages, and that can be encoded and decoded as JSON, YAML and text without those packages depending on each other.
|
Package cmdtypes provides types that are shared by the configuration and command line packages, and that can be encoded and decoded as JSON, YAML and text without those packages depending on each other. |
|
Package envfile parses files containing shell-style environment variable definitions of the form NAME=VALUE, as commonly used in .env files.
|
Package envfile parses files containing shell-style environment variable definitions of the form NAME=VALUE, as commonly used in .env files. |
|
Package expect provides support for making expectations on the contents of input streams.
|
Package expect provides support for making expectations on the contents of input streams. |
|
Package flags provides support for working with flag variables, and for managing flag variables by embedding them in structs.
|
Package flags provides support for working with flag variables, and for managing flag variables by embedding them in structs. |
|
Package keys provides types and utilities for managing API keys/tokens.
|
Package keys provides types and utilities for managing API keys/tokens. |
|
keyscmd
Package keyscmd provides a set of utilities for reading and writing multiple keys stored in a single item in a file system using the format used by keys.InMemoryKeyStore.
|
Package keyscmd provides a set of utilities for reading and writing multiple keys stored in a single item in a file system using the format used by keys.InMemoryKeyStore. |
|
unsafekeystore
Package unsafekeystore is intended to document the use of plaintext, local filesystems being used to store keys.
|
Package unsafekeystore is intended to document the use of plaintext, local filesystems being used to store keys. |
|
Package profiling provides support for enabling profiling of command line tools via flags.
|
Package profiling provides support for enabling profiling of command line tools via flags. |
|
Package registry provides support for various forms of registry useful for building command line tools.
|
Package registry provides support for various forms of registry useful for building command line tools. |
|
Package signals provides support for working with operating system signals and contexts.
|
Package signals provides support for working with operating system signals and contexts. |
|
Package structdoc provides a means of exposing struct tags for use when generating documentation for those structs.
|
Package structdoc provides a means of exposing struct tags for use when generating documentation for those structs. |
|
Package subcmd provides a multi-level command facility of the following form:
|
Package subcmd provides a multi-level command facility of the following form: |