cli

package
v0.34.2 Latest Latest
Warning

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

Go to latest
Published: May 8, 2023 License: MIT Imports: 66 Imported by: 0

Documentation

Overview

Package cli implements sq's CLI. The spf13/cobra library is used, with some notable modifications.

Although cobra provides excellent functionality, it has some issues. Most prominently, its documentation suggests reliance upon package-level constructs for initializing the command tree (bad for testing).

Thus, this cmd package deviates from cobra's suggested usage pattern by eliminating all pkg-level constructs (which makes testing easier).

The entry point to this pkg is the Execute function.

Index

Constants

This section is empty.

Variables

View Source
var (
	OptLogEnabled = options.NewBool(
		"log",
		0,
		false,
		"Enable logging",
		"Enable logging.",
	)

	OptLogFile = options.NewString(
		"log.file",
		0,
		getDefaultLogFilePath(),
		"Log file path",
		`Path to log file. Empty value disables logging.`,
	)

	OptLogLevel = NewLogLevelOpt(
		"log.level",
		slog.LevelDebug,
		`Log level, one of: DEBUG, INFO, WARN, ERROR`,
		"Log level, one of: DEBUG, INFO, WARN, ERROR.",
	)
)
View Source
var (
	OptPrintHeader = options.NewBool(
		"header",
		0,
		true,
		"Print header row",
		`Controls whether a header row is printed. This applies only
to certain formats, such as "text" or "csv".`,
		"format",
	)

	OptFormat = NewFormatOpt(
		"format",
		format.Text,
		"Output format",

		`Specify the output format. Some formats are only implemented for a subset of
sq's commands. If the specified format is not available for a particular
command, sq falls back to "text". Available formats:

  text, csv, tsv, xlsx,
  json, jsona, jsonl,
  markdown, html, xlsx, xml, yaml, raw`,
	)

	OptVerbose = options.NewBool(
		"verbose",
		'v',
		false,
		"Print verbose output",
		`Print verbose output.`,
		"format",
	)

	OptMonochrome = options.NewBool(
		"monochrome",
		'M',
		false,
		"Don't print color output",
		`Don't print color output.`,
		"format",
	)

	OptCompact = options.NewBool(
		"compact",
		'c',
		false,
		"Compact instead of pretty-printed output",
		`Compact instead of pretty-printed output.`,
		"format",
	)

	OptTuningFlushThreshold = options.NewInt(
		"tuning.flush-threshold",
		0,
		1000,
		"Output writer buffer flush threshold in bytes",
		`Size in bytes after which output writers should flush any internal buffer.
Generally, it is not necessary to fiddle this knob.`,
	)

	OptDatetimeFormat = options.NewString(
		"format.datetime",
		0,
		"RFC3339",
		"Timestamp format: constant such as RFC3339 or a strftime format",
		`Timestamp format. This can be one of several predefined constants such
as "RFC3339" or "Unix", or a strftime format such as "%Y-%m-%d %H:%M:%S".

`+timeLayoutsList,
	)

	OptDatetimeFormatAsNumber = options.NewBool(
		"format.datetime.number",
		0,
		true,
		"Render numeric datetime value as number instead of string",
		`Render numeric datetime value as number instead of string, if possible.
If format.datetime renders a numeric value (e.g. a Unix timestamp such
as "1591843854"), that value is typically rendered as a string. For some output
formats, such as JSON, it can be useful to instead render the value as a naked
number instead of a string. Note that this option is no-op if the rendered value
is not an integer.

  format.datetime.number=false
  [{"first_name":"PENELOPE","last_update":"1591843854"}]
  format.datetime.number=true
  [{"first_name":"PENELOPE","last_update":1591843854}]
`,
	)

	OptDateFormat = options.NewString(
		"format.date",
		0,
		"DateOnly",
		"Date format: constant such as DateOnly or a strftime format",
		`Date format. This can be one of several predefined constants such
as "DateOnly" or "Unix", or a strftime format such as "%Y-%m-%d".
Note that date values are sometimes programmatically indistinguishable
from datetime values. In that situation, use format.datetime instead.

`+timeLayoutsList,
	)

	OptDateFormatAsNumber = options.NewBool(
		"format.date.number",
		0,
		true,
		"Render numeric date value as number instead of string",
		`Render numeric date value as number instead of string, if possible.
If format.date renders a numeric value (e.g. a year such as "1979"), that value
is typically rendered as a string. For some output formats, such as JSON, it can
be useful to instead render the value as a naked number instead of a string.
Note that this option is no-op if the rendered value is not an integer.

  format.date.number=false
  [{"first_name":"PENELOPE","birth_year":"1979"}]
  format.date.number=true
  [{"first_name":"PENELOPE","birth_year":1979}]
`,
	)

	OptTimeFormat = options.NewString(
		"format.time",
		0,
		"TimeOnly",
		"Time format: constant such as TimeOnly or a strftime format",
		`Time format. This can be one of several predefined constants such
as "TimeOnly" or "Unix", or a strftime format such as "%Y-%m-%d".
Note that time values are sometimes programmatically indistinguishable
from datetime values. In that situation, use format.datetime instead.

`+timeLayoutsList,
	)

	OptTimeFormatAsNumber = options.NewBool(
		"format.time.number",
		0,
		true,
		"Render numeric time value as number instead of string",
		`Render numeric time value as number instead of string, if possible.
If format.time renders a numeric value (e.g. "59"), that value
is typically rendered as a string. For some output formats, such as JSON, it can
be useful to instead render the value as a naked number instead of a string.
Note that this option is no-op if the rendered value is not an integer.

  format.time.number=false
  [{"first_name":"PENELOPE","favorite_minute":"59"}]
  format.time.number=true
  [{"first_name":"PENELOPE","favorite_minute":59}]
`,
	)
)
View Source
var OptPingTimeout = options.NewDuration(
	"ping.timeout",
	0,
	time.Second*10,
	"ping timeout duration",
	"How long to wait before ping timeout occurs. For example: 500ms or 2m10s.",
)

OptPingTimeout controls ping timeout.

View Source
var OptShellCompletionTimeout = options.NewDuration(
	"shell-completion.timeout",
	0,
	time.Millisecond*500,
	"shell completion timeout",
	`How long shell completion should wait before giving up. This can
become relevant when shell completion inspects a source's metadata, e.g. to
offer a list of tables in a source.`,
)

OptShellCompletionTimeout determines how long to wait until for long-running shell completion operations (such as fetching table names from a DB) before giving up.

Functions

func Execute

func Execute(ctx context.Context, stdin *os.File, stdout, stderr io.Writer, args []string) error

Execute builds a RunContext using ctx and default settings, and invokes ExecuteWith.

func ExecuteWith

func ExecuteWith(ctx context.Context, rc *RunContext, args []string) error

ExecuteWith invokes the cobra CLI framework, ultimately resulting in a command being executed. The caller must invoke rc.Close.

func RegisterDefaultOpts added in v0.34.0

func RegisterDefaultOpts(reg *options.Registry)

RegisterDefaultOpts registers the options.Opt instances that the CLI knows about.

func WithRunContext added in v0.15.0

func WithRunContext(ctx context.Context, rc *RunContext) context.Context

WithRunContext returns ctx with rc added as a value.

Types

type FormatOpt added in v0.34.0

type FormatOpt struct {
	options.BaseOpt
	// contains filtered or unexported fields
}

FormatOpt is an options.Opt for format.Format.

func NewFormatOpt added in v0.34.0

func NewFormatOpt(key string, defaultVal format.Format, usage, help string) FormatOpt

NewFormatOpt returns a new FormatOpt instance.

func (FormatOpt) DefaultAny added in v0.34.0

func (op FormatOpt) DefaultAny() any

DefaultAny implements options.Opt.

func (FormatOpt) Get added in v0.34.0

Get returns op's value in o. If o is nil, or no value is set, op's default value is returned.

func (FormatOpt) GetAny added in v0.34.0

func (op FormatOpt) GetAny(o options.Options) any

GetAny implements options.Opt.

func (FormatOpt) Process added in v0.34.0

func (op FormatOpt) Process(o options.Options) (options.Options, error)

Process implements options.Processor. It converts matching string values in o into format.Format. If no match found, the input arg is returned unchanged. Otherwise, a clone is returned.

type LogLevelOpt added in v0.34.0

type LogLevelOpt struct {
	options.BaseOpt
	// contains filtered or unexported fields
}

LogLevelOpt is an options.Opt for slog.Level.

func NewLogLevelOpt added in v0.34.0

func NewLogLevelOpt(key string, defaultVal slog.Level, usage, help string) LogLevelOpt

NewLogLevelOpt returns a new LogLevelOpt instance.

func (LogLevelOpt) DefaultAny added in v0.34.0

func (op LogLevelOpt) DefaultAny() any

DefaultAny implements options.Opt.

func (LogLevelOpt) Get added in v0.34.0

func (op LogLevelOpt) Get(o options.Options) slog.Level

Get returns op's value in o. If o is nil, or no value is set, op's default value is returned.

func (LogLevelOpt) GetAny added in v0.34.0

func (op LogLevelOpt) GetAny(o options.Options) any

GetAny implements options.Opt.

func (LogLevelOpt) Process added in v0.34.0

func (op LogLevelOpt) Process(o options.Options) (options.Options, error)

Process implements options.Processor. It converts matching string values in o into slog.Level. If no match found, the input arg is returned unchanged. Otherwise, a clone is returned.

type RunContext

type RunContext struct {
	// Stdin typically is os.Stdin, but can be changed for testing.
	Stdin *os.File

	// Out is the output destination.
	// If nil, default to stdout.
	Out io.Writer

	// ErrOut is the error output destination.
	// If nil, default to stderr.
	ErrOut io.Writer

	// Cmd is the command instance provided by cobra for
	// the currently executing command. This field will
	// be set before the command's runFunc is invoked.
	Cmd *cobra.Command

	// Args is the arg slice supplied by cobra for
	// the currently executing command. This field will
	// be set before the command's runFunc is invoked.
	Args []string

	// Config is the run's config.
	Config *config.Config

	// ConfigStore is run's config store.
	ConfigStore config.Store

	OptionsRegistry *options.Registry
	// contains filtered or unexported fields
}

RunContext is a container for injectable resources passed to all execX funcs. The Close method should be invoked when the RunContext is no longer needed.

func RunContextFrom added in v0.15.0

func RunContextFrom(ctx context.Context) *RunContext

RunContextFrom extracts the RunContext added to ctx via WithRunContext.

func (*RunContext) Close

func (rc *RunContext) Close() error

Close should be invoked to dispose of any open resources held by rc. If an error occurs during Close and rc.Log is not nil, that error is logged at WARN level before being returned.

Directories

Path Synopsis
Package buildinfo hosts build info variables populated via ldflags.
Package buildinfo hosts build info variables populated via ldflags.
Package config holds CLI configuration.
Package config holds CLI configuration.
yamlstore
Package yamlstore contains an implementation of config.Store that uses YAML files for persistence.
Package yamlstore contains an implementation of config.Store that uses YAML files for persistence.
yamlstore/upgrades/v0.34.0
Package v0_34_0 upgrades YAML config to v0.34.0.
Package v0_34_0 upgrades YAML config to v0.34.0.
Package flag holds CLI flags.
Package flag holds CLI flags.
Package output provides interfaces and implementations for outputting data and messages.
Package output provides interfaces and implementations for outputting data and messages.
csvw
Package csvw implements writers for CSV.
Package csvw implements writers for CSV.
htmlw
Package htmlw implements a RecordWriter for HTML.
Package htmlw implements a RecordWriter for HTML.
jsonw
Package jsonw implements output writers for JSON.
Package jsonw implements output writers for JSON.
markdownw
Package markdownw implements writers for Markdown.
Package markdownw implements writers for Markdown.
outputx
Package outputx contains extensions to pkg output, and helpers for implementing output writers.
Package outputx contains extensions to pkg output, and helpers for implementing output writers.
tablew
Package tablew implements text table output writers.
Package tablew implements text table output writers.
tablew/internal
Package tablewriter creates & generates text based table
Package tablewriter creates & generates text based table
xlsxw
Package xlsxw implements output writers for Microsoft Excel.
Package xlsxw implements output writers for Microsoft Excel.
xmlw
Package xmlw implements output writers for XML.
Package xmlw implements output writers for XML.
yamlw
Package yamlw implements output writers for YAML.
Package yamlw implements output writers for YAML.

Jump to

Keyboard shortcuts

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