shared

package
v0.9.2 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AtomicWrite added in v0.4.8

func AtomicWrite(path string, data []byte, mode os.FileMode) error

AtomicWrite writes data to path atomically using a temp-file-then-rename pattern. This prevents corruption if the process crashes during the write.

func BuildConfirmDeleteCommand added in v0.4.8

func BuildConfirmDeleteCommand(cfg ConfirmDeleteCommandConfig) *ffcli.Command

BuildConfirmDeleteCommand creates a standard delete command requiring --confirm.

func BuildPaginatedListCommand added in v0.4.8

func BuildPaginatedListCommand(cfg PaginatedListCommandConfig) *ffcli.Command

BuildPaginatedListCommand creates a standard list command with --page-size, --paginate, --next, --output, and --pretty flags.

func ContextWithClock added in v0.9.0

func ContextWithClock(ctx context.Context, clock Clock) context.Context

ContextWithClock installs a command-scoped clock.

func ContextWithDryRun added in v0.4.2

func ContextWithDryRun(ctx context.Context, dryRun bool) context.Context

ContextWithDryRun returns a context with the dry-run flag set.

func ContextWithFilesystem added in v0.9.0

func ContextWithFilesystem(ctx context.Context, filesystem Filesystem) context.Context

ContextWithFilesystem installs a command-scoped durable file boundary.

func ContextWithIO added in v0.9.0

func ContextWithIO(ctx context.Context, stdout, stderr io.Writer) context.Context

ContextWithIO installs command-scoped output streams.

func ContextWithTimeout

func ContextWithTimeout(ctx context.Context, cfg *config.Config) (context.Context, context.CancelFunc)

ContextWithTimeout applies request timeouts.

func ContextWithUploadTimeout

func ContextWithUploadTimeout(ctx context.Context, cfg *config.Config) (context.Context, context.CancelFunc)

ContextWithUploadTimeout applies upload timeouts.

func DefaultUsageFunc

func DefaultUsageFunc(cmd *ffcli.Command) string

DefaultUsageFunc renders help output for any command with formatted sections.

func DeprecatedAliasLeafCommand added in v0.4.8

func DeprecatedAliasLeafCommand(original *ffcli.Command, oldName, newCommandPath string) *ffcli.Command

DeprecatedAliasLeafCommand creates a deprecated alias that wraps an existing command. When invoked, it prints a deprecation warning to stderr then runs the original command. The alias is hidden from parent help via the "DEPRECATED:" prefix in ShortHelp.

func DeriveUpdateMask added in v0.4.9

func DeriveUpdateMask(raw []byte, mutableFields []string) (string, error)

DeriveUpdateMask extracts top-level keys from raw JSON and returns a sorted, comma-separated update mask containing only keys that appear in mutableFields.

We use an allowlist rather than a blocklist because the CLI unmarshals JSON into typed SDK structs before sending. The SDK drops unknown fields during unmarshal, so including an unknown key in the mask would create a mismatch (mask names a field the body doesn't contain) and cause a guaranteed 400.

func FormatUnknownCommand added in v0.4.2

func FormatUnknownCommand(input string, commands []string) string

FormatUnknownCommand returns an error message with an optional suggestion.

func IsDryRun added in v0.4.2

func IsDryRun(ctx context.Context) bool

IsDryRun returns true if the context has dry-run enabled.

func IsReportedError

func IsReportedError(err error) bool

IsReportedError returns true if err is a ReportedError.

func LevenshteinDistance added in v0.4.2

func LevenshteinDistance(a, b string) int

LevenshteinDistance computes the edit distance between two strings.

func LoadJSONArg

func LoadJSONArg(value string, out interface{}) error

LoadJSONArg parses JSON from a literal string or @file path.

func LoadJSONArgRaw added in v0.4.9

func LoadJSONArgRaw(value string) ([]byte, error)

LoadJSONArgRaw returns the raw JSON bytes from a literal string or @file path without unmarshaling. Use this when you need to inspect the JSON keys before parsing into a typed struct.

func NewActionableError

func NewActionableError(op string, cause error, hint string) error

NewActionableError builds an ActionableError.

func NewAuthError

func NewAuthError(op string, cause error, hint string) error

NewAuthError builds an AuthError.

func NewNotFoundError

func NewNotFoundError(op string, cause error, hint string) error

NewNotFoundError builds a NotFoundError.

func NewPermissionError

func NewPermissionError(op string, cause error, hint string) error

NewPermissionError builds a PermissionError.

func NewReportedError

func NewReportedError(err error) error

NewReportedError wraps err as ReportedError.

func NewValidationError

func NewValidationError(op string, cause error, hint string) error

NewValidationError builds a ValidationError.

func Now added in v0.9.0

func Now(ctx context.Context) time.Time

Now reads the command-scoped clock or the production wall clock.

func ParseTimeouts

func ParseTimeouts(cfg *config.Config) (time.Duration, time.Duration)

func PrintOutput

func PrintOutput(data interface{}, format string, pretty bool) error

PrintOutput renders output in the requested format.

func PrintOutputContext added in v0.9.0

func PrintOutputContext(ctx context.Context, data interface{}, format string, pretty bool) error

PrintOutputContext renders output to the command-scoped stdout stream.

func RegisterCIFlags added in v0.4.4

func RegisterCIFlags(fs *flag.FlagSet, cf *CIFlags)

RegisterCIFlags adds --report and --report-file flags to a flag set.

func RequireFlags

func RequireFlags(flagSet *flag.FlagSet, required ...string) error

RequireFlags ensures the required flags are provided.

func RequirePackageName added in v0.4.8

func RequirePackageName(flagValue string, cfg *config.Config) (string, error)

RequirePackageName resolves the package name and returns an error if not found.

func ResolveOutputFormat added in v0.4.2

func ResolveOutputFormat(flagValue string, flagDefault string) string

ResolveOutputFormat returns the output format to use based on flag and env var. If flagValue is non-empty and not the default, it takes precedence. Otherwise falls back to GPLAY_DEFAULT_OUTPUT, then "json".

func ResolvePackageName

func ResolvePackageName(flagValue string, cfg *config.Config) string

ResolvePackageName returns a package name from flags/env/config.

func ResolveProfileName

func ResolveProfileName(cfg *config.Config) string

ResolveProfileName returns the selected profile name.

func SplitCSV added in v0.4.8

func SplitCSV(s string) []string

SplitCSV splits a comma-separated string, trims whitespace from each element, and removes empty strings.

func SplitUniqueCSV added in v0.4.8

func SplitUniqueCSV(s string) []string

SplitUniqueCSV splits a comma-separated string, trims whitespace, removes empties, and deduplicates (preserving first occurrence order).

func Stderr added in v0.9.0

func Stderr(ctx context.Context) io.Writer

Stderr returns the command-scoped standard error stream.

func Stdout added in v0.9.0

func Stdout(ctx context.Context) io.Writer

Stdout returns the command-scoped standard output stream.

func StrictAuthEnabled

func StrictAuthEnabled() bool

func SuggestCommand added in v0.4.2

func SuggestCommand(input string, commands []string, maxDistance int) string

SuggestCommand finds the closest command name within maxDistance.

func UsageError added in v0.4.8

func UsageError(msg string) error

UsageError returns a structured usage error. This is the standard way to report missing/invalid flags. It results in exit code 2 (usage error) when structured exit codes are wired.

func UsageErrorf added in v0.4.8

func UsageErrorf(format string, args ...any) error

UsageErrorf is like UsageError but with fmt.Sprintf formatting.

func ValidateCIFlags added in v0.4.4

func ValidateCIFlags(cf *CIFlags) error

ValidateCIFlags checks that the flag values are valid.

func ValidateOutputFlags

func ValidateOutputFlags(output string, pretty bool) error

ValidateOutputFlags enforces output/pretty compatibility.

func VisibleUsageFunc added in v0.4.8

func VisibleUsageFunc(cmd *ffcli.Command) string

VisibleUsageFunc renders help for a command, hiding deprecated subcommands. A subcommand is considered deprecated if its ShortHelp starts with "DEPRECATED:".

func WithSpinner added in v0.4.4

func WithSpinner(label string, fn func() error) error

WithSpinner wraps fn with a braille spinner on stderr. If fn is nil, it returns nil immediately. If fn returns an error, WithSpinner returns it. If fn panics, the spinner stops and the panic is re-raised.

func WithSpinnerDelayed added in v0.4.4

func WithSpinnerDelayed(label string, delay time.Duration, fn func() error) error

WithSpinnerDelayed wraps fn with a spinner that only appears after delay. Useful for operations that may complete quickly — no visual noise for fast calls.

func WrapActionable

func WrapActionable(err error, op, hint string) error

WrapActionable wraps err with context and an optional hint.

func WrapCommandOutputValidation added in v0.4.8

func WrapCommandOutputValidation(cmd *ffcli.Command)

WrapCommandOutputValidation recursively wraps all commands' Exec functions to validate output format flags before execution. This prevents API calls when invalid output flags are passed.

func WrapGoogleAPIError

func WrapGoogleAPIError(op string, err error) error

WrapGoogleAPIError adds contextual hints for common Google API failures.

func WriteJUnitReport added in v0.4.4

func WriteJUnitReport(suites *JUnitTestSuites, filePath string) error

WriteJUnitReport writes JUnit XML to the specified file.

Types

type ActionableError

type ActionableError struct {
	Op    string
	Cause error
	Hint  string
}

ActionableError adds context and an optional hint to an error.

func (*ActionableError) Error

func (e *ActionableError) Error() string

func (*ActionableError) Unwrap

func (e *ActionableError) Unwrap() error

type AuthError

type AuthError struct{ ActionableError }

AuthError represents authentication failures.

type CIFlags added in v0.4.4

type CIFlags struct {
	Report     string // "junit" or empty
	ReportFile string // output file path (default: "results.xml")
}

CIFlags holds CI report configuration.

type Clock added in v0.9.0

type Clock interface {
	Now() time.Time
}

Clock is the runtime time source used by commands that create or validate durable artifacts.

type ClockFunc added in v0.9.0

type ClockFunc func() time.Time

ClockFunc adapts a function into a Clock.

func (ClockFunc) Now added in v0.9.0

func (f ClockFunc) Now() time.Time

Now implements Clock.

type CommandUsageError added in v0.9.0

type CommandUsageError struct {
	Message string
}

CommandUsageError carries a user-facing usage failure while preserving flag.ErrHelp semantics so ffcli renders the selected command's help.

func (*CommandUsageError) Error added in v0.9.0

func (e *CommandUsageError) Error() string

func (*CommandUsageError) Unwrap added in v0.9.0

func (e *CommandUsageError) Unwrap() error

type ConfirmDeleteCommandConfig added in v0.4.8

type ConfirmDeleteCommandConfig struct {
	Name       string
	ShortUsage string
	ShortHelp  string
	LongHelp   string
	// ExtraFlags registers additional command-specific flags.
	ExtraFlags func(fs *flag.FlagSet)
	// Exec is called only if --confirm is true.
	Exec func(ctx context.Context) error
}

ConfirmDeleteCommandConfig configures a standard delete command with --confirm.

type DryRunTransport added in v0.4.2

type DryRunTransport struct {
	Base   http.RoundTripper
	Writer io.Writer // output destination (typically os.Stderr)
}

DryRunTransport wraps an http.RoundTripper and intercepts write requests when dry-run mode is active. GET/HEAD requests pass through normally. Write requests (POST, PUT, PATCH, DELETE) are logged to stderr and return a synthetic 200 OK response without making any actual API call.

func (*DryRunTransport) RoundTrip added in v0.4.2

func (t *DryRunTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type Filesystem added in v0.9.0

type Filesystem interface {
	ReadFile(path string) ([]byte, error)
	AtomicWriteFile(path string, data []byte, fileMode, dirMode os.FileMode) error
	CreateExclusiveFile(path string, data []byte, fileMode, dirMode os.FileMode) error
}

Filesystem is the durable file boundary carried by the CLI runtime.

func FilesystemFrom added in v0.9.0

func FilesystemFrom(ctx context.Context) Filesystem

FilesystemFrom returns the command-scoped filesystem or the rooted production implementation.

type JUnitFailure added in v0.4.4

type JUnitFailure struct {
	Message string `xml:"message,attr"`
	Type    string `xml:"type,attr"`
	Body    string `xml:",chardata"`
}

JUnitFailure represents a test failure.

type JUnitTestCase added in v0.4.4

type JUnitTestCase struct {
	XMLName   xml.Name      `xml:"testcase"`
	Name      string        `xml:"name,attr"`
	ClassName string        `xml:"classname,attr"`
	Time      float64       `xml:"time,attr"`
	Failure   *JUnitFailure `xml:"failure,omitempty"`
}

JUnitTestCase represents a single test case.

type JUnitTestSuite added in v0.4.4

type JUnitTestSuite struct {
	XMLName  xml.Name        `xml:"testsuite"`
	Name     string          `xml:"name,attr"`
	Tests    int             `xml:"tests,attr"`
	Failures int             `xml:"failures,attr"`
	Errors   int             `xml:"errors,attr"`
	Time     float64         `xml:"time,attr"`
	Cases    []JUnitTestCase `xml:"testcase"`
}

JUnitTestSuite represents a single test suite.

type JUnitTestSuites added in v0.4.4

type JUnitTestSuites struct {
	XMLName xml.Name         `xml:"testsuites"`
	Suites  []JUnitTestSuite `xml:"testsuite"`
}

JUnitTestSuites is the top-level XML element.

func NewJUnitFromValidation added in v0.4.4

func NewJUnitFromValidation(validationName string, errors []string, warnings []string, durationSecs float64) *JUnitTestSuites

NewJUnitFromValidation converts validation results into JUnit format. validationName is the suite name (e.g., "bundle", "listing", "screenshots"). errors are test failures, warnings are passed-with-warnings.

type NotFoundError

type NotFoundError struct{ ActionableError }

NotFoundError represents missing resources.

type OptionalBool added in v0.4.4

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

OptionalBool is a tri-state boolean: unset, true, or false. It implements flag.Value and reports IsBoolFlag() = true so --flag (without value) sets it to true.

func (*OptionalBool) IsBoolFlag added in v0.4.4

func (o *OptionalBool) IsBoolFlag() bool

IsBoolFlag tells the flag package this can be used without "=value".

func (*OptionalBool) IsSet added in v0.4.4

func (o *OptionalBool) IsSet() bool

IsSet reports whether the flag was explicitly set.

func (*OptionalBool) Set added in v0.4.4

func (o *OptionalBool) Set(s string) error

Set implements flag.Value. Accepts: true, false, 1, 0, yes, no (case-insensitive).

func (*OptionalBool) String added in v0.4.4

func (o *OptionalBool) String() string

String implements flag.Value.

func (*OptionalBool) Value added in v0.4.4

func (o *OptionalBool) Value() bool

Value returns the boolean value (only meaningful when IsSet is true).

type OutputFlags added in v0.4.8

type OutputFlags struct {
	Output *string
	Pretty *bool
}

OutputFlags holds the parsed output format flags.

func BindOutputFlags added in v0.4.8

func BindOutputFlags(fs *flag.FlagSet) *OutputFlags

BindOutputFlags registers --output and --pretty flags on the given FlagSet. The default for --output is TTY-aware: "table" if stdout is a terminal, "json" otherwise. The GPLAY_DEFAULT_OUTPUT env var overrides the default.

func (*OutputFlags) Format added in v0.4.8

func (o *OutputFlags) Format() string

Format returns the resolved output format string.

func (*OutputFlags) IsPretty added in v0.4.8

func (o *OutputFlags) IsPretty() bool

IsPretty returns whether pretty-printing is enabled.

type PaginatedListCommandConfig added in v0.4.8

type PaginatedListCommandConfig struct {
	Name       string
	ShortUsage string
	ShortHelp  string
	LongHelp   string
	// ExtraFlags registers additional command-specific flags.
	ExtraFlags func(fs *flag.FlagSet)
	// Exec is called with the parsed pagination and output settings.
	Exec func(ctx context.Context, pageSize int, pageToken string, paginate bool, output *OutputFlags) error
}

PaginatedListCommandConfig configures a standard paginated list command.

type PermissionError

type PermissionError struct{ ActionableError }

PermissionError represents permission/authorization failures.

type ProgressReader added in v0.4.2

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

ProgressReader wraps an io.Reader and reports progress to stderr.

func NewProgressReader added in v0.4.2

func NewProgressReader(r io.Reader, total int64, filename string) *ProgressReader

NewProgressReader creates a progress-reporting reader. If stderr is not a TTY, output is disabled. total can be 0 if unknown.

func (*ProgressReader) Read added in v0.4.2

func (pr *ProgressReader) Read(p []byte) (int, error)

type ReportedError

type ReportedError struct{ Err error }

ReportedError wraps errors that already have user-facing output.

func (ReportedError) Error

func (r ReportedError) Error() string

func (ReportedError) Unwrap

func (r ReportedError) Unwrap() error

type RootFlags added in v0.4.8

type RootFlags struct {
	Profile    *string
	Debug      *bool
	DryRun     *bool
	Report     *string
	ReportFile *string
}

RootFlags holds the parsed root-level flags.

func BindRootFlags added in v0.4.8

func BindRootFlags(fs *flag.FlagSet) *RootFlags

BindRootFlags registers root-level flags on the given FlagSet.

func (*RootFlags) Apply added in v0.4.8

func (rf *RootFlags) Apply()

Apply sets environment variables based on parsed root flags. Call this after root.Parse() and before root.Run().

func (*RootFlags) ValidateReportFlags added in v0.4.8

func (rf *RootFlags) ValidateReportFlags() error

ValidateReportFlags checks that --report and --report-file are used together.

type ValidationError

type ValidationError struct{ ActionableError }

ValidationError represents malformed requests or invalid inputs.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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