flags

package
v1.202.1 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2025 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetActualArgs

func GetActualArgs(cmd *cobra.Command, osArgs []string) []string

GetActualArgs extracts the actual arguments when DisableFlagParsing=true. When DisableFlagParsing=true, cmd.Flags().Args() returns empty because Cobra doesn't parse flags. This function falls back to os.Args to get the raw arguments.

This logic is extracted here to be testable and reusable, rather than duplicated in UsageFunc handlers.

Returns the arguments slice that should be used for Args validation.

func GetBool

func GetBool(m map[string]interface{}, key string) bool

GetBool extracts a boolean value from the parsed flags map.

func GetIdentitySelector

func GetIdentitySelector(m map[string]interface{}, key string) global.IdentitySelector

GetIdentitySelector extracts an IdentitySelector value from the parsed flags map.

func GetInt

func GetInt(m map[string]interface{}, key string) int

GetInt extracts an integer value from the parsed flags map.

func GetPagerSelector

func GetPagerSelector(m map[string]interface{}, key string) global.PagerSelector

GetPagerSelector extracts a PagerSelector value from the parsed flags map.

func GetString

func GetString(m map[string]interface{}, key string) string

GetString extracts a string value from the parsed flags map.

func GetStringSlice

func GetStringSlice(m map[string]interface{}, key string) []string

GetStringSlice extracts a string slice value from the parsed flags map.

func NormalizeShorthandWithEquals

func NormalizeShorthandWithEquals(cmd *cobra.Command, arg string) (normalized string, wasNormalized bool)

NormalizeShorthandWithEquals normalizes shorthand flags with = syntax to longhand format. This fixes a Cobra quirk where -i=value works but -i= returns literal "=" instead of empty string.

Examples:

  • -i=value → --identity=value
  • -i= → --identity=
  • -s=dev → --stack=dev

This ensures consistent behavior: -i=value behaves the same as --identity=value.

Returns:

  • normalized: The normalized flag (e.g., "--identity=value")
  • wasNormalized: True if normalization occurred, false otherwise

func ParseGlobalFlags

func ParseGlobalFlags(cmd *cobra.Command, v *viper.Viper) global.Flags

ParseGlobalFlags extracts all global flags from Viper with proper precedence. This should be called by parsers to populate the Flags struct in interpreters.

Precedence order (handled automatically by Viper):

  1. CLI flag value
  2. Environment variable
  3. Config file value
  4. Flag default
  5. Go zero value

Special handling:

  • identity and pager flags use NoOptDefVal pattern (require cmd.Flags().Changed check)
  • All other flags use standard Viper resolution

func PromptForMissingRequired added in v1.202.0

func PromptForMissingRequired(flagName, promptTitle string, completionFunc CompletionFunc, cmd *cobra.Command, args []string) (string, error)

PromptForMissingRequired prompts for a required flag that is missing. This is Use Case 1: Missing Required Flags.

Example:

$ atmos describe component vpc
? Choose a stack
  ue2-dev
> ue2-prod

func PromptForOptionalValue added in v1.202.0

func PromptForOptionalValue(ctx *OptionalValuePromptContext) (string, error)

PromptForOptionalValue prompts for a flag that was used without a value. This is Use Case 2: Optional Value Flags (like the --identity pattern).

The flag must have NoOptDefVal set to cfg.IdentityFlagSelectValue ("__SELECT__"). When user provides --flag without value, Cobra sets it to the sentinel value, and we detect this to show the prompt.

Example:

$ atmos list stacks --format
? Choose output format
  yaml
> json
  table

func PromptForPositionalArg added in v1.202.0

func PromptForPositionalArg(argName, promptTitle string, completionFunc CompletionFunc, cmd *cobra.Command, currentArgs []string) (string, error)

PromptForPositionalArg prompts for a required positional argument that is missing. This is Use Case 3: Missing Required Positional Arguments.

Example:

$ atmos theme show
? Choose a theme to preview
  Dracula
  Tokyo Night
> Nord

func PromptForValue added in v1.202.0

func PromptForValue(name, title string, options []string) (string, error)

PromptForValue shows an interactive Huh selector with the given options. Returns the selected value or an error.

This is the core prompting function used by all three use cases: 1. Missing required flags. 2. Optional value flags (sentinel pattern). 3. Missing required positional arguments.

func ResetCommandFlags

func ResetCommandFlags(cmd *cobra.Command)

ResetCommandFlags resets all flags on a cobra.Command to their default values. This is a shared helper used by all FlagParser implementations to prevent flag pollution between test runs.

It resets:

  • Local flags (cmd.Flags())
  • Persistent flags (cmd.PersistentFlags())

For each flag, it:

  1. Sets the value back to DefValue
  2. Clears the Changed state

func ValidateArgsOrNil

func ValidateArgsOrNil(cmd *cobra.Command, args []string) error

ValidateArgsOrNil checks if the command's Args validator accepts the given arguments. Returns nil if validation passes, or the validation error if it fails.

This is used to distinguish between:

  • Valid positional arguments (return nil, show usage without "Unknown command" error)
  • Invalid arguments/unknown subcommands (return error, show "Unknown command" error)

This logic is extracted here to be testable and avoid duplication in UsageFunc handlers.

Types

type AtmosFlagParser

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

AtmosFlagParser is a unified parser that combines compatibility flag translation with standard Cobra flag parsing.

Key features:

  • Translates legacy flag syntax to Cobra-compatible format via compat.CompatibilityFlagTranslator.
  • Enables Cobra validation (no DisableFlagParsing).
  • Separates Atmos flags from separated args (for external tools).
  • Handles double-dash separator (--) for explicit separation.
  • Preprocesses NoOptDefVal flags to support space-separated syntax.

func NewAtmosFlagParser

func NewAtmosFlagParser(cmd *cobra.Command, v *viper.Viper, translator *compat.CompatibilityFlagTranslator, registry *FlagRegistry) *AtmosFlagParser

NewAtmosFlagParser creates a new unified parser.

func (*AtmosFlagParser) Parse

func (p *AtmosFlagParser) Parse(args []string) (*ParsedConfig, error)

Parse processes command-line arguments and returns parsed configuration.

Process:

  1. Set command on translator (enables shorthand normalization)
  2. Validate no conflicts between compatibility flags and Cobra native shorthands
  3. Split args at -- separator (if present)
  4. Validate compatibility flag targets for aliases used in args
  5. Translate compatibility flags + normalize Cobra shorthands in pre-separator args
  6. Let Cobra parse the normalized Atmos args
  7. Bind parsed flags to Viper
  8. Collect separated args (post-separator + translated pass-through flags)
  9. Handle NoOptDefVal resolution for empty flag values

Example:

Input:  ["plan", "vpc", "-s", "dev", "-i=prod", "-var", "x=1", "--", "-var-file", "prod.tfvars"]
Step 3: argsBeforeSep=["plan", "vpc", "-s", "dev", "-i=prod", "-var", "x=1"], argsAfterSep=["-var-file", "prod.tfvars"]
Step 5: atmosArgs=["plan", "vpc", "-s", "dev", "--identity=prod"], separatedArgs=["-var", "x=1"]
        (-i=prod normalized to --identity=prod, -var moved to separated args)
Step 6: Cobra parses ["plan", "vpc", "-s", "dev", "--identity=prod"] (Cobra handles -s → --stack natively)
Result: Flags{stack="dev", identity="prod"}, Positional=["plan", "vpc"], SeparatedArgs=["-var", "x=1", "-var-file", "prod.tfvars"]

func (*AtmosFlagParser) Reset

func (p *AtmosFlagParser) Reset()

Reset clears any internal parser state to prevent pollution between test runs. This resets the command's flag state to prevent flag values from one test polluting subsequent tests when using a global parser instance.

type BaseOptions

type BaseOptions struct {
	global.Flags // Embedded global flags.
	// contains filtered or unexported fields
}

BaseOptions provides common implementation for CommandOptions interface. Command-specific interpreters should embed this (or just embed global.Flags directly).

func NewBaseOptions

func NewBaseOptions(globalFlags *global.Flags, positionalArgs, passThroughArgs []string) BaseOptions

NewBaseOptions creates a new BaseOptions with the given arguments.

func (*BaseOptions) GetPositionalArgs

func (b *BaseOptions) GetPositionalArgs() []string

GetPositionalArgs implements CommandOptions.

func (*BaseOptions) GetSeparatedArgs

func (b *BaseOptions) GetSeparatedArgs() []string

GetSeparatedArgs implements CommandOptions.

type BoolFlag

type BoolFlag struct {
	Name        string
	Shorthand   string
	Default     bool
	Description string
	EnvVars     []string
}

BoolFlag represents a boolean-valued flag.

func (*BoolFlag) GetCompletionFunc added in v1.202.0

func (f *BoolFlag) GetCompletionFunc() func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective)

GetCompletionFunc implements Flag.

func (*BoolFlag) GetDefault

func (f *BoolFlag) GetDefault() interface{}

GetDefault implements Flag.

func (*BoolFlag) GetDescription

func (f *BoolFlag) GetDescription() string

GetDescription implements Flag.

func (*BoolFlag) GetEnvVars

func (f *BoolFlag) GetEnvVars() []string

GetEnvVars implements Flag.

func (*BoolFlag) GetName

func (f *BoolFlag) GetName() string

GetName implements Flag.

func (*BoolFlag) GetNoOptDefVal

func (f *BoolFlag) GetNoOptDefVal() string

GetNoOptDefVal implements Flag.

func (*BoolFlag) GetShorthand

func (f *BoolFlag) GetShorthand() string

GetShorthand implements Flag.

func (*BoolFlag) IsRequired

func (f *BoolFlag) IsRequired() bool

IsRequired implements Flag.

type Builder

type Builder interface {
	// RegisterFlags registers flags with a Cobra command.
	// This attaches flags to the command so Cobra can parse them.
	RegisterFlags(cmd *cobra.Command)

	// BindToViper binds flags to a Viper instance for precedence.
	// This enables CLI > ENV > config > default resolution.
	// Returns error if binding fails.
	BindToViper(v *viper.Viper) error
}

Builder is the interface for flag configuration builders.

This interface is implemented by:

  • StandardParser: Simple commands with direct flag registration
  • FlagRegistry: Per-subcommand flag registration (terraform, helmfile, packer)

Commands implementing CommandProvider.GetFlagsBuilder() return a Builder to enable standardized flag registration across all commands.

Example usage:

// Simple command (version, list, etc.)
func (v *VersionCommandProvider) GetFlagsBuilder() Builder {
    return NewStandardParser(
        WithBoolFlag("check", "c", false, "Run additional checks"),
    )
}

// Per-subcommand (terraform plan)
func (t *TerraformPlanCommandProvider) GetFlagsBuilder() Builder {
    return TerraformPlanFlags()  // Returns *FlagRegistry
}

// No flags (about)
func (a *AboutCommandProvider) GetFlagsBuilder() Builder {
    return nil
}

type CommandOptions

type CommandOptions interface {
	// GetGlobalFlags returns the global flags available to all commands.
	GetGlobalFlags() *global.Flags

	// GetPositionalArgs returns positional arguments (e.g., component name, subcommand).
	GetPositionalArgs() []string

	// GetSeparatedArgs returns arguments to pass to underlying tools (Terraform, Helmfile, etc.).
	GetSeparatedArgs() []string
}

CommandOptions is the base interface all strongly-typed interpreters implement. Each command type (Terraform, Helmfile, Auth, etc.) has its own interpreter struct that embeds GlobalFlags and provides command-specific fields.

This enables strongly-typed access to flags instead of weak map-based access:

// ❌ Weak typing (old way with map access)
stack := atmosFlags["stack"].(string)  // runtime type assertion, can panic

// ✅ Strong typing (new way with interpreter)
stack := interpreter.Stack  // compile-time type safety

type CompletionFunc added in v1.202.0

type CompletionFunc func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompletionFunc is a type alias for Cobra's ValidArgsFunction. This function provides completion values for flags and positional arguments. It's used both for shell completion and for interactive prompts.

Parameters:

  • cmd: The cobra command being completed.
  • args: Positional arguments provided so far.
  • toComplete: Partial string being completed.

Returns:

  • []string: List of completion options.
  • cobra.ShellCompDirective: Directive for shell completion behavior.

type Flag

type Flag interface {
	// GetName returns the long flag name (without -- prefix).
	GetName() string

	// GetShorthand returns the short flag name (single character, without - prefix).
	// Returns empty string if no shorthand.
	GetShorthand() string

	// GetDescription returns the help text for this flag.
	GetDescription() string

	// GetDefault returns the default value for this flag.
	GetDefault() interface{}

	// IsRequired returns true if this flag is required.
	IsRequired() bool

	// GetNoOptDefVal returns the value to use when flag is provided without a value.
	// Returns empty string if NoOptDefVal is not supported for this flag type.
	// This is used for the identity pattern: --identity (alone) vs --identity value.
	GetNoOptDefVal() string

	// GetEnvVars returns the list of environment variable names to bind to this flag.
	// Returns nil if no env vars.
	GetEnvVars() []string

	// GetCompletionFunc returns the custom completion function for this flag.
	// Returns nil if no custom completion is configured.
	// Custom completions enable dynamic shell completion based on codebase state.
	GetCompletionFunc() func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective)
}

Flag represents a command-line flag configuration. This is used by FlagRegistry to store reusable flag definitions.

type FlagParser

type FlagParser interface {
	// RegisterFlags adds flags to the Cobra command.
	// This should be called during command initialization before the command is added to root.
	RegisterFlags(cmd *cobra.Command)

	// BindToViper binds registered flags to Viper for automatic precedence handling.
	// Must be called after RegisterFlags and before command execution.
	// Handles both flag binding (BindPFlag) and environment variable binding (BindEnv).
	//
	// Special handling for NoOptDefVal flags:
	//   - Only bind env vars, NOT the flag itself
	//   - This prevents Viper from interfering with NoOptDefVal detection
	BindToViper(v *viper.Viper) error

	// Parse processes command-line arguments and returns parsed configuration.
	// For standard commands, this extracts flag values from Viper.
	// For pass-through commands, this separates Atmos flags from tool flags.
	//
	// Returns ParsedConfig containing:
	//   - Atmos flags and their values
	//   - Pass-through arguments (for terraform/helmfile/etc)
	//   - Component and stack information
	Parse(ctx context.Context, args []string) (*ParsedConfig, error)

	// Reset clears any internal parser state to prevent pollution between test runs.
	// This should be called between tests when reusing a global parser instance.
	// For production code, parsers are typically created once and don't need resetting.
	Reset()
}

FlagParser handles flag registration, parsing, and Viper binding for commands.

This interface provides a unified way to handle command-line flags across all Atmos commands, ensuring consistent precedence order (flags > env vars > config > defaults), proper Viper integration, and support for advanced patterns like NoOptDefVal.

Usage:

parser := flags.NewStandardFlagParser(
    flags.WithStringFlag("stack", "s", "", "Stack name"),
    flags.WithBoolFlag("dry-run", "", false, "Dry run mode"),
)

// In command setup:
parser.RegisterFlags(cmd)
parser.BindToViper(viper.GetViper())

// In command execution:
cfg, err := parser.Parse(ctx, args)

type FlagRegistry

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

FlagRegistry stores reusable flag definitions. This allows common flags (stack, identity, dry-run) to be defined once and reused across multiple commands.

func CommonFlags

func CommonFlags() *FlagRegistry

CommonFlags returns a registry pre-populated with common Atmos flags. This includes:

  • All global flags from GlobalFlagsRegistry() (logs-level, chdir, base-path, identity, etc.)
  • stack (-s): Stack name
  • dry-run: Dry run mode

Note: identity is already in GlobalFlagsRegistry(), so it's not duplicated here.

Usage:

registry := flags.CommonFlags()
// Add command-specific flags
registry.Register(&flags.StringFlag{Name: "format", ...})

func GlobalFlagsRegistry

func GlobalFlagsRegistry() *FlagRegistry

GlobalFlagsRegistry returns a FlagRegistry with all global flags pre-configured. This can be used to register global flags on commands that don't inherit from RootCmd.

func HelmfileFlags

func HelmfileFlags() *FlagRegistry

HelmfileFlags returns a registry with flags specific to Helmfile commands.

func NewFlagRegistry

func NewFlagRegistry() *FlagRegistry

NewFlagRegistry creates a new flag registry.

func PackerFlags

func PackerFlags() *FlagRegistry

PackerFlags returns a registry with flags specific to Packer commands.

func (*FlagRegistry) All

func (r *FlagRegistry) All() []Flag

All returns all registered flags. The returned slice is a copy and safe to modify.

func (*FlagRegistry) BindToViper

func (r *FlagRegistry) BindToViper(v *viper.Viper) error

BindToViper binds all flags in this registry to a Viper instance. This is part of the Builder interface.

Binding enables flag precedence: CLI > ENV > config > default. Each flag is bound to its environment variables if specified.

func (*FlagRegistry) Count

func (r *FlagRegistry) Count() int

Count returns the number of registered flags.

func (*FlagRegistry) Get

func (r *FlagRegistry) Get(name string) Flag

Get retrieves a flag by name. Returns nil if flag not found.

func (*FlagRegistry) Has

func (r *FlagRegistry) Has(name string) bool

Has returns true if the registry contains a flag with the given name.

func (*FlagRegistry) PreprocessNoOptDefValArgs

func (r *FlagRegistry) PreprocessNoOptDefValArgs(args []string) []string

PreprocessNoOptDefValArgs rewrites space-separated flag syntax to equals syntax for flags that have NoOptDefVal set.

This maintains backward compatibility with user expectations while working within Cobra's documented behavior that NoOptDefVal requires equals syntax (pflag #134, #321, cobra #1962).

Example:

Input:  ["--identity", "prod", "plan"]
Output: ["--identity=prod", "plan"]

Only processes flags registered in this registry with non-empty NoOptDefVal. This includes both long form (--identity) and shorthand (-i).

func (*FlagRegistry) Register

func (r *FlagRegistry) Register(flag Flag)

Register adds a flag to the registry. Panics if a flag with the same name already exists to prevent duplicate registrations. This is a programming error that should be caught during development.

func (*FlagRegistry) RegisterBoolFlag

func (r *FlagRegistry) RegisterBoolFlag(name, shorthand string, defaultValue bool, description string)

RegisterBoolFlag is a convenience method to register a boolean flag.

func (*FlagRegistry) RegisterFlags

func (r *FlagRegistry) RegisterFlags(cmd *cobra.Command)

RegisterFlags registers all flags in this registry with a Cobra command. This is part of the Builder interface.

Each flag type is registered with its appropriate Cobra method:

  • StringFlag → cmd.Flags().StringP()
  • BoolFlag → cmd.Flags().BoolP()
  • IntFlag → cmd.Flags().IntP()
  • StringSliceFlag → cmd.Flags().StringSlice()

func (*FlagRegistry) RegisterIntFlag

func (r *FlagRegistry) RegisterIntFlag(name, shorthand string, defaultValue int, description string, required bool)

RegisterIntFlag is a convenience method to register an integer flag.

func (*FlagRegistry) RegisterPersistentFlags

func (r *FlagRegistry) RegisterPersistentFlags(cmd *cobra.Command)

RegisterPersistentFlags registers all flags as persistent flags on the command. Persistent flags are inherited by subcommands.

func (*FlagRegistry) RegisterStringFlag

func (r *FlagRegistry) RegisterStringFlag(name, shorthand, defaultValue, description string, required bool)

RegisterStringFlag is a convenience method to register a string flag.

func (*FlagRegistry) SetCompletionFunc added in v1.202.0

func (r *FlagRegistry) SetCompletionFunc(name string, fn func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective))

SetCompletionFunc sets a custom completion function for a flag. This is used to set completion functions after flag registration to avoid import cycles. For example, cmd/terraform can set the stack completion function without pkg/flags needing to import internal/exec.

func (*FlagRegistry) Validate

func (r *FlagRegistry) Validate(flagValues map[string]interface{}) error

Validate checks if all required flags are present and have valid values. Returns error if validation fails.

type GlobalOptionsBuilder

type GlobalOptionsBuilder struct {
	*StandardOptionsBuilder
}

GlobalOptionsBuilder provides a type-safe, fluent interface for building a parser with global flag definitions. This is used by RootCmd to register all global flags with proper defaults and precedence handling.

Example:

parser := flags.NewGlobalOptionsBuilder().Build()
parser.RegisterFlags(RootCmd)
if err := parser.BindToViper(viper.GetViper()); err != nil {
    log.Fatal("Failed to bind flags", "error", err)
}

func NewGlobalOptionsBuilder

func NewGlobalOptionsBuilder() *GlobalOptionsBuilder

NewGlobalOptionsBuilder creates a new builder for global flags. Returns a builder with all global flags pre-configured.

func (*GlobalOptionsBuilder) Build

Build creates a StandardParser with all global flags configured. This parser can be used to register flags with RootCmd and parse them with proper precedence.

type IntFlag

type IntFlag struct {
	Name        string
	Shorthand   string
	Default     int
	Description string
	Required    bool
	EnvVars     []string
}

IntFlag represents an integer-valued flag.

func (*IntFlag) GetCompletionFunc added in v1.202.0

func (f *IntFlag) GetCompletionFunc() func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective)

GetCompletionFunc implements Flag.

func (*IntFlag) GetDefault

func (f *IntFlag) GetDefault() interface{}

GetDefault implements Flag.

func (*IntFlag) GetDescription

func (f *IntFlag) GetDescription() string

GetDescription implements Flag.

func (*IntFlag) GetEnvVars

func (f *IntFlag) GetEnvVars() []string

GetEnvVars implements Flag.

func (*IntFlag) GetName

func (f *IntFlag) GetName() string

GetName implements Flag.

func (*IntFlag) GetNoOptDefVal

func (f *IntFlag) GetNoOptDefVal() string

GetNoOptDefVal implements Flag.

func (*IntFlag) GetShorthand

func (f *IntFlag) GetShorthand() string

GetShorthand implements Flag.

func (*IntFlag) IsRequired

func (f *IntFlag) IsRequired() bool

IsRequired implements Flag.

type Option

type Option func(*parserConfig)

Option is a functional option for configuring a FlagParser. This pattern allows for flexible, extensible configuration without breaking changes when new options are added.

Usage:

parser := flags.NewStandardFlagParser(
    flags.WithStringFlag("stack", "s", "", "Stack name"),
    flags.WithBoolFlag("dry-run", "", false, "Dry run mode"),
)

func WithBoolFlag

func WithBoolFlag(name, shorthand string, defaultValue bool, description string) Option

WithBoolFlag adds a boolean flag to the parser configuration.

func WithCommonFlags

func WithCommonFlags() Option

WithCommonFlags adds all common Atmos flags (stack, identity, dry-run).

func WithCompletionPrompt added in v1.202.0

func WithCompletionPrompt(flagName, promptTitle string, completionFunc CompletionFunc) Option

WithCompletionPrompt enables interactive prompts for a required flag when the flag is missing. This is Use Case 1: Missing Required Flags.

When the flag is required but not provided, and the terminal is interactive, the user will be shown a selector with options from the completion function.

Example:

WithRequiredStringFlag("stack", "s", "Stack name"),
WithCompletionPrompt("stack", "Choose a stack", stackFlagCompletion),

func WithDryRunFlag

func WithDryRunFlag() Option

WithDryRunFlag adds the dry-run flag.

func WithEnvVars

func WithEnvVars(flagName string, envVars ...string) Option

WithEnvVars adds environment variable bindings to a flag. Must be called after the flag is added.

Usage:

WithStringFlag("format", "f", "yaml", "Output format"),
WithEnvVars("format", "ATMOS_FORMAT", "FORMAT"),

func WithFlagRegistry added in v1.202.0

func WithFlagRegistry(registry *FlagRegistry) Option

WithFlagRegistry adds all flags from a FlagRegistry to the parser's registry. Unlike WithRegistry which replaces the registry, this merges flags into the existing registry. This is useful for adding domain-specific flags from cmd packages.

Usage:

terraformRegistry := terraform.TerraformFlags()
parser := flags.NewStandardParser(flags.WithFlagRegistry(terraformRegistry))

func WithHelmfileFlags

func WithHelmfileFlags() Option

WithHelmfileFlags adds all Helmfile-specific flags.

func WithIdentityFlag

func WithIdentityFlag() Option

WithIdentityFlag adds the identity flag with NoOptDefVal support. This enables the pattern: --identity (interactive), --identity value (explicit).

The identity flag:

  • Supports --identity=value and --identity value forms
  • Uses NoOptDefVal for interactive selection when flag is alone
  • Binds to ATMOS_IDENTITY and IDENTITY env vars
  • Respects precedence: flag > env > config > default

func WithIntFlag

func WithIntFlag(name, shorthand string, defaultValue int, description string) Option

WithIntFlag adds an integer flag to the parser configuration.

func WithNoOptDefVal

func WithNoOptDefVal(flagName, value string) Option

WithNoOptDefVal sets the NoOptDefVal for a string flag. This enables the flag to have a special value when used without an argument.

Example:

WithStringFlag("identity", "i", "", "Identity name"),
WithNoOptDefVal("identity", "__SELECT__"),  // --identity alone = "__SELECT__"

func WithOptionalValuePrompt added in v1.202.0

func WithOptionalValuePrompt(flagName, promptTitle string, completionFunc CompletionFunc) Option

WithOptionalValuePrompt enables interactive prompts for a flag when used without a value. This is Use Case 2: Optional Value Flags (like --identity pattern).

The flag's NoOptDefVal will be set to cfg.IdentityFlagSelectValue ("__SELECT__"). When the user provides --flag without a value, Cobra sets it to the sentinel value, and we detect this to show the interactive prompt.

Example:

WithStringFlag("format", "", "yaml", "Output format"),
WithOptionalValuePrompt("format", "Choose output format", formatCompletionFunc),

Result:

  • `--format` → shows interactive selector
  • `--format=json` → uses "json" (no prompt)
  • no flag → uses default "yaml" (no prompt)

func WithPackerFlags

func WithPackerFlags() Option

WithPackerFlags adds all Packer-specific flags.

func WithPositionalArgPrompt added in v1.202.0

func WithPositionalArgPrompt(argName, promptTitle string, completionFunc CompletionFunc) Option

WithPositionalArgPrompt enables interactive prompts for a positional argument when missing. This is Use Case 3: Missing Required Positional Arguments.

When the positional argument is required but not provided, and the terminal is interactive, the user will be shown a selector with options from the completion function.

Note: This requires the positional argument to be configured via PositionalArgSpec with CompletionFunc and PromptTitle fields set.

Example:

argsBuilder := flags.NewPositionalArgsBuilder()
argsBuilder.AddArg(&flags.PositionalArgSpec{
    Name:           "theme-name",
    Required:       true,
    CompletionFunc: themeNameCompletion,
    PromptTitle:    "Choose a theme to preview",
})

func WithRegistry

func WithRegistry(registry *FlagRegistry) Option

WithRegistry uses a pre-configured FlagRegistry instead of building one from options. This is useful when you want full control over flag configuration.

Usage:

registry := flags.NewFlagRegistry()
registry.Register(&flags.StringFlag{...})
parser := flags.NewStandardFlagParser(flags.WithRegistry(registry))

func WithRequiredStringFlag

func WithRequiredStringFlag(name, shorthand, description string) Option

WithRequiredStringFlag adds a required string flag.

func WithStackFlag

func WithStackFlag() Option

WithStackFlag adds the stack flag (-s).

func WithStringFlag

func WithStringFlag(name, shorthand, defaultValue, description string) Option

WithStringFlag adds a string flag to the parser configuration.

Parameters:

  • name: Long flag name (without --)
  • shorthand: Short flag name (single character, without -)
  • defaultValue: Default value if flag not provided
  • description: Help text

Usage:

WithStringFlag("stack", "s", "", "Stack name")

func WithStringSliceFlag

func WithStringSliceFlag(name, shorthand string, defaultValue []string, description string) Option

WithStringSliceFlag adds a string slice flag to the parser configuration.

Parameters:

  • name: Long flag name (without --)
  • shorthand: Short flag name (single character, without -)
  • defaultValue: Default value if flag not provided
  • description: Help text

Usage:

WithStringSliceFlag("components", "", []string{}, "Filter by components")

func WithValidValues

func WithValidValues(flagName string, validValues ...string) Option

WithValidValues sets the list of valid values for a string flag. During parsing, the flag value will be validated against this list.

Example:

WithStringFlag("format", "f", "yaml", "Output format"),
WithValidValues("format", "json", "yaml", "table"),

func WithViperPrefix

func WithViperPrefix(prefix string) Option

WithViperPrefix sets a prefix for all Viper keys. This is useful for namespacing flags in config files.

Example:

WithViperPrefix("terraform")  // flags stored as terraform.stack, terraform.identity, etc.

type OptionalValuePromptContext added in v1.202.0

type OptionalValuePromptContext struct {
	FlagName       string
	FlagValue      string
	PromptTitle    string
	CompletionFunc CompletionFunc
	Cmd            *cobra.Command
	Args           []string
}

OptionalValuePromptContext holds the context for prompting when a flag is used without a value.

type ParsedConfig

type ParsedConfig struct {
	// Flags contains parsed Atmos-specific flags (--stack, --identity, etc.).
	// Keys are flag names, values are the parsed values.
	//
	// This is internal storage used by parsers. Access individual flags through
	// helper methods like GetIdentity(), GetStack(), or by using the Get* helper
	// functions (GetString, GetBool, etc.) from this package.
	Flags map[string]interface{}

	// PositionalArgs contains positional arguments extracted from the command line.
	// The meaning of these depends on the command:
	//   - For terraform: [component] e.g., ["vpc"]
	//   - For packer/helmfile: [component] e.g., ["vpc"]
	// Callers should interpret these based on their command's semantics.
	PositionalArgs []string

	// SeparatedArgs contains arguments after the -- separator for external tools.
	// These arguments come after -- and are passed to external tools unchanged.
	// Example: atmos terraform plan vpc -s dev -- -var foo=bar
	//   PositionalArgs: ["vpc"]
	//   SeparatedArgs: ["-var", "foo=bar"]
	SeparatedArgs []string
}

ParsedConfig contains the results of parsing command-line arguments.

This is an intermediate type returned by StandardFlagParser.Parse(). Command-specific parsers (AuthParser, TerraformParser, etc.) convert this to strongly-typed options (AuthOptions, TerraformOptions, etc.).

func (*ParsedConfig) GetArgsForTool

func (pc *ParsedConfig) GetArgsForTool() []string

GetArgsForTool builds the complete argument array for executing a subprocess tool. This eliminates manual args building boilerplate throughout the codebase.

Format: [subcommand, component, ...pass-through-args] Example: ["plan", "vpc", "-var-file", "common.tfvars"]

Usage:

args := result.GetArgsForTool()  // Instead of manual: append(result.PositionalArgs, result.SeparatedArgs...)

func (*ParsedConfig) GetIdentity

func (p *ParsedConfig) GetIdentity() string

GetIdentity returns the identity value from parsed flags with proper type safety. Returns empty string if identity is not set.

func (*ParsedConfig) GetStack

func (p *ParsedConfig) GetStack() string

GetStack returns the stack value from parsed flags with proper type safety. Returns empty string if stack is not set.

type PositionalArgSpec

type PositionalArgSpec struct {
	Name           string         // Argument name (e.g., "component", "workflow")
	Description    string         // Human-readable description for usage/help
	Required       bool           // Whether this argument is required
	TargetField    string         // Name of field in Options struct to populate (e.g., "Component")
	CompletionFunc CompletionFunc // Optional: Function to provide completion values for interactive prompts
	PromptTitle    string         // Optional: Title for interactive prompt (e.g., "Choose a component")
}

PositionalArgSpec defines a single positional argument specification. This is used by builders to configure positional argument parsing.

Example:

spec := &PositionalArgSpec{
    Name:           "component",
    Description:    "Component name",
    Required:       true,
    TargetField:    "Component", // Field name in options struct (e.g., TerraformOptions.Component)
    CompletionFunc: ComponentsArgCompletion,
    PromptTitle:    "Choose a component",
}

type PositionalArgsBuilder

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

PositionalArgsBuilder provides low-level builder pattern for positional arguments. This is the foundation for domain-specific builders like TerraformPositionalArgsBuilder.

Features:

  • Auto-generates Cobra Args validator
  • Auto-generates usage string (e.g., "<component>" or "[component]")
  • Maps positional args to struct fields via TargetField
  • Type-safe extraction without manual array indexing

Usage:

builder := flags.NewPositionalArgsBuilder()
builder.AddArg(&flags.PositionalArgSpec{
    Name:        "component",
    Description: "Component name",
    Required:    true,
    TargetField: "Component", // Maps to TerraformOptions.Component field
})
specs, validator, usage := builder.Build()

func NewPositionalArgsBuilder

func NewPositionalArgsBuilder() *PositionalArgsBuilder

NewPositionalArgsBuilder creates a new PositionalArgsBuilder.

func (*PositionalArgsBuilder) AddArg

AddArg adds a positional argument specification to the builder.

Example:

builder.AddArg(&flags.PositionalArgSpec{
    Name:        "component",
    Description: "Component name",
    Required:    true,
    TargetField: "Component",
})

func (*PositionalArgsBuilder) Build

func (b *PositionalArgsBuilder) Build() (specs []*PositionalArgSpec, validator cobra.PositionalArgs, usage string)

Build generates the positional args configuration.

Returns:

  • specs: Array of positional argument specifications with TargetField mapping
  • validator: Cobra Args validator function (validates required/optional args)
  • usage: Usage string for Cobra Use field (e.g., "<component>" or "[workflow]")

Example:

specs, validator, usage := builder.Build()
cmd.Use = "deploy " + usage   // "deploy <component>"
cmd.Args = validator           // Validates component is provided

func (*PositionalArgsBuilder) GeneratePromptAwareValidator added in v1.202.0

func (b *PositionalArgsBuilder) GeneratePromptAwareValidator(hasPrompts bool) cobra.PositionalArgs

GeneratePromptAwareValidator creates a prompt-aware Cobra PositionalArgs validator. This validator allows missing required args when interactive prompts are configured, enabling the Parse() method to show prompts instead of failing validation.

Logic:

  • If interactive mode available AND prompts configured: allow 0 to totalCount args
  • Otherwise: use standard validator (enforces required args immediately)

This solves the timing issue where Cobra's Args validation happens BEFORE RunE, preventing Parse() from ever being called to show prompts.

Parameters:

  • hasPrompts: Whether interactive prompts are configured for positional args

Returns:

  • Prompt-aware validator that allows missing args when prompts will handle them

type StandardFlagParser

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

StandardFlagParser implements FlagParser for regular commands. This parser is used for commands that don't pass arguments to external tools (e.g., version, describe, list, validate).

Features:

  • Registers flags with Cobra
  • Binds flags to Viper for automatic precedence (flag > env > config > default)
  • Supports NoOptDefVal for identity pattern
  • Pure function parsing (no side effects)

Usage:

parser := flags.NewStandardFlagParser(
    flags.WithStringFlag("stack", "s", "", "Stack name"),
    flags.WithBoolFlag("dry-run", "", false, "Dry run mode"),
)

// In command setup:
parser.RegisterFlags(cmd)
parser.BindToViper(viper.GetViper())

func NewStandardFlagParser

func NewStandardFlagParser(opts ...Option) *StandardFlagParser

NewStandardFlagParser creates a new StandardFlagParser with the given options.

Example:

parser := flags.NewStandardFlagParser(
    flags.WithStackFlag(),
    flags.WithIdentityFlag(),
    flags.WithStringFlag("format", "f", "yaml", "Output format"),
)

func (*StandardFlagParser) BindFlagsToViper

func (p *StandardFlagParser) BindFlagsToViper(cmd *cobra.Command, v *viper.Viper) error

BindFlagsToViper is called after RegisterFlags to bind Cobra flags to Viper. This must be called separately because we need access to the Cobra command. Sets defaults and binds both pflags and environment variables to ensure all precedence levels work correctly (CLI flags > ENV vars > defaults).

Usage:

parser.RegisterFlags(cmd)
parser.BindFlagsToViper(cmd, viper.GetViper())

func (*StandardFlagParser) BindToViper

func (p *StandardFlagParser) BindToViper(v *viper.Viper) error

BindToViper implements FlagParser. Binds both environment variables and Cobra pflags (if command is available) to Viper.

func (*StandardFlagParser) GetIdentityFromCmd

func (p *StandardFlagParser) GetIdentityFromCmd(cmd *cobra.Command, v *viper.Viper) (string, error)

GetIdentityFromCmd retrieves the identity value from a command with proper precedence. This handles the NoOptDefVal pattern for the identity flag.

Precedence:

  1. Flag value (if changed)
  2. Environment variable (ATMOS_IDENTITY, IDENTITY)
  3. Config file
  4. Default (empty string)

Special handling:

  • If flag value is cfg.IdentityFlagSelectValue, triggers interactive selection
  • If flag not changed, falls back to Viper (env/config)

Usage:

identity, err := parser.GetIdentityFromCmd(cmd, viper.GetViper())
if err != nil {
    return err
}
if identity == cfg.IdentityFlagSelectValue {
    // Show interactive selector
}

func (*StandardFlagParser) Parse

func (p *StandardFlagParser) Parse(ctx context.Context, args []string) (*ParsedConfig, error)

Parse implements FlagParser.

func (*StandardFlagParser) ParsedFlags

func (p *StandardFlagParser) ParsedFlags() *pflag.FlagSet

ParsedFlags returns the combined FlagSet used in the last Parse() call. This is useful for checking if flags were Changed when DisableFlagParsing is enabled.

func (*StandardFlagParser) RegisterFlags

func (p *StandardFlagParser) RegisterFlags(cmd *cobra.Command)

RegisterFlags registers flags with Cobra for normal flag validation. Does NOT set DisableFlagParsing, allowing Cobra to validate flags and reject unknown ones.

For commands that need to pass unknown flags to external tools (terraform, helmfile, packer), those commands should set DisableFlagParsing=true manually in their command definition. This is a temporary measure until the compatibility flags system is fully integrated.

If positional args with prompts are configured, this sets a prompt-aware Args validator that allows missing required args when interactive mode is available.

func (*StandardFlagParser) RegisterPersistentFlags

func (p *StandardFlagParser) RegisterPersistentFlags(cmd *cobra.Command)

RegisterPersistentFlags registers flags as persistent flags (available to subcommands). This is used for global flags that should be inherited by all subcommands. NOTE: Unlike RegisterFlags(), this does NOT set DisableFlagParsing=true because persistent flags on the root command should work with Cobra's normal flag parsing. Disabling flag parsing on the root would break all subcommands' positional arguments.

func (*StandardFlagParser) Registry added in v1.202.0

func (p *StandardFlagParser) Registry() *FlagRegistry

Registry returns the underlying flag registry. This allows access to the registry for operations like SetCompletionFunc() that need to modify flags after parser creation. Any mutations to the returned registry must be made before calling RegisterFlags or RegisterPersistentFlags; changes made afterward will not affect already-registered flags.

func (*StandardFlagParser) Reset

func (p *StandardFlagParser) Reset()

Reset clears any internal parser state to prevent pollution between test runs. This resets the command's flag state and the parsedFlags FlagSet.

func (*StandardFlagParser) SetPositionalArgs

func (p *StandardFlagParser) SetPositionalArgs(
	specs []*PositionalArgSpec,
	validator cobra.PositionalArgs,
	usage string,
)

SetPositionalArgs configures positional argument extraction and validation.

Parameters:

  • specs: Positional argument specifications with TargetField mapping
  • validator: Cobra Args validator function
  • usage: Usage string for Cobra Use field (e.g., "[component]")

This method is called by StandardOptionsBuilder.Build() when WithPositionalArgs() was used.

type StandardOptions

type StandardOptions struct {
	global.Flags // Embedded global flags (identity, chdir, config, logs, pager, profiling, etc.)

	// Common command flags.
	Stack     string // Stack to operate on (--stack, -s)
	Component string // Component to operate on (--component, -c)
	Key       string // Configuration key to filter (positional arg for list components)

	// Output formatting flags.
	Format string // Output format (--format, -f): yaml, json, etc.
	File   string // Write output to file (--file)

	// Processing flags (common across describe/terraform/helmfile commands).
	ProcessTemplates     bool     // Enable Go template processing (--process-templates)
	ProcessYamlFunctions bool     // Enable YAML functions processing (--process-functions)
	Skip                 []string // Skip YAML functions (--skip)

	// Dry run flag (common across vendor, workflow, pro commands).
	DryRun bool // Simulate operation without making changes (--dry-run)

	// Query flag (for describe commands with jq/jmespath).
	Query string // JQ/JMESPath query string (--query)

	// Additional common flags.
	Provenance bool // Enable provenance tracking (--provenance)

	// List command specific flags.
	Abstract   bool   // Include abstract components (--abstract)
	Vars       bool   // Show only vars section (--vars)
	MaxColumns int    // Maximum columns for table output (--max-columns)
	Delimiter  string // Delimiter for CSV/TSV output (--delimiter)

	// Vendor command specific flags.
	Type string // Component type filter: terraform or helmfile (--type)
	Tags string // Component tag filter (--tags)

	// Validate command specific flags.
	SchemaPath           string   // Path to schema file (--schema-path)
	SchemaType           string   // Schema type: jsonschema or opa (--schema-type)
	ModulePaths          []string // OPA module paths (--module-paths)
	Timeout              int      // Validation timeout in seconds (--timeout)
	SchemasAtmosManifest string   // Path to Atmos manifest schema (--schemas-atmos-manifest)

	// Auth command specific flags.
	Login      bool   // Perform login before command (--login)
	Provider   string // Identity provider filter (--provider)
	Providers  string // Comma-separated providers list (--providers)
	Identities string // Comma-separated identities list (--identities)
	All        bool   // Apply to all items (--all)
	Everything bool   // Vendor all components (--everything)

	// Describe affected command specific flags.
	Ref                         string // Git reference for comparison (--ref)
	Sha                         string // Git commit SHA for comparison (--sha)
	RepoPath                    string // Path to cloned target repository (--repo-path)
	SSHKey                      string // Path to SSH private key (--ssh-key)
	SSHKeyPassword              string // Password for encrypted SSH key (--ssh-key-password)
	IncludeSpaceliftAdminStacks bool   // Include Spacelift admin stacks (--include-spacelift-admin-stacks)
	IncludeDependents           bool   // Include dependent components (--include-dependents)
	IncludeSettings             bool   // Include settings section (--include-settings)
	Upload                      bool   // Upload to HTTP endpoint (--upload)
	CloneTargetRef              bool   // Clone target ref instead of checkout (--clone-target-ref)
	Verbose                     bool   // Deprecated verbose flag (--verbose)
	ExcludeLocked               bool   // Exclude locked components (--exclude-locked)

	// Describe workflows command specific flags.
	Components     []string // Filter by specific components (--components)
	ComponentTypes []string // Filter by component types (--component-types)
	Output         string   // Output type: list, detail (--output)
	// contains filtered or unexported fields
}

StandardOptions provides strongly-typed access to standard Atmos command flags. Used for commands that don't pass through arguments to external tools (describe, list, validate, vendor, etc.).

Embeds global.Flags for global Atmos flags (identity, chdir, config, logs, etc.). Provides common command fields (Stack, Component, Format, File, etc.).

Commands with additional flags should embed StandardOptions and add their own fields.

func (*StandardOptions) GetGlobalFlags

func (s *StandardOptions) GetGlobalFlags() *global.Flags

GetGlobalFlags returns a pointer to the embedded global.Flags. Implements CommandOptions interface.

func (*StandardOptions) GetPositionalArgs

func (s *StandardOptions) GetPositionalArgs() []string

GetPositionalArgs returns positional arguments extracted by the parser. For standard commands: typically component name or other required args.

func (*StandardOptions) GetSeparatedArgs

func (s *StandardOptions) GetSeparatedArgs() []string

GetSeparatedArgs returns pass-through arguments. For standard commands: always empty (no pass-through).

func (*StandardOptions) SetPositionalArgs

func (s *StandardOptions) SetPositionalArgs(args []string)

SetPositionalArgs sets the positional arguments. This is exported for use by subpackage parsers that need to set positional args.

type StandardOptionsBuilder

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

StandardOptionsBuilder provides a type-safe, fluent interface for building StandardParser with strongly-typed flag definitions that map directly to StandardOptions fields.

Benefits:

  • Compile-time guarantee that flags map to StandardOptions fields
  • Refactoring-safe: renaming struct fields updates flag definitions
  • Clear intent: method names match struct field names
  • Testable: each method can be unit tested independently

Example:

parser := flags.NewStandardOptionsBuilder().
    WithStack(true).        // Required stack flag → .Stack field
    WithFormat("yaml").     // Format flag with default → .Format field
    WithQuery().            // Optional query flag → .Query field
    Build()

opts, _ := parser.Parse(ctx, args)
fmt.Println(opts.Stack)   // Type-safe!
fmt.Println(opts.Format)  // Type-safe!

func NewStandardOptionsBuilder

func NewStandardOptionsBuilder() *StandardOptionsBuilder

NewStandardOptionsBuilder creates a new builder for StandardParser.

func (*StandardOptionsBuilder) Build

Build creates the StandardParser with all configured flags and positional args. Returns a parser ready for RegisterFlags() and Parse() operations.

func (*StandardOptionsBuilder) WithAbstract

WithAbstract adds the abstract flag for including abstract components. Maps to StandardOptions.Abstract field.

func (*StandardOptionsBuilder) WithAll

WithAll adds the all flag. Maps to StandardOptions.All field.

func (*StandardOptionsBuilder) WithCloneTargetRef

func (b *StandardOptionsBuilder) WithCloneTargetRef() *StandardOptionsBuilder

WithCloneTargetRef adds the clone-target-ref flag.

func (*StandardOptionsBuilder) WithComponent

func (b *StandardOptionsBuilder) WithComponent(required bool) *StandardOptionsBuilder

WithComponent adds the component flag. Maps to StandardOptions.Component field.

Parameters:

  • required: if true, flag is marked as required

func (*StandardOptionsBuilder) WithComponentTypes

func (b *StandardOptionsBuilder) WithComponentTypes() *StandardOptionsBuilder

WithComponentTypes adds the component-types flag for filtering by component types. Maps to StandardOptions.ComponentTypes field.

func (*StandardOptionsBuilder) WithComponents

func (b *StandardOptionsBuilder) WithComponents() *StandardOptionsBuilder

WithComponents adds the components flag for filtering by specific components. Maps to StandardOptions.Components field.

func (*StandardOptionsBuilder) WithDelimiter

func (b *StandardOptionsBuilder) WithDelimiter(defaultValue string) *StandardOptionsBuilder

WithDelimiter adds the delimiter flag for CSV/TSV output. Maps to StandardOptions.Delimiter field.

func (*StandardOptionsBuilder) WithDryRun

WithDryRun adds the dry-run flag. Maps to StandardOptions.DryRun field.

func (*StandardOptionsBuilder) WithEverything

func (b *StandardOptionsBuilder) WithEverything() *StandardOptionsBuilder

WithEverything adds the everything flag for vendoring all components.

func (*StandardOptionsBuilder) WithExcludeLocked

func (b *StandardOptionsBuilder) WithExcludeLocked() *StandardOptionsBuilder

WithExcludeLocked adds the exclude-locked flag.

func (*StandardOptionsBuilder) WithFile

WithFile adds the file output flag. Maps to StandardOptions.File field.

func (*StandardOptionsBuilder) WithForceColor

func (b *StandardOptionsBuilder) WithForceColor() *StandardOptionsBuilder

WithForceColor adds the force-color flag for forcing color output. Maps to GlobalFlags.ForceColor field.

func (*StandardOptionsBuilder) WithForceTTY

WithForceTTY adds the force-tty flag for forcing TTY mode. Maps to GlobalFlags.ForceTTY field.

func (*StandardOptionsBuilder) WithFormat

func (b *StandardOptionsBuilder) WithFormat(validFormats []string, defaultValue string) *StandardOptionsBuilder

WithFormat adds the format output flag with explicit valid values and default. Maps to StandardOptions.Format field.

Parameters:

  • validFormats: List of valid format values (e.g., []string{"json", "yaml", "table"})
  • defaultValue: Default format to use when flag not provided

Example:

WithFormat([]string{"json", "yaml"}, "yaml")           // describe stacks
WithFormat([]string{"table", "tree", "json"}, "table") // auth list

func (*StandardOptionsBuilder) WithIdentities

func (b *StandardOptionsBuilder) WithIdentities() *StandardOptionsBuilder

WithIdentities adds the identities flag. Maps to StandardOptions.Identities field.

func (*StandardOptionsBuilder) WithIncludeDependents

func (b *StandardOptionsBuilder) WithIncludeDependents() *StandardOptionsBuilder

WithIncludeDependents adds the include-dependents flag.

func (*StandardOptionsBuilder) WithIncludeSettings

func (b *StandardOptionsBuilder) WithIncludeSettings() *StandardOptionsBuilder

WithIncludeSettings adds the include-settings flag.

func (*StandardOptionsBuilder) WithIncludeSpaceliftAdminStacks

func (b *StandardOptionsBuilder) WithIncludeSpaceliftAdminStacks() *StandardOptionsBuilder

WithIncludeSpaceliftAdminStacks adds the include-spacelift-admin-stacks flag.

func (*StandardOptionsBuilder) WithLogin

WithLogin adds the login flag. Maps to StandardOptions.Login field.

func (*StandardOptionsBuilder) WithMask

WithMask adds the mask flag for automatic masking of sensitive data. Maps to GlobalFlags.Mask field.

func (*StandardOptionsBuilder) WithMaxColumns

func (b *StandardOptionsBuilder) WithMaxColumns(defaultValue int) *StandardOptionsBuilder

WithMaxColumns adds the max-columns flag for table output. Maps to StandardOptions.MaxColumns field.

func (*StandardOptionsBuilder) WithModulePaths

func (b *StandardOptionsBuilder) WithModulePaths() *StandardOptionsBuilder

WithModulePaths adds the module-paths flag. Maps to StandardOptions.ModulePaths field.

func (*StandardOptionsBuilder) WithOutput

func (b *StandardOptionsBuilder) WithOutput(validOutputs []string, defaultValue string) *StandardOptionsBuilder

WithOutput adds the output flag with explicit valid values and default. Maps to StandardOptions.Output field.

Parameters:

  • validOutputs: List of valid output values (e.g., []string{"list", "map", "all"})
  • defaultValue: Default output type to use when flag not provided

Example:

WithOutput([]string{"list", "map", "all"}, "list")  // describe workflows

func (*StandardOptionsBuilder) WithPositionalArgs

func (b *StandardOptionsBuilder) WithPositionalArgs(
	specs []*PositionalArgSpec,
	validator cobra.PositionalArgs,
	usage string,
) *StandardOptionsBuilder

WithPositionalArgs configures positional argument validation and extraction.

Parameters:

  • specs: Positional argument specifications with TargetField mapping
  • validator: Cobra Args validator function
  • usage: Usage string (e.g., "[component]")

Example:

builder := flags.NewStandardOptionsBuilder().
    WithPositionalArgs(flags.NewListSettingsPositionalArgsBuilder().
        WithComponent(false).  // Optional component arg
        Build()).
    Build()

func (*StandardOptionsBuilder) WithProcessFunctions

func (b *StandardOptionsBuilder) WithProcessFunctions(defaultValue bool) *StandardOptionsBuilder

WithProcessFunctions adds the process-functions flag with specified default. Maps to StandardOptions.ProcessYamlFunctions field.

Parameters:

  • defaultValue: default value (typically true)

func (*StandardOptionsBuilder) WithProcessTemplates

func (b *StandardOptionsBuilder) WithProcessTemplates(defaultValue bool) *StandardOptionsBuilder

WithProcessTemplates adds the process-templates flag with specified default. Maps to StandardOptions.ProcessTemplates field.

Parameters:

  • defaultValue: default value (typically true)

func (*StandardOptionsBuilder) WithProvenance

func (b *StandardOptionsBuilder) WithProvenance() *StandardOptionsBuilder

WithProvenance adds the provenance tracking flag. Maps to StandardOptions.Provenance field.

func (*StandardOptionsBuilder) WithProvider

WithProvider adds the provider flag. Maps to StandardOptions.Provider field.

func (*StandardOptionsBuilder) WithProviders

func (b *StandardOptionsBuilder) WithProviders() *StandardOptionsBuilder

WithProviders adds the providers flag. Maps to StandardOptions.Providers field.

func (*StandardOptionsBuilder) WithQuery

WithQuery adds the query flag for JQ/JMESPath queries. Maps to StandardOptions.Query field.

func (*StandardOptionsBuilder) WithRef

func (b *StandardOptionsBuilder) WithRef(defaultValue string) *StandardOptionsBuilder

WithRef adds the ref flag for Git reference comparison.

func (*StandardOptionsBuilder) WithRepoPath

func (b *StandardOptionsBuilder) WithRepoPath(defaultValue string) *StandardOptionsBuilder

WithRepoPath adds the repo-path flag for target repository path.

func (*StandardOptionsBuilder) WithSSHKey

func (b *StandardOptionsBuilder) WithSSHKey(defaultValue string) *StandardOptionsBuilder

WithSSHKey adds the ssh-key flag for SSH private key path.

func (*StandardOptionsBuilder) WithSSHKeyPassword

func (b *StandardOptionsBuilder) WithSSHKeyPassword(defaultValue string) *StandardOptionsBuilder

WithSSHKeyPassword adds the ssh-key-password flag.

func (*StandardOptionsBuilder) WithSchemaPath

func (b *StandardOptionsBuilder) WithSchemaPath(defaultValue string) *StandardOptionsBuilder

WithSchemaPath adds the schema-path flag. Maps to StandardOptions.SchemaPath field.

func (*StandardOptionsBuilder) WithSchemaType

func (b *StandardOptionsBuilder) WithSchemaType(defaultValue string) *StandardOptionsBuilder

WithSchemaType adds the schema-type flag. Maps to StandardOptions.SchemaType field.

func (*StandardOptionsBuilder) WithSchemasAtmosManifest

func (b *StandardOptionsBuilder) WithSchemasAtmosManifest(defaultValue string) *StandardOptionsBuilder

WithSchemasAtmosManifest adds the schemas-atmos-manifest flag. Maps to StandardOptions.SchemasAtmosManifest field.

func (*StandardOptionsBuilder) WithSha

func (b *StandardOptionsBuilder) WithSha(defaultValue string) *StandardOptionsBuilder

WithSha adds the sha flag for Git commit SHA comparison.

func (*StandardOptionsBuilder) WithSkip

WithSkip adds the skip flag for skipping YAML functions. Maps to StandardOptions.Skip field.

func (*StandardOptionsBuilder) WithStack

func (b *StandardOptionsBuilder) WithStack(required bool) *StandardOptionsBuilder

WithStack adds the stack flag. Maps to StandardOptions.Stack field.

Parameters:

  • required: if true, flag is marked as required

func (*StandardOptionsBuilder) WithTags

func (b *StandardOptionsBuilder) WithTags(defaultValue string) *StandardOptionsBuilder

WithTags adds the tags flag for component tag filtering. Maps to StandardOptions.Tags field.

func (*StandardOptionsBuilder) WithTimeout

func (b *StandardOptionsBuilder) WithTimeout(defaultValue int) *StandardOptionsBuilder

WithTimeout adds the timeout flag. Maps to StandardOptions.Timeout field.

func (*StandardOptionsBuilder) WithType

func (b *StandardOptionsBuilder) WithType(defaultValue string) *StandardOptionsBuilder

WithType adds the type flag for component type filtering. Maps to StandardOptions.Type field.

func (*StandardOptionsBuilder) WithUpload

WithUpload adds the upload flag for HTTP endpoint upload.

func (*StandardOptionsBuilder) WithVars

WithVars adds the vars flag for showing only the vars section. Maps to StandardOptions.Vars field.

func (*StandardOptionsBuilder) WithVerbose

WithVerbose adds the verbose flag.

type StandardParser

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

StandardParser handles flag parsing for standard Atmos commands (non-pass-through). Returns strongly-typed StandardOptions with all parsed flags.

Standard commands include: describe, list, validate, vendor, workflow, aws, pro, etc. These commands don't pass arguments through to external tools.

func NewStandardParser

func NewStandardParser(opts ...Option) *StandardParser

NewStandardParser creates a parser for standard commands with specified flags. Use existing Option functions (WithStringFlag, WithBoolFlag, etc.) to add command-specific flags.

Example:

parser := NewStandardParser(
    WithStringFlag("stack", "s", "", "Stack name"),
    WithStringFlag("format", "f", "yaml", "Output format"),
    WithBoolFlag("dry-run", "", false, "Dry run mode"),
)

func (*StandardParser) BindFlagsToViper

func (p *StandardParser) BindFlagsToViper(cmd *cobra.Command, v *viper.Viper) error

BindFlagsToViper binds Cobra flags to Viper for precedence handling.

func (*StandardParser) BindToViper

func (p *StandardParser) BindToViper(v *viper.Viper) error

BindToViper binds flags to Viper for precedence handling.

func (*StandardParser) Parse

func (p *StandardParser) Parse(ctx context.Context, args []string) (*StandardOptions, error)

Parse processes command-line arguments and returns strongly-typed StandardOptions.

Handles precedence (CLI > ENV > config > defaults) via Viper. Extracts positional arguments (e.g., component name).

func (*StandardParser) RegisterFlags

func (p *StandardParser) RegisterFlags(cmd *cobra.Command)

RegisterFlags adds flags to the Cobra command. Does NOT set DisableFlagParsing - allows Cobra to validate flags normally. Commands that need pass-through set DisableFlagParsing=true manually.

func (*StandardParser) RegisterPersistentFlags

func (p *StandardParser) RegisterPersistentFlags(cmd *cobra.Command)

RegisterPersistentFlags adds flags as persistent flags (inherited by subcommands). This is used for global flags that should be available to all subcommands.

func (*StandardParser) Registry added in v1.202.0

func (p *StandardParser) Registry() *FlagRegistry

Registry returns the underlying flag registry. This allows access to the registry for operations like SetCompletionFunc() that need to modify flags after parser creation.

func (*StandardParser) SetPositionalArgs

func (p *StandardParser) SetPositionalArgs(
	specs []*PositionalArgSpec,
	validator cobra.PositionalArgs,
	usage string,
)

SetPositionalArgs configures positional argument extraction and validation. Delegates to the underlying StandardFlagParser.

type StringFlag

type StringFlag struct {
	Name           string
	Shorthand      string
	Default        string
	Description    string
	Required       bool
	NoOptDefVal    string   // Value when flag used without argument (identity pattern).
	EnvVars        []string // Environment variables to bind.
	ValidValues    []string // Valid values for this flag (enforced during validation).
	CompletionFunc func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective)
}

StringFlag represents a string-valued flag.

func (*StringFlag) GetCompletionFunc added in v1.202.0

func (f *StringFlag) GetCompletionFunc() func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective)

GetCompletionFunc implements Flag.

func (*StringFlag) GetDefault

func (f *StringFlag) GetDefault() interface{}

GetDefault implements Flag.

func (*StringFlag) GetDescription

func (f *StringFlag) GetDescription() string

GetDescription implements Flag.

func (*StringFlag) GetEnvVars

func (f *StringFlag) GetEnvVars() []string

GetEnvVars implements Flag.

func (*StringFlag) GetName

func (f *StringFlag) GetName() string

GetName implements Flag.

func (*StringFlag) GetNoOptDefVal

func (f *StringFlag) GetNoOptDefVal() string

GetNoOptDefVal implements Flag.

func (*StringFlag) GetShorthand

func (f *StringFlag) GetShorthand() string

GetShorthand implements Flag.

func (*StringFlag) GetValidValues

func (f *StringFlag) GetValidValues() []string

GetValidValues returns the list of valid values for this flag. Returns nil if no validation is needed.

func (*StringFlag) IsRequired

func (f *StringFlag) IsRequired() bool

IsRequired implements Flag.

type StringSliceFlag

type StringSliceFlag struct {
	Name        string
	Shorthand   string
	Default     []string
	Description string
	Required    bool
	EnvVars     []string // Environment variables to bind.
}

StringSliceFlag represents a string slice flag. This allows a flag to be provided multiple times to build a list:

--config file1.yaml --config file2.yaml

or with comma-separated values:

--config file1.yaml,file2.yaml

func (*StringSliceFlag) GetCompletionFunc added in v1.202.0

func (f *StringSliceFlag) GetCompletionFunc() func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective)

GetCompletionFunc implements Flag.

func (*StringSliceFlag) GetDefault

func (f *StringSliceFlag) GetDefault() interface{}

GetDefault implements Flag.

func (*StringSliceFlag) GetDescription

func (f *StringSliceFlag) GetDescription() string

GetDescription implements Flag.

func (*StringSliceFlag) GetEnvVars

func (f *StringSliceFlag) GetEnvVars() []string

GetEnvVars implements Flag.

func (*StringSliceFlag) GetName

func (f *StringSliceFlag) GetName() string

GetName implements Flag.

func (*StringSliceFlag) GetNoOptDefVal

func (f *StringSliceFlag) GetNoOptDefVal() string

GetNoOptDefVal implements Flag.

func (*StringSliceFlag) GetShorthand

func (f *StringSliceFlag) GetShorthand() string

GetShorthand implements Flag.

func (*StringSliceFlag) IsRequired

func (f *StringSliceFlag) IsRequired() bool

IsRequired implements Flag.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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