cobraflags

package module
v0.0.0-...-f76efc9 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2026 License: MIT Imports: 8 Imported by: 10

README

CobraFlags

Build Status

cobraflags is a Go module that provides an integration layer between Cobra CLI applications and Viper configuration management. It automates the binding of environment variables to Cobra command flags, simplifying the process of managing configurations in CLI applications.

Features

  • Automatic binding of environment variables to Cobra flags.
  • Support for persistent and non-persistent flags.
  • Validation of flag values using custom validation functions.
  • Easy integration with Cobra commands and subcommands.

Installation

To install the package, use:

go get github.com/go-extras/cobraflags

Usage

Registering Flags

You can define and register flags using the provided IntFlag and StringFlag types. For example:

import (
	"github.com/spf13/cobra"
	"github.com/go-extras/cobraflags"
)

var myFlag = &cobraflags.IntFlag{
	Name:     "example-flag",
	Usage:    "An example integer flag",
	Value:    42,
	Required: true,
}

func main() {
	cmd := &cobra.Command{
		Use:   "myapp",
		Short: "An example application",
		Run: func(cmd *cobra.Command, args []string) {
			value := myFlag.GetInt()
			fmt.Println("Flag value:", value)
		},
	}

	myFlag.Register(cmd)
	cobraflags.CobraOnInitialize("MYAPP", cmd)

	if err := cmd.Execute(); err != nil {
		fmt.Println(err)
	}
}
Environment Variable Binding

Flags are automatically bound to environment variables using the provided prefix. For example, a flag named example-flag with the prefix MYAPP will be bound to the environment variable MYAPP_EXAMPLE_FLAG.

Custom Viper Keys

By default, flags use their name as the Viper configuration key. You can customize this by setting the ViperKey field:

myFlag := &cobraflags.StringFlag{
    Name:     "config-file",
    ViperKey: "app.config.file", // Custom Viper key
    Usage:    "Path to configuration file",
    Value:    "config.yaml",
}

This allows you to:

  • Use different configuration keys than flag names
  • Support nested configuration structures
  • Maintain backward compatibility when renaming flags

If ViperKey is empty, the flag will fall back to using its Name for Viper binding.

Validation

You can add custom validation logic for flags using the ValidateFunc field:

myFlag.ValidateFunc = func(value int) error {
	if value < 0 {
		return fmt.Errorf("value must be non-negative")
	}
	return nil
}

You can also use the Validator field to provide a custom validator that implements the cobraflags.Validator interface:

myFlag.Validator = cobraflags.ValidatorFunc[int](func(value int) error {
	if value < 0 {
		return fmt.Errorf("value must be non-negative")
	}
	return nil
})

Note: cobraflags.ValidatorFunc is used for demonstration purposes only, use your own validators.

Documentation

For detailed documentation, refer to the source code and comments in the package.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Overview

Package cobraflags provides an integration layer between Cobra CLI applications and Viper configuration management to automate the binding of environment variables to Cobra command flags.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CobraOnInitialize

func CobraOnInitialize(envPrefix string, command *cobra.Command)

CobraOnInitialize initializes Cobra command(s) with automatic environment variable binding. This function sets up Viper to automatically detect and bind environment variables to command flags based on the provided prefix. It should be called after registering flags but before executing the Cobra command.

Environment Variable Mapping: Flags are automatically mapped to environment variables using the pattern: {envPrefix}_{FLAG_NAME} where FLAG_NAME is the flag name converted to uppercase with hyphens replaced by underscores.

Examples:

  • Flag "config-file" with prefix "MYAPP" → "MYAPP_CONFIG_FILE"
  • Flag "port" with prefix "SERVER" → "SERVER_PORT"
  • Flag "verbose" with prefix "CLI" → "CLI_VERBOSE"

Custom Viper Keys: If a flag has a custom ViperKey set, the environment variable will be based on the ViperKey instead of the flag name, following the same transformation rules.

Parameters:

  • envPrefix: Environment variable prefix (without trailing underscore)
  • command: Root Cobra command to initialize (subcommands are processed recursively)

Usage Example:

cmd := &cobra.Command{Use: "myapp"}
flag := &StringFlag{Name: "config", Value: "config.yaml"}
flag.Register(cmd)
CobraOnInitialize("MYAPP", cmd)  // Binds to MYAPP_CONFIG
cmd.Execute()

Note: This function modifies the help function to ensure initialization occurs before help is displayed, and uses sync.Once to prevent multiple initializations.

Example

ExampleCobraOnInitialize demonstrates environment variable binding.

package main

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"

	"github.com/go-extras/cobraflags"
)

func main() {
	// Reset Viper state to avoid interference from other tests
	viper.Reset()

	// Set environment variable for demo
	os.Setenv("MYAPP_MESSAGE", "from environment")
	defer os.Unsetenv("MYAPP_MESSAGE")

	messageFlag := &cobraflags.StringFlag{
		Name:  "message",
		Usage: "Message to display",
		Value: "default message",
	}

	cmd := &cobra.Command{
		Use:   "greet",
		Short: "Greeting application",
		Run: func(_cmd *cobra.Command, _args []string) {
			message := messageFlag.GetString()
			fmt.Printf("Message: %s\n", message)
		},
	}

	messageFlag.Register(cmd)
	cobraflags.CobraOnInitialize("MYAPP", cmd)
	cmd.SetArgs(make([]string, 0))
	_ = cmd.Execute()

}
Output:
Message: from environment

func PostInitCommands

func PostInitCommands(envPrefix string, flags map[*pflag.Flag]bool, commands ...*cobra.Command)

PostInitCommands iterates through the given slice of Cobra commands and recursively initializes them and their subcommands. This includes binding each command's flags to corresponding environment variables using Viper.

Parameters: - commands: A slice of Cobra commands to be initialized.

This function is called recursively for each command that contains subcommands, ensuring that the entire command tree is covered.

func PresetRequiredFlags

func PresetRequiredFlags(envPrefix string, flags map[*pflag.Flag]bool, cmd *cobra.Command)

PresetRequiredFlags binds each flag of the given Cobra command to a corresponding environment variable, if such a variable is set. This function uses Viper to read the environment variable that matches the flag name and sets the flag's value accordingly.

Parameters: - cmd: The Cobra command whose flags are to be initialized.

This function iterates through all flags of the given command, binding them to environment variables and setting their values if applicable.

func Register

func Register(cmd *cobra.Command, flags ...Flag)

Register registers multiple flags with the given cobra command in a single call. This is a convenience function that calls Register() on each flag individually.

Example:

countFlag := &IntFlag{Name: "count", Value: 10}
verboseFlag := &BoolFlag{Name: "verbose", Value: false}
Register(cmd, countFlag, verboseFlag)
Example

ExampleRegister demonstrates how to register multiple flags at once.

package main

import (
	"fmt"

	"github.com/spf13/cobra"

	"github.com/go-extras/cobraflags"
)

func main() {
	countFlag := &cobraflags.IntFlag{
		Name:  "count",
		Usage: "Number of items",
		Value: 3,
	}

	verboseFlag := &cobraflags.BoolFlag{
		Name:  "verbose",
		Usage: "Enable verbose output",
		Value: true,
	}

	cmd := &cobra.Command{
		Use:   "app",
		Short: "Example application",
		Run: func(_cmd *cobra.Command, _args []string) {
			count := countFlag.GetInt()
			verbose := verboseFlag.GetBool()

			fmt.Printf("Count: %d, Verbose: %v\n", count, verbose)
		},
	}

	cobraflags.Register(cmd, countFlag, verboseFlag)
	cmd.SetArgs(make([]string, 0))
	_ = cmd.Execute()

}
Output:
Count: 3, Verbose: true

func RegisterMap

func RegisterMap(cmd *cobra.Command, flags map[string]Flag)

RegisterMap registers flags from a map with the given cobra command. The map keys are ignored; only the flag values are registered. This is useful when you have flags organized in a map structure.

Example:

flags := map[string]Flag{
	"count":   &IntFlag{Name: "count", Value: 10},
	"verbose": &BoolFlag{Name: "verbose", Value: false},
}
RegisterMap(cmd, flags)

Types

type BoolFlag

type BoolFlag FlagBase[bool]

BoolFlag represents a command-line flag that accepts boolean values. It provides automatic binding to environment variables via Viper and supports custom validation through ValidateFunc or Validator fields.

BoolFlag supports all standard flag features:

  • Required flags (will cause command execution to fail if not provided)
  • Persistent flags (available to subcommands)
  • Shorthand notation (single character aliases)
  • Custom Viper keys for configuration binding
  • Validation with custom functions or validators

Boolean flags have special behavior:

  • They can be used without a value: --verbose (sets to true)
  • They can be explicitly set: --verbose=true or --verbose=false
  • Environment variables accept: true/false, 1/0, yes/no, on/off

Example usage:

verboseFlag := &BoolFlag{
	Name:      "verbose",
	Shorthand: "v",
	Usage:     "Enable verbose output",
	Value:     false,
	ValidateFunc: func(verbose bool) error {
		// Custom validation logic if needed
		return nil
	},
}
verboseFlag.Register(cmd)

Environment variable binding: With CobraOnInitialize("MYAPP", cmd), a flag named "verbose" will automatically bind to the environment variable "MYAPP_VERBOSE".

Example

ExampleBoolFlag demonstrates how to use a BoolFlag with Cobra commands.

package main

import (
	"fmt"

	"github.com/spf13/cobra"

	"github.com/go-extras/cobraflags"
)

func main() {
	myFlag := &cobraflags.BoolFlag{
		Name:     "verbose",
		Usage:    "Enable verbose output",
		Value:    false,
		Required: false,
	}

	cmd := &cobra.Command{
		Use:   "run",
		Short: "Run the application",
		Run: func(_cmd *cobra.Command, _args []string) {
			if myFlag.GetBool() {
				fmt.Println("Verbose mode enabled")
			} else {
				fmt.Println("Verbose mode disabled")
			}
		},
	}

	myFlag.Register(cmd)
	cmd.SetArgs([]string{"--verbose"})
	_ = cmd.Execute()

}
Output:
Verbose mode enabled

func (*BoolFlag) GetBool

func (s *BoolFlag) GetBool() bool

GetBool retrieves the current boolean value of the flag. This method automatically binds the flag to Viper on first call and returns the value from Viper, which may come from command-line arguments, environment variables, or configuration files.

Note: This method does NOT perform validation. Use GetBoolE() if you need validation to be executed.

Returns the boolean value, which may be the default value if the flag was not set.

func (*BoolFlag) GetBoolE

func (s *BoolFlag) GetBoolE() (bool, error)

GetBoolE retrieves the current boolean value of the flag with validation. This method automatically binds the flag to Viper on first call, retrieves the value, and then applies any configured validation (ValidateFunc or Validator).

Validation behavior:

  • If ValidateFunc is set, it is called with the boolean value
  • If ValidateFunc is nil but Validator is set, Validator.Validate() is called
  • If neither is set, no validation is performed

Returns:

  • On success: the boolean value and nil error
  • On validation failure: false and the validation error

Use this method when you need to ensure the flag value meets your validation criteria.

func (*BoolFlag) Register

func (s *BoolFlag) Register(cmd *cobra.Command)

type Flag

type Flag interface {
	// Register registers the flag with the given cobra command.
	Register(*cobra.Command)
	// contains filtered or unexported methods
}

Flag is an interface for a flag that can be registered with a cobra command.

type FlagBase

type FlagBase[T any] struct {
	Name         string        // Flag name used for command line arguments
	ViperKey     string        // Custom Viper configuration key (falls back to Name if empty)
	Shorthand    string        // Single character shorthand for the flag
	Usage        string        // Help text for the flag
	Required     bool          // Whether the flag is required
	Persistent   bool          // Whether the flag is persistent across subcommands
	Value        T             // Default value
	ValidateFunc func(T) error // Custom validation function (takes precedence over Validator)
	Validator    Validator     // Custom validator implementing the Validator interface
	// contains filtered or unexported fields
}

FlagBase is a generic base struct for all flag types that provides common functionality for flag registration, validation, and value retrieval. It uses Go generics to ensure type safety while sharing common behavior across different flag types.

The validation system supports two approaches:

  • ValidateFunc: A simple function that takes the flag's value type and returns an error
  • Validator: An interface-based validator that can be reused across different flag types

When both ValidateFunc and Validator are set, ValidateFunc takes precedence and Validator is ignored.

The ViperKey field allows using different configuration keys than flag names for Viper binding. If ViperKey is empty, the flag will fall back to using its Name for Viper binding. This enables:

  • Using different configuration keys than flag names
  • Supporting nested configuration structures (e.g., "app.config.file")
  • Maintaining backward compatibility when renaming flags

Example usage:

flag := &StringFlag{
	Name:     "config-file",
	ViperKey: "app.config.file", // Custom Viper key
	Usage:    "Path to configuration file",
	Value:    "default.yaml",
	ValidateFunc: func(path string) error {
		if !strings.HasSuffix(path, ".yaml") {
			return fmt.Errorf("config file must be a YAML file")
		}
		return nil
	},
}

type IntFlag

type IntFlag FlagBase[int]

IntFlag represents a command-line flag that accepts integer values. It provides automatic binding to environment variables via Viper and supports custom validation through ValidateFunc or Validator fields.

IntFlag supports all standard flag features:

  • Required flags (will cause command execution to fail if not provided)
  • Persistent flags (available to subcommands)
  • Shorthand notation (single character aliases)
  • Custom Viper keys for configuration binding
  • Validation with custom functions or validators

Example usage:

portFlag := &IntFlag{
	Name:      "port",
	Shorthand: "p",
	Usage:     "Server port number",
	Value:     8080,
	Required:  true,
	ValidateFunc: func(port int) error {
		if port < 1 || port > 65535 {
			return fmt.Errorf("port must be between 1 and 65535")
		}
		return nil
	},
}
portFlag.Register(cmd)

Environment variable binding: With CobraOnInitialize("MYAPP", cmd), a flag named "port" will automatically bind to the environment variable "MYAPP_PORT".

Example

ExampleIntFlag demonstrates how to use an IntFlag with Cobra commands.

package main

import (
	"fmt"

	"github.com/spf13/cobra"

	"github.com/go-extras/cobraflags"
)

func main() {
	myFlag := &cobraflags.IntFlag{
		Name:     "count",
		Usage:    "Number of items to process",
		Value:    10,
		Required: true,
	}

	cmd := &cobra.Command{
		Use:   "process",
		Short: "Process items",
		Run: func(_cmd *cobra.Command, _args []string) {
			value := myFlag.GetInt()
			fmt.Printf("Processing %d items\n", value)
		},
	}

	myFlag.Register(cmd)
	cmd.SetArgs([]string{"--count", "10"})
	_ = cmd.Execute()

}
Output:
Processing 10 items
Example (WithValidation)

ExampleIntFlag_withValidation demonstrates adding validation to an IntFlag.

package main

import (
	"fmt"

	"github.com/spf13/cobra"

	"github.com/go-extras/cobraflags"
)

func main() {
	myFlag := &cobraflags.IntFlag{
		Name:     "count",
		Usage:    "Number of items to process (must be positive)",
		Value:    5,
		Required: true,
		ValidateFunc: func(value int) error {
			if value <= 0 {
				return fmt.Errorf("count must be positive")
			}
			return nil
		},
	}

	cmd := &cobra.Command{
		Use:   "process",
		Short: "Process items",
		Run: func(_cmd *cobra.Command, _args []string) {
			value, err := myFlag.GetIntE()
			if err != nil {
				fmt.Printf("Validation error: %v\n", err)
				return
			}
			fmt.Printf("Processing %d items\n", value)
		},
	}

	myFlag.Register(cmd)
	cmd.SetArgs([]string{"--count", "-5"})
	_ = cmd.Execute()

}
Output:
Validation error: count must be positive
Example (WithValidator)

ExampleIntFlag_withValidator demonstrates using a custom validator with an IntFlag.

package main

import (
	"fmt"

	"github.com/spf13/cobra"

	"github.com/go-extras/cobraflags"
)

func main() {
	myFlag := &cobraflags.IntFlag{
		Name:     "count",
		Usage:    "Number of items to process (must be between 1 and 100)",
		Value:    10,
		Required: true,
		Validator: cobraflags.ValidatorFunc[int](func(value int) error {
			v := value
			if v < 1 || v > 100 {
				return fmt.Errorf("count must be between 1 and 100")
			}
			return nil
		}),
	}

	cmd := &cobra.Command{
		Use:   "process",
		Short: "Process items",
		Run: func(_cmd *cobra.Command, _args []string) {
			value, err := myFlag.GetIntE()
			if err != nil {
				fmt.Printf("Validation error: %v\n", err)
				return
			}
			fmt.Printf("Processing %d items\n", value)
		},
	}

	myFlag.Register(cmd)
	cmd.SetArgs([]string{"--count", "150"})
	_ = cmd.Execute()

}
Output:
Validation error: count must be between 1 and 100

func (*IntFlag) GetInt

func (s *IntFlag) GetInt() int

GetInt retrieves the current integer value of the flag. This method automatically binds the flag to Viper on first call and returns the value from Viper, which may come from command-line arguments, environment variables, or configuration files.

Note: This method does NOT perform validation. Use GetIntE() if you need validation to be executed.

Returns the integer value, which may be the default value if the flag was not set.

func (*IntFlag) GetIntE

func (s *IntFlag) GetIntE() (int, error)

GetIntE retrieves the current integer value of the flag with validation. This method automatically binds the flag to Viper on first call, retrieves the value, and then applies any configured validation (ValidateFunc or Validator).

Validation behavior:

  • If ValidateFunc is set, it is called with the integer value
  • If ValidateFunc is nil but Validator is set, Validator.Validate() is called
  • If neither is set, no validation is performed

Returns:

  • On success: the integer value and nil error
  • On validation failure: 0 and the validation error

Use this method when you need to ensure the flag value meets your validation criteria.

func (*IntFlag) Register

func (s *IntFlag) Register(cmd *cobra.Command)

type StringFlag

type StringFlag FlagBase[string]

StringFlag represents a command-line flag that accepts string values. It provides automatic binding to environment variables via Viper and supports custom validation through ValidateFunc or Validator fields.

StringFlag supports all standard flag features:

  • Required flags (will cause command execution to fail if not provided)
  • Persistent flags (available to subcommands)
  • Shorthand notation (single character aliases)
  • Custom Viper keys for configuration binding
  • Validation with custom functions or validators

Example usage:

configFlag := &StringFlag{
	Name:      "config",
	Shorthand: "c",
	Usage:     "Path to configuration file",
	Value:     "config.yaml",
	Required:  true,
	ValidateFunc: func(path string) error {
		if !strings.HasSuffix(path, ".yaml") {
			return fmt.Errorf("config file must be a YAML file")
		}
		return nil
	},
}
configFlag.Register(cmd)

Environment variable binding: With CobraOnInitialize("MYAPP", cmd), a flag named "config-file" will automatically bind to the environment variable "MYAPP_CONFIG_FILE".

Example

ExampleStringFlag demonstrates how to use a StringFlag with Cobra commands.

package main

import (
	"fmt"

	"github.com/spf13/cobra"

	"github.com/go-extras/cobraflags"
)

func main() {
	myFlag := &cobraflags.StringFlag{
		Name:     "message",
		Usage:    "Message to display",
		Value:    "Hello, World!",
		Required: true,
	}

	cmd := &cobra.Command{
		Use:   "greet",
		Short: "Greeting application",
		Run: func(_cmd *cobra.Command, _args []string) {
			message := myFlag.GetString()
			fmt.Printf("Message: %s\n", message)
		},
	}

	myFlag.Register(cmd)
	cmd.SetArgs([]string{"--message", "Hello, Cobra!"})
	_ = cmd.Execute()

}
Output:
Message: Hello, Cobra!
Example (WithViperKey)

ExampleStringFlag_withViperKey demonstrates using a custom ViperKey with a StringFlag. ViperKey allows using different configuration keys than flag names for Viper binding.

package main

import (
	"fmt"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"

	"github.com/go-extras/cobraflags"
)

func main() {
	// Simulate setting a configuration value using Viper directly
	// This demonstrates how ViperKey allows different config keys than flag names
	viper.Set("app.config.file", "custom.yaml")
	defer viper.Reset()

	configFlag := &cobraflags.StringFlag{
		Name:     "config-file",
		ViperKey: "app.config.file", // Custom Viper key for configuration binding
		Usage:    "Path to configuration file",
		Value:    "default.yaml",
	}

	cmd := &cobra.Command{
		Use:   "myapp",
		Short: "My application",
		Run: func(_cmd *cobra.Command, _args []string) {
			configFile := configFlag.GetString()
			fmt.Printf("Config file: %s\n", configFile)
		},
	}

	configFlag.Register(cmd)
	cmd.SetArgs(make([]string, 0))
	_ = cmd.Execute()

}
Output:
Config file: custom.yaml

func (*StringFlag) GetString

func (s *StringFlag) GetString() string

GetString retrieves the current string value of the flag. This method automatically binds the flag to Viper on first call and returns the value from Viper, which may come from command-line arguments, environment variables, or configuration files.

Note: This method does NOT perform validation. Use GetStringE() if you need validation to be executed.

Returns the string value, which may be the default value if the flag was not set.

func (*StringFlag) GetStringE

func (s *StringFlag) GetStringE() (string, error)

GetStringE retrieves the current string value of the flag with validation. This method automatically binds the flag to Viper on first call, retrieves the value, and then applies any configured validation (ValidateFunc or Validator).

Validation behavior:

  • If ValidateFunc is set, it is called with the string value
  • If ValidateFunc is nil but Validator is set, Validator.Validate() is called
  • If neither is set, no validation is performed

Returns:

  • On success: the string value and nil error
  • On validation failure: empty string and the validation error

Use this method when you need to ensure the flag value meets your validation criteria.

func (*StringFlag) Register

func (s *StringFlag) Register(cmd *cobra.Command)

type StringSliceFlag

type StringSliceFlag FlagBase[[]string]

StringSliceFlag represents a command-line flag that accepts multiple string values. It provides automatic binding to environment variables via Viper and supports custom validation through ValidateFunc or Validator fields.

StringSliceFlag supports all standard flag features:

  • Required flags (will cause command execution to fail if not provided)
  • Persistent flags (available to subcommands)
  • Shorthand notation (single character aliases)
  • Custom Viper keys for configuration binding
  • Validation with custom functions or validators

String slice flags accept multiple values in several ways:

  • Multiple flag instances: --item value1 --item value2
  • Comma-separated values: --item value1,value2,value3
  • Environment variables as comma-separated strings

Example usage:

tagsFlag := &StringSliceFlag{
	Name:      "tags",
	Shorthand: "t",
	Usage:     "Tags to apply (can be specified multiple times)",
	Value:     []string{"default"},
	ValidateFunc: func(tags []string) error {
		if len(tags) == 0 {
			return fmt.Errorf("at least one tag must be specified")
		}
		return nil
	},
}
tagsFlag.Register(cmd)

Environment variable binding: With CobraOnInitialize("MYAPP", cmd), a flag named "tags" will automatically bind to the environment variable "MYAPP_TAGS".

Example

ExampleStringSliceFlag demonstrates how to use a StringSliceFlag with Cobra commands.

package main

import (
	"fmt"

	"github.com/spf13/cobra"

	"github.com/go-extras/cobraflags"
)

func main() {
	myFlag := &cobraflags.StringSliceFlag{
		Name:     "items",
		Usage:    "List of items to process",
		Value:    []string{"item1", "item2"},
		Required: false,
	}

	cmd := &cobra.Command{
		Use:   "process",
		Short: "Process items",
		Run: func(_cmd *cobra.Command, _args []string) {
			items := myFlag.GetStringSlice()
			fmt.Printf("Processing items: %v\n", items)
		},
	}

	myFlag.Register(cmd)
	cmd.SetArgs([]string{"--items", "item3,item4"})
	_ = cmd.Execute()

}
Output:
Processing items: [item3 item4]

func (*StringSliceFlag) GetStringSlice

func (s *StringSliceFlag) GetStringSlice() []string

GetStringSlice retrieves the current string slice value of the flag. This method automatically binds the flag to Viper on first call and returns the value from Viper, which may come from command-line arguments, environment variables, or configuration files.

Note: This method does NOT perform validation. Use GetStringSliceE() if you need validation to be executed.

Returns the string slice value, which may be the default value if the flag was not set.

func (*StringSliceFlag) GetStringSliceE

func (s *StringSliceFlag) GetStringSliceE() ([]string, error)

GetStringSliceE retrieves the current string slice value of the flag with validation. This method automatically binds the flag to Viper on first call, retrieves the value, and then applies any configured validation (ValidateFunc or Validator).

Validation behavior:

  • If ValidateFunc is set, it is called with the string slice value
  • If ValidateFunc is nil but Validator is set, Validator.Validate() is called
  • If neither is set, no validation is performed

Returns:

  • On success: the string slice value and nil error
  • On validation failure: nil slice and the validation error

Use this method when you need to ensure the flag value meets your validation criteria.

func (*StringSliceFlag) Register

func (s *StringSliceFlag) Register(cmd *cobra.Command)

type Uint8Flag

type Uint8Flag FlagBase[uint8]

Uint8Flag represents a command-line flag that accepts unsigned 8-bit integer values (0-255). It provides automatic binding to environment variables via Viper and supports custom validation through ValidateFunc or Validator fields.

Uint8Flag supports all standard flag features:

  • Required flags (will cause command execution to fail if not provided)
  • Persistent flags (available to subcommands)
  • Shorthand notation (single character aliases)
  • Custom Viper keys for configuration binding
  • Validation with custom functions or validators

Uint8 flags accept values in the range 0-255. Values outside this range will be automatically clamped by the underlying cast.ToUint8() function.

Example usage:

priorityFlag := &Uint8Flag{
	Name:      "priority",
	Shorthand: "p",
	Usage:     "Task priority level (0-255)",
	Value:     128,
	ValidateFunc: func(priority uint8) error {
		if priority == 0 {
			return fmt.Errorf("priority must be greater than 0")
		}
		return nil
	},
}
priorityFlag.Register(cmd)

Environment variable binding: With CobraOnInitialize("MYAPP", cmd), a flag named "priority" will automatically bind to the environment variable "MYAPP_PRIORITY".

Example

ExampleUint8Flag demonstrates how to use a Uint8Flag with Cobra commands.

package main

import (
	"fmt"

	"github.com/spf13/cobra"

	"github.com/go-extras/cobraflags"
)

func main() {
	myFlag := &cobraflags.Uint8Flag{
		Name:     "level",
		Usage:    "Level of detail (0-255)",
		Value:    128,
		Required: false,
	}

	cmd := &cobra.Command{
		Use:   "setlevel",
		Short: "Set the level",
		Run: func(_cmd *cobra.Command, _args []string) {
			level := myFlag.GetUint8()
			fmt.Printf("Setting level to %d\n", level)
		},
	}

	myFlag.Register(cmd)
	cmd.SetArgs([]string{"--level", "200"})
	_ = cmd.Execute()

}
Output:
Setting level to 200

func (*Uint8Flag) GetUint8

func (s *Uint8Flag) GetUint8() uint8

GetUint8 retrieves the current uint8 value of the flag. This method automatically binds the flag to Viper on first call and returns the value from Viper, which may come from command-line arguments, environment variables, or configuration files.

Note: This method does NOT perform validation. Use GetUint8E() if you need validation to be executed.

The value is retrieved as uint16 from Viper and then cast to uint8 using spf13/cast.ToUint8(), which handles overflow by clamping to the uint8 range.

Returns the uint8 value, which may be the default value if the flag was not set.

func (*Uint8Flag) GetUint8E

func (s *Uint8Flag) GetUint8E() (uint8, error)

GetUint8E retrieves the current uint8 value of the flag with validation. This method automatically binds the flag to Viper on first call, retrieves the value, and then applies any configured validation (ValidateFunc or Validator).

Validation behavior:

  • If ValidateFunc is set, it is called with the uint8 value
  • If ValidateFunc is nil but Validator is set, Validator.Validate() is called
  • If neither is set, no validation is performed

The value is retrieved as uint16 from Viper and then cast to uint8 using spf13/cast.ToUint8(), which handles overflow by clamping to the uint8 range.

Returns:

  • On success: the uint8 value and nil error
  • On validation failure: 0 and the validation error

Use this method when you need to ensure the flag value meets your validation criteria.

func (*Uint8Flag) Register

func (s *Uint8Flag) Register(cmd *cobra.Command)

type Validator

type Validator interface {
	Validate(any) error
}

Validator is an interface that defines a method for validating a value. It is used to validate the values of flags.

type ValidatorFunc

type ValidatorFunc[T any] func(T) error

ValidatorFunc is a function type that implements the Validator interface. This function exists just for demonstration and testing purposes only. Use ValidateFunc field in FlagBase instead. Note, T must be the same type as the flag value.

func (ValidatorFunc[T]) Validate

func (f ValidatorFunc[T]) Validate(value any) error

Validate calls the ValidatorFunc itself to validate the value.

Jump to

Keyboard shortcuts

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