cmdutil

package module
v0.0.0-...-052fa94 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2026 License: Apache-2.0 Imports: 12 Imported by: 9

README

Package cloudeng.io/cmdutil

import cloudeng.io/cmdutil

Package cmdutil provides support for implementing command line utilities.

Variables

ErrInterrupt
ErrInterrupt = errors.New("interrupted")

ErrInterrupt is returned as the cause for HandleInterrupt cancellations.

Functions

Func BuildInfoJSON
func BuildInfoJSON() json.RawMessage

BuildInfoJSON returns the build information as a JSON raw message or nil if the build information is not available.

Func CopyAll
func CopyAll(fromDir, toDir string, ovewrite bool) error

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 is suitable for very large directory trees since it uses filepath.Walk.

Func CopyFile
func CopyFile(from, to string, perms os.FileMode, overwrite bool) (returnErr error)

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 Exit
func Exit(format string, args ...any)

Exit formats and prints the supplied parameters to os.Stderr and then calls os.Exit(1).

Func HandleInterrupt
func HandleInterrupt(ctx context.Context) (context.Context, context.CancelCauseFunc)

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
func HandleSignals(fn func(), signals ...os.Signal)

HandleSignals will asynchronously invoke the supplied function when the specified signals are received.

Func IsDir
func IsDir(path string) bool

IsDir returns true iff path exists and is a directory.

Func ListDir
func ListDir(dir string) ([]string, error)

ListDir returns the lexicographically ordered directories that lie beneath dir.

Func ListRegular
func ListRegular(dir string) ([]string, error)

ListRegular returns the lexicographically ordered regular files that lie beneath dir.

Func LogBuildInfo
func LogBuildInfo(logger *slog.Logger)

LogBuildInfo logs build information using the provided logger.

Func ReplaceAttrNoTime
func ReplaceAttrNoTime(_ []string, a slog.Attr) slog.Attr

ReplaceAttrNoTime returns a slog.Attr with the time attribute removed. This is useful for tests where the time is not deterministic.

Func VCSInfo
func VCSInfo() (goVersion, revision string, lastCommit time.Time, dirty, ok bool)

VCSInfo extracts version control system information from the build info if available. The returned values are the revision, last commit time, a boolean indicating whether there were uncommitted changes (dirty) and a boolean indicating whether the information was successfully extracted.

Types

Type Logger
type Logger struct {
	*slog.Logger
	// contains filtered or unexported fields
}

Logger represents a logger with an optional closer for the log file if one is specified.

Methods
func (l *Logger) Close() error
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.

Methods
func (c LoggingConfig) Leveler() slog.Leveler
func (c LoggingConfig) NewLogger() (*Logger, error)

NewLogger creates a new logger based on the configuration.

func (c LoggingConfig) NewLoggerMust(opts *slog.HandlerOptions) *Logger

NewLoggerMust is like NewLogger but panics on error.

func (c LoggingConfig) NewLoggerOpts(opts *slog.HandlerOptions) (*Logger, error)

NewLoggerOpts creates a new logger based on the configuration and custom handler options.

func (c LoggingConfig) Options() *slog.HandlerOptions
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.

Methods
func (lf LoggingFlags) LoggingConfig() LoggingConfig

LoggingConfig returns the logging configuration represented by the flags.

Examples

ExampleLoggingFlags

Documentation

Overview

Package cmdutil provides support for implementing command line utilities.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrInterrupt = errors.New("interrupted")

ErrInterrupt is returned as the cause for HandleInterrupt cancellations.

Functions

func BuildInfoJSON

func BuildInfoJSON() json.RawMessage

BuildInfoJSON returns the build information as a JSON raw message or nil if the build information is not available.

func CopyAll

func CopyAll(fromDir, toDir string, ovewrite bool) error

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 is suitable for very large directory trees since it uses filepath.Walk.

func CopyFile

func CopyFile(from, to string, perms os.FileMode, overwrite bool) (returnErr error)

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 Exit

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

Exit formats and prints the supplied parameters to os.Stderr and then calls os.Exit(1).

func HandleInterrupt

func HandleInterrupt(ctx context.Context) (context.Context, context.CancelCauseFunc)

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

func HandleSignals(fn func(), signals ...os.Signal)

HandleSignals will asynchronously invoke the supplied function when the specified signals are received.

func IsDir

func IsDir(path string) bool

IsDir returns true iff path exists and is a directory.

func ListDir

func ListDir(dir string) ([]string, error)

ListDir returns the lexicographically ordered directories that lie beneath dir.

func ListRegular

func ListRegular(dir string) ([]string, error)

ListRegular returns the lexicographically ordered regular files that lie beneath dir.

func LogBuildInfo

func LogBuildInfo(logger *slog.Logger)

LogBuildInfo logs build information using the provided logger.

func ReplaceAttrNoTime

func ReplaceAttrNoTime(_ []string, a slog.Attr) slog.Attr

ReplaceAttrNoTime returns a slog.Attr with the time attribute removed. This is useful for tests where the time is not deterministic.

func VCSInfo

func VCSInfo() (goVersion, revision string, lastCommit time.Time, dirty, ok bool)

VCSInfo extracts version control system information from the build info if available. The returned values are the revision, last commit time, a boolean indicating whether there were uncommitted changes (dirty) and a boolean indicating whether the information was successfully extracted.

Types

type Logger

type Logger struct {
	*slog.Logger
	// contains filtered or unexported fields
}

Logger represents a logger with an optional closer for the log file if one is specified.

func (*Logger) Close

func (l *Logger) Close() error

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() (*Logger, error)

NewLogger creates a new logger based on the configuration.

func (LoggingConfig) NewLoggerMust

func (c LoggingConfig) NewLoggerMust(opts *slog.HandlerOptions) *Logger

NewLoggerMust is like NewLogger but panics on error.

func (LoggingConfig) NewLoggerOpts

func (c LoggingConfig) NewLoggerOpts(opts *slog.HandlerOptions) (*Logger, error)

NewLoggerOpts creates a new logger based on the configuration and custom handler options.

func (LoggingConfig) Options

func (c LoggingConfig) Options() *slog.HandlerOptions

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")
}

func (LoggingFlags) LoggingConfig

func (lf LoggingFlags) LoggingConfig() LoggingConfig

LoggingConfig returns the logging configuration represented by the flags.

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 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.
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:

Jump to

Keyboard shortcuts

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