cobra

package
v1.19.2 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2026 License: MIT Imports: 21 Imported by: 0

README

Cobra Package

Go Version

Production-ready wrapper around spf13/cobra for building professional CLI applications with enhanced features.


Table of Contents


Overview

The cobra package provides a comprehensive solution for building CLI applications in Go. It wraps spf13/cobra with additional features for production use, including integrated version management, configuration handling, shell completion support, and thread-safe design.

Design Philosophy
  1. Instance-Based Architecture - No global state, ensuring thread-safety and testability
  2. Progressive Enhancement - Start simple, add features incrementally
  3. Type Safety - Comprehensive flag support with compile-time safety
  4. Developer Experience - Intuitive API with clear method names
Performance
  • Minimal overhead - Thin wrapper (<1% impact vs raw cobra)
  • Zero-copy flags - Direct binding to variables, no memory duplication
  • Fast startup - Lazy initialization and efficient parsing
  • Thread-safe - Multiple CLI instances can coexist safely

Key Features

  • Zero-Boilerplate Setup - Build complete CLI apps in minutes
  • Thread-Safe Design - Instance-based, no global state
  • Type-Safe Flags - Support for 20+ Go types
  • Shell Completion - Auto-generate for bash, zsh, fish, PowerShell
  • Config Generation - Auto-generate JSON, YAML, TOML configs
  • Version Management - Integrated version display
  • Logging Integration - Built-in structured logging support
  • Error Handling - Clean error printing and code management
  • Persistent Flags - Flags that propagate to subcommands
  • Custom Commands - Easy addition of commands and subcommands

Installation

go get github.com/nabbar/golib/cobra

Requirements:

  • Go 1.18+
  • Dependencies: spf13/cobra, nabbar/golib/{logger,version,viper}

Architecture

Package Structure
cobra/
├── interface.go      # Public API (Cobra interface)
├── model.go          # Core implementation
├── configure.go      # Config file generation
├── completion.go     # Shell completion support
└── printError.go     # Error code management
Component Diagram
┌────────────────────────────────────────┐
│         Cobra Interface                │
│    CLI Application Builder             │
└──────────┬─────────────────────────────┘
           │
           ├──> Version (libver.Version)
           │    └─ Version, license, build info
           │
           ├──> Logger (liblog.Logger)
           │    └─ Structured logging
           │
           ├──> Config (libvpr.Viper)
           │    └─ Config loading/generation
           │
           ├──> Commands (spfcbr.Command)
           │    ├─ Root command
           │    ├─ Built-in commands
           │    └─ Custom commands
           │
           └──> Flags (20+ types)
                ├─ Persistent flags
                ├─ Local flags
                └─ Zero-copy binding
Design Patterns

Instance-Based Design

// Each instance is independent and thread-safe
app1 := libcbr.New()
app2 := libcbr.New()
// No interference

Dependency Injection

// Inject as functions for flexibility
app.SetLogger(func() liblog.Logger { return myLogger })
app.SetViper(func() libvpr.Viper { return myConfig })

Progressive Enhancement

app := libcbr.New()
app.Init()                        // Basic CLI
app.AddCommandCompletion()        // Add completion
app.AddCommandConfigure(...)      // Add config gen

Quick Start

Minimal CLI
package main

import (
    libcbr "github.com/nabbar/golib/cobra"
    libver "github.com/nabbar/golib/version"
)

func main() {
    version := libver.NewVersion(
        libver.License_MIT, "myapp", "My App",
        "2024-01-01", "abc123", "v1.0.0",
        "Author", "myapp", struct{}{}, 0,
    )
    
    app := libcbr.New()
    app.SetVersion(version)
    app.Init()
    app.Execute()
}
CLI with Features
package main

import (
    "context"
    libcbr "github.com/nabbar/golib/cobra"
    liblog "github.com/nabbar/golib/logger"
    libver "github.com/nabbar/golib/version"
    libvpr "github.com/nabbar/golib/viper"
)

func main() {
    version := libver.NewVersion(/* ... */)
    
    app := libcbr.New()
    app.SetVersion(version)
    app.SetLogger(func() liblog.Logger {
        return liblog.New(context.Background)
    })
    app.SetViper(func() libvpr.Viper {
        return libvpr.New()
    })
    app.Init()
    
    // Add flags
    var configPath string
    var verbose int
    app.SetFlagConfig(true, &configPath)
    app.SetFlagVerbose(true, &verbose)
    
    // Add commands
    app.AddCommandCompletion()
    app.AddCommandConfigure("config", "c", "Generate config file")
    
    app.Execute()
}
CLI with Custom Command
package main

import (
    libcbr "github.com/nabbar/golib/cobra"
    spfcbr "github.com/spf13/cobra"
)

func main() {
    app := libcbr.New()
    app.SetVersion(version)
    app.Init()
    
    runCmd := &spfcbr.Command{
        Use:   "run",
        Short: "Run the application",
        RunE: func(cmd *spfcbr.Command, args []string) error {
            // Application logic
            return nil
        },
    }
    
    app.AddCommand(runCmd)
    app.Execute()
}

Built-in Commands

Completion Command

Generates shell completion scripts.

Usage:

# Bash
myapp --completion bash > /etc/bash_completion.d/myapp

# Zsh
myapp --completion zsh > /usr/local/share/zsh/site-functions/_myapp

# Fish
myapp --completion fish > ~/.config/fish/completions/myapp.fish

# PowerShell
myapp --completion powershell > myapp.ps1

Add to CLI:

app.AddCommandCompletion()

Installation:

# Bash
sudo myapp --completion bash /etc/bash_completion.d/myapp
source ~/.bashrc

# Zsh
myapp --completion zsh /usr/local/share/zsh/site-functions/_myapp
source ~/.zshrc

# Fish
myapp --completion fish ~/.config/fish/completions/myapp.fish

# PowerShell
myapp --completion powershell > myapp.ps1
. ./myapp.ps1
Configure Command

Generates configuration files in multiple formats.

Usage:

myapp --configure json config.json   # JSON format
myapp --configure yaml config.yaml   # YAML format
myapp --configure toml config.toml   # TOML format

Add to CLI:

app.AddCommandConfigure("config", "c", "Generate configuration file")

The generated config includes all flags with current values and types.

Print Error Code Command

Lists all error codes used in the application.

Usage:

myapp --print-error-code

Add to CLI:

app.AddCommandPrintErrorCode("errors", "e", "Print error codes", 
    func(item, value string) {
        fmt.Printf("%s: %s\n", item, value)
    })

Flag Management

Standard Flags

Config Flag:

var configPath string
app.SetFlagConfig(true, &configPath)
// Usage: --config /path/to/config.yaml

Verbose Flag:

var verbose int
app.SetFlagVerbose(true, &verbose)
// Usage: -v (1), -vv (2), -vvv (3)
Supported Flag Types

String:

var str string
app.AddFlagString(true, &str, "name", "n", "default", "Description")

Integer Types:

var i int
app.AddFlagInt(true, &i, "count", "c", 10, "Count value")

var i8 int8
app.AddFlagInt8(true, &i8, "level", "l", 5, "Level value")

var i16 int16
app.AddFlagInt16(true, &i16, "port", "p", 8080, "Port number")

var i32 int32
app.AddFlagInt32(true, &i32, "size", "s", 1024, "Size value")

var i64 int64
app.AddFlagInt64(true, &i64, "bytes", "b", 4096, "Byte count")

Unsigned Integer Types:

var u uint
app.AddFlagUint(true, &u, "max", "m", 100, "Maximum value")

var u8 uint8
app.AddFlagUint8(true, &u8, "level", "l", 5, "Level")

var u16 uint16
app.AddFlagUint16(true, &u16, "port", "p", 8080, "Port")

var u32 uint32
app.AddFlagUint32(true, &u32, "size", "s", 1024, "Size")

var u64 uint64
app.AddFlagUint64(true, &u64, "bytes", "b", 4096, "Bytes")

Floating-Point:

var f32 float32
app.AddFlagFloat32(true, &f32, "rate", "r", 0.5, "Rate value")

var f64 float64
app.AddFlagFloat64(true, &f64, "ratio", "r", 0.75, "Ratio value")

Boolean:

var enabled bool
app.AddFlagBool(true, &enabled, "enable", "e", false, "Enable feature")

Duration:

var timeout time.Duration
app.AddFlagDuration(true, &timeout, "timeout", "t", 
    30*time.Second, "Timeout duration")

Count:

var verbosity int
app.AddFlagCount(true, &verbosity, "verbose", "v", "Increase verbosity")

IP Address:

var ip net.IP
app.AddFlagIP(true, &ip, "addr", "a", 
    net.IPv4(127, 0, 0, 1), "IP address")

var mask net.IPMask
app.AddFlagIPMask(true, &mask, "mask", "m", 
    net.CIDRMask(24, 32), "Network mask")

var ipnet net.IPNet
app.AddFlagIPNet(true, &ipnet, "network", "n", 
    defaultNet, "IP network")

Slices:

var strSlice []string
app.AddFlagStringSlice(true, &strSlice, "tags", "t", 
    []string{}, "Tags")

var intSlice []int
app.AddFlagIntSlice(true, &intSlice, "ids", "i", 
    []int{}, "IDs")
Persistent vs Local Flags

Persistent (inherited by subcommands):

app.AddFlagString(true, &global, "global", "g", "", "Global option")

Local (command-specific):

app.AddFlagString(false, &local, "local", "l", "", "Local option")

Configuration

Initialization Function
app.SetFuncInit(func() {
    // Custom initialization
    setupDatabase()
    loadPlugins()
    validateEnvironment()
})
Logger Integration
app.SetLogger(func() liblog.Logger {
    logger := liblog.New(context.Background)
    logger.SetLevel(liblog.InfoLevel)
    return logger
})
Viper Integration
app.SetViper(func() libvpr.Viper {
    v := libvpr.New()
    v.SetConfigType("yaml")
    v.AddConfigPath("/etc/myapp/")
    v.AddConfigPath("$HOME/.myapp")
    v.AddConfigPath(".")
    return v
})
Force No Info Mode
app.SetForceNoInfo(true)  // Disable package path info

Custom Commands

Basic Command
cmd := &spfcbr.Command{
    Use:   "serve",
    Short: "Start the server",
    Long:  "Start the HTTP server on the specified port",
    RunE: func(cmd *spfcbr.Command, args []string) error {
        return startServer()
    },
}

var port int
cmd.Flags().IntVarP(&port, "port", "p", 8080, "Server port")

app.AddCommand(cmd)
Subcommands
// Parent command
dbCmd := &spfcbr.Command{
    Use:   "database",
    Short: "Database operations",
}

// Subcommands
migrateCmd := &spfcbr.Command{
    Use:   "migrate",
    Short: "Run migrations",
    RunE:  runMigrations,
}

seedCmd := &spfcbr.Command{
    Use:   "seed",
    Short: "Seed database",
    RunE:  seedDatabase,
}

dbCmd.AddCommand(migrateCmd, seedCmd)
app.AddCommand(dbCmd)

// Usage: myapp database migrate
Pre/Post Hooks
cmd := &spfcbr.Command{
    Use: "process",
    PreRunE: func(cmd *spfcbr.Command, args []string) error {
        return validateInput(args)  // Before execution
    },
    RunE: func(cmd *spfcbr.Command, args []string) error {
        return processData(args)    // Main logic
    },
    PostRunE: func(cmd *spfcbr.Command, args []string) error {
        return cleanup()            // After execution
    },
}

Advanced Usage

Multiple CLI Instances
// Thread-safe: independent instances
adminCLI := libcbr.New()
adminCLI.SetVersion(adminVersion)
adminCLI.Init()

userCLI := libcbr.New()
userCLI.SetVersion(userVersion)
userCLI.Init()

go adminCLI.Execute()
go userCLI.Execute()
Dynamic Command Registration
app := libcbr.New()
app.Init()

plugins := loadPlugins()
for _, plugin := range plugins {
    app.AddCommand(plugin.GetCommand())
}
Context-Aware Commands
cmd := &spfcbr.Command{
    Use: "run",
    RunE: func(cmd *spfcbr.Command, args []string) error {
        ctx := cmd.Context()
        
        select {
        case <-ctx.Done():
            return ctx.Err()
        default:
            return doWork(ctx)
        }
    },
}
Custom Error Handling
app.GetCommand().SilenceErrors = true
app.GetCommand().SilenceUsage = true

if err := app.Execute(); err != nil {
    logger.Error("Execution failed", "error", err)
    os.Exit(1)
}

Use Cases

Microservice CLI
app := libcbr.New()
app.SetVersion(version)
app.Init()

serverCmd := &spfcbr.Command{
    Use:   "server",
    Short: "Start microservice",
    RunE:  runServer,
}

healthCmd := &spfcbr.Command{
    Use:   "health",
    Short: "Health check",
    RunE:  checkHealth,
}

app.AddCommand(serverCmd, healthCmd)
DevOps Deployment Tool
app := libcbr.New()
app.Init()

deployCmd := &spfcbr.Command{
    Use:   "deploy",
    Short: "Deploy application",
}

var env string
deployCmd.Flags().StringVarP(&env, "env", "e", "dev", "Environment")
deployCmd.RunE = func(cmd *spfcbr.Command, args []string) error {
    return deploy(env)
}

app.AddCommand(deployCmd)
System Administration Tool
app := libcbr.New()
app.Init()

backupCmd := &spfcbr.Command{
    Use:   "backup",
    Short: "Backup data",
    RunE:  performBackup,
}

restoreCmd := &spfcbr.Command{
    Use:   "restore",
    Short: "Restore from backup",
    RunE:  performRestore,
}

app.AddCommand(backupCmd, restoreCmd)
Configuration Generator
app := libcbr.New()
app.Init()
app.AddCommandConfigure("config", "c", "Generate config file")

// Users can: myapp --configure yaml config.yaml

API Reference

Factory Function

New() Cobra

Creates a new Cobra instance.

app := libcbr.New()
Configuration Methods
Method Description
SetVersion(v libver.Version) Set version information
SetLogger(fct FuncLogger) Inject logger provider
SetViper(fct FuncViper) Inject config provider
SetFuncInit(fct FuncInit) Set initialization function
SetForceNoInfo(flag bool) Control info display
Init() Initialize CLI (required)
Execute() error Execute CLI
Command Methods
Method Description
AddCommand(cmd ...*spfcbr.Command) Add custom commands
AddCommandCompletion() Add completion command
AddCommandConfigure(use, short, long string) Add config command
AddCommandPrintErrorCode(...) Add error code command
GetCommand() *spfcbr.Command Get root command
Flag Methods
Method Description
SetFlagConfig(persistent bool, flagVar *string) Config flag
SetFlagVerbose(persistent bool, flagVar *int) Verbose flag
AddFlagString(...) String flag
AddFlagInt(...) Int flag
AddFlagBool(...) Bool flag
AddFlagDuration(...) Duration flag
AddFlagFloat32/64(...) Float flags
AddFlagInt8/16/32/64(...) Integer flags
AddFlagUint/8/16/32/64(...) Unsigned integer flags
AddFlagIP/IPMask/IPNet(...) IP address flags
AddFlagStringSlice/IntSlice(...) Slice flags
AddFlagCount(...) Count flag

Testing

The package uses Ginkgo v2 + Gomega for comprehensive testing.

# Run tests
go test ./...

# With coverage
go test -cover ./...

# With race detection
CGO_ENABLED=1 go test -race ./...

# Using Ginkgo
go install github.com/onsi/ginkgo/v2/ginkgo@latest
ginkgo -r

Coverage:

Component Coverage Specs
Commands ~80% 25
Flags ~85% 30
Configuration ~70% 20
Completion ~65% 15
Initialization ~75% 10
Total ~75% 100

See TESTING.md for detailed testing documentation.


Best Practices

1. Initialization Order
// ✅ Correct
app := libcbr.New()
app.SetVersion(version)
app.SetLogger(logger)
app.SetViper(viper)
app.Init()
app.AddCommand(cmd)
app.Execute()
2. Flag Organization
// ✅ Group related flags
type Config struct {
    Host string
    Port int
    TLS  bool
}

var cfg Config
app.AddFlagString(true, &cfg.Host, "host", "h", "localhost", "Host")
app.AddFlagInt(true, &cfg.Port, "port", "p", 8080, "Port")
app.AddFlagBool(true, &cfg.TLS, "tls", "t", false, "Enable TLS")
3. Error Handling
// ✅ Wrap errors with context
cmd.RunE = func(cmd *spfcbr.Command, args []string) error {
    if err := validate(args); err != nil {
        return fmt.Errorf("validation failed: %w", err)
    }
    return execute()
}
4. Command Documentation
// ✅ Comprehensive documentation
cmd := &spfcbr.Command{
    Use:   "deploy [env]",
    Short: "Deploy application",
    Long: `Deploy application to environment.
    
Environments: dev, staging, prod`,
    Example: "myapp deploy prod --region us-east-1",
    Args:    spfcbr.ExactArgs(1),
    RunE:    deployCommand,
}
5. Resource Cleanup
// ✅ Always clean up
cmd.RunE = func(cmd *spfcbr.Command, args []string) error {
    db, err := openDB()
    if err != nil {
        return err
    }
    defer db.Close()
    
    return process(db)
}
6. Testable Design
// ✅ Factory for testing
func CreateApp(logger liblog.Logger) libcbr.Cobra {
    app := libcbr.New()
    app.SetLogger(func() liblog.Logger { return logger })
    app.Init()
    return app
}

// In tests
app := CreateApp(mockLogger)

Troubleshooting

Flags Not Working

Problem: Flags not recognized.

Solution: Call Init() before adding flags.

app.Init()  // ✅ First
app.SetFlagConfig(true, &config)
Command Not Found

Problem: Custom command not found.

Solution: Add commands after Init().

app.Init()
app.AddCommand(myCommand)  // ✅ After Init
Configuration Not Loading

Problem: Viper config not loading.

Solution: Set viper before Init() and read config.

app.SetViper(func() libvpr.Viper {
    v := libvpr.New()
    v.SetConfigFile(path)
    v.ReadInConfig()  // ✅ Read config
    return v
})
app.Init()
Completion Not Working

Problem: Shell completion not functioning.

Solution: Install completion correctly and check permissions.

sudo myapp --completion bash /etc/bash_completion.d/myapp
chmod +x /etc/bash_completion.d/myapp
source ~/.bashrc
Debug Mode

Enable verbose logging:

app.SetLogger(func() liblog.Logger {
    logger := liblog.New(context.Background)
    logger.SetLevel(liblog.DebugLevel)
    return logger
})

Contributing

Contributions welcome! Follow these guidelines:

Code:

  • Do not use AI for implementation code
  • AI may assist with tests, docs, and bug fixes
  • Pass go test -race
  • Follow existing patterns
  • Add tests for new features

Documentation:

  • Update README.md for new features
  • Add examples for common use cases
  • Keep docs synchronized

Pull Requests:

  • Clear description of changes
  • Reference related issues
  • Include test results
  • Update documentation

AI Transparency Notice

In accordance with Article 50.4 of the EU AI Act, AI assistance has been used for testing, documentation, and bug fixing under human supervision.


Resources

Documentation:

Related Packages:

  • logger - Logging implementation
  • version - Version management
  • viper - Configuration management

External Resources:


License

MIT License - See LICENSE file for details.

Documentation

Overview

Package cobra provides a comprehensive, production-ready wrapper around spf13/cobra for building professional CLI applications in Go.

This package simplifies CLI application development by providing:

  • Zero-boilerplate setup for complete CLI applications
  • Thread-safe, instance-based design (no global state)
  • Type-safe flags for 20+ Go types with compile-time safety
  • Auto-generated shell completion (bash, zsh, fish, PowerShell)
  • Auto-generated configuration file support
  • Integrated logging and version management

Design Philosophy:

1. Instance-Based Architecture: Unlike raw cobra which often relies on global variables, this package uses instance-based design ensuring thread-safety and testability.

2. Progressive Enhancement: Start with a basic CLI, then add features (completion, config generation) with single function calls.

3. Type Safety: Comprehensive flag support with Go's type system preventing runtime errors.

Quick Example:

package main

import (
    libcbr "github.com/nabbar/golib/cobra"
    libver "github.com/nabbar/golib/version"
)

func main() {
    app := libcbr.New()
    app.SetVersion(version)
    app.Init()

    var config string
    app.SetFlagConfig(true, &config)
    app.AddCommandCompletion()

    app.Execute()
}

Built-in Features:

  • Shell completion generation (--completion bash|zsh|fish|powershell)
  • Configuration file generation (--configure json|yaml|toml)
  • Error code printing (--print-error-code)
  • Version information (--version)

For more examples and detailed documentation, see README.md.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cobra

type Cobra interface {
	// SetVersion sets the version of the Cobra application. The version is used
	// to construct the help message and the version message.
	//
	// The SetVersion function does not return any value. It is designed to be used as a
	// setter function, which means that the function will not return until the Cobra
	// application's logic has been set.
	//
	// If an error occurs while setting the version, the function will panic.
	SetVersion(v libver.Version)

	// SetFuncInit sets the initialization function. The initialization function is called
	// when the Cobra application is initialized. The initialization function takes
	// no arguments and returns no value.
	//
	// The SetFuncInit function does not return any value. It is designed to be used as a
	// setter function, which means that the function will not return until the Cobra
	// application's logic has been set.
	//
	// If an error occurs while setting the initialization function, the error is returned.
	//
	// The SetFuncInit function is safe to call concurrently.
	SetFuncInit(fct FuncInit)
	// SetViper sets the viper function. The viper function is called when the Cobra
	// application needs to access the viper configuration. The viper function takes
	// no arguments and returns a viper configuration.
	//
	// The SetViper function does not return any value. It is designed to be used as a
	// setter function, which means that the function will not return until the Cobra
	// application's logic has been set.
	//
	// If an error occurs while setting the viper, the error is returned.
	SetViper(fct FuncViper)
	// SetLogger sets the logger function. The logger function is called when the Cobra
	// application needs to log information. The logger function takes no arguments and
	// returns a logger.
	//
	// The SetLogger function does not return any value. It is designed to be used as a
	// setter function, which means that the function will not return until the Cobra
	// application's logic has been set.
	//
	// If an error occurs while setting the logger, the error is returned.
	//
	// The SetLogger function is safe to call concurrently.
	SetLogger(fct FuncLogger)
	// SetForceNoInfo sets the ForceNoInfo flag. If the flag is set to true, the
	// Cobra application will not print any information related to the
	// package path. If the flag is set to false, the Cobra application will
	// print information related to the package path.
	//
	// The SetForceNoInfo function does not return any value. It is designed to be
	// used as a setter function, which means that the function will not return
	// until the Cobra application's logic has been set.
	SetForceNoInfo(flag bool)

	// Init initializes the Cobra application. It sets the logger, the version,
	// and the force no info flag. The function must be called before executing
	// the Cobra application.
	//
	// If an error occurs while initializing the Cobra application, the
	// error is returned.
	//
	// The Init function does not return any value. It is designed to be used as
	// a setter function, which means that the function will not return until the
	// Cobra application's logic has been set.
	Init()

	// SetFlagConfig adds a string flag to the Cobra application that can be used
	// to configure the application.
	//
	// The SetFlagConfig function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to a string
	//
	// If an error occurs while adding the flag, the error is returned.
	SetFlagConfig(persistent bool, flagVar *string) error
	// SetFlagVerbose adds a verbose flag to the Cobra application
	//
	// The SetFlagVerbose function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to an int
	//
	// The verbose flag is used to enable verbose mode (multi allowed v, vv, vvv)
	//
	// Example:
	// cobra.SetFlagVerbose(true, &verbose)
	SetFlagVerbose(persistent bool, flagVar *int)

	// AddFlagString adds a string flag to the Cobra application
	//
	// The AddFlagString function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to a string
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagString(persistent bool, p *string, name, shorthand string, value string, usage string)
	// AddFlagCount adds a count flag to the Cobra application
	//
	// The AddFlagCount function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to an int
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - usage: a description of the flag
	AddFlagCount(persistent bool, p *int, name, shorthand string, usage string)
	// AddFlagBool adds a bool flag to the Cobra application
	//
	// The AddFlagBool function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to a bool
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagBool(persistent bool, p *bool, name, shorthand string, value bool, usage string)
	// AddFlagDuration adds a time.Duration flag to the Cobra application
	//
	// The AddFlagDuration function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to a time.Duration
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagDuration(persistent bool, p *time.Duration, name, shorthand string, value time.Duration, usage string)
	// AddFlagFloat32 adds a float32 flag to the Cobra application
	//
	// The AddFlagFloat32 function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to a float32
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagFloat32(persistent bool, p *float32, name, shorthand string, value float32, usage string)
	// AddFlagFloat64 adds a float64 flag to the Cobra application
	//
	// The AddFlagFloat64 function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to a float64
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagFloat64(persistent bool, p *float64, name, shorthand string, value float64, usage string)
	// AddFlagInt adds an int flag to the Cobra application
	//
	// The AddFlagInt function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to an int
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagInt(persistent bool, p *int, name, shorthand string, value int, usage string)
	// AddFlagInt8 adds an int8 flag to the Cobra application
	//
	// The AddFlagInt8 function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to an int8
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagInt8(persistent bool, p *int8, name, shorthand string, value int8, usage string)
	// AddFlagInt16 adds an int16 flag to the Cobra application
	//
	// The AddFlagInt16 function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to an int16
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagInt16(persistent bool, p *int16, name, shorthand string, value int16, usage string)
	// AddFlagInt32 adds an int32 flag to the Cobra application
	//
	// The AddFlagInt32 function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to an int32
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagInt32(persistent bool, p *int32, name, shorthand string, value int32, usage string)
	// AddFlagInt32Slice adds an int32 slice flag to the Cobra application
	//
	// The AddFlagInt32Slice function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to an int32 slice
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagInt32Slice(persistent bool, p *[]int32, name, shorthand string, value []int32, usage string)
	// AddFlagInt64 adds an int64 flag to the Cobra application
	//
	// The AddFlagInt64 function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to an int64
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagInt64(persistent bool, p *int64, name, shorthand string, value int64, usage string)
	// AddFlagInt64Slice adds an int64 slice flag to the Cobra application
	//
	// The AddFlagInt64Slice function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to an int64 slice
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagInt64Slice(persistent bool, p *[]int64, name, shorthand string, value []int64, usage string)
	// AddFlagUint adds a uint flag to the Cobra application
	//
	// The AddFlagUint function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to a uint
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagUint(persistent bool, p *uint, name, shorthand string, value uint, usage string)
	// AddFlagUintSlice adds a uint slice flag to the Cobra application
	//
	// The AddFlagUintSlice function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to a uint slice
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagUintSlice(persistent bool, p *[]uint, name, shorthand string, value []uint, usage string)
	// AddFlagUint8 adds a uint8 flag to the Cobra application
	//
	// The AddFlagUint8 function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to a uint8
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagUint8(persistent bool, p *uint8, name, shorthand string, value uint8, usage string)
	// AddFlagUint16 adds a uint16 flag to the Cobra application
	//
	// The AddFlagUint16 function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to a uint16
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagUint16(persistent bool, p *uint16, name, shorthand string, value uint16, usage string)
	// AddFlagUint32 adds a uint32 flag to the Cobra application
	//
	// The AddFlagUint32 function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to a uint32
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	//
	// The AddFlagUint32 function does not return any value. It is used
	// to add a uint32 flag to the Cobra application.
	//
	// The AddFlagUint32 function allocates memory for the returned
	// flag. The caller is responsible for freeing this memory when it is no
	// longer needed.
	AddFlagUint32(persistent bool, p *uint32, name, shorthand string, value uint32, usage string)
	// AddFlagUint64 adds a uint64 flag to the Cobra application
	//
	// The AddFlagUint64 function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to a uint64
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	//
	// The AddFlagUint64 function does not return any value. It is used
	// to add a uint64 flag to the Cobra application.
	//
	// The AddFlagUint64 function allocates memory for the returned
	// flag. The caller is responsible for freeing this memory when it is no
	// longer needed.
	AddFlagUint64(persistent bool, p *uint64, name, shorthand string, value uint64, usage string)
	// AddFlagStringArray adds a string array flag to the Cobra application
	//
	// The AddFlagStringArray function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to a string array
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	//
	// The AddFlagStringArray function does not return any value. It is used
	// to add a string array flag to the Cobra application.
	//
	// The AddFlagStringArray function allocates memory for the returned
	// flag. The caller is responsible for freeing this memory when it is no
	// longer needed.
	AddFlagStringArray(persistent bool, p *[]string, name, shorthand string, value []string, usage string)
	// AddFlagStringToInt adds a string flag to the Cobra application
	// that maps string keys to int values.
	//
	// The AddFlagStringToInt function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to a map of string keys to int values
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	AddFlagStringToInt(persistent bool, p *map[string]int, name, shorthand string, value map[string]int, usage string)
	// AddFlagStringToInt64 adds a string flag to the Cobra application
	// that maps string keys to int64 values.
	//
	// The AddFlagStringToInt64 function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to a map of string keys to int64 values
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	//
	// The AddFlagStringToInt64 function does not return any value. It is used
	// to add a string flag to the Cobra application.
	//
	// The AddFlagStringToInt64 function allocates memory for the returned
	// flag. The caller is responsible for freeing this memory when it is no
	// longer needed.
	AddFlagStringToInt64(persistent bool, p *map[string]int64, name, shorthand string, value map[string]int64, usage string)
	// AddFlagStringToString adds a string flag to the Cobra application
	// that maps string keys to string values.
	//
	// The AddFlagStringToString function takes the following arguments:
	//
	// - persistent: a boolean indicating whether the flag is persistent
	//   or not
	// - p: a pointer to a map of string keys to string values
	// - name: the name of the flag
	// - shorthand: a shorthand string for the flag
	// - value: the default value of the flag
	// - usage: a description of the flag
	//
	// The AddFlagStringToString function does not return any value. It is used
	// to add a string flag to the Cobra application.
	//
	// The AddFlagStringToString function allocates memory for the returned
	// flag. The caller is responsible for freeing this memory when it is no
	// longer needed.
	AddFlagStringToString(persistent bool, p *map[string]string, name, shorthand string, value map[string]string, usage string)

	// NewCommand returns a new Cobra command with the given command name,
	// short description, long description, usage without command, and
	// example usage without command.
	//
	// The NewCommand function takes the following arguments:
	//
	// - cmd: the name of the command
	// - short: a short description of the command
	// - long: a long description of the command
	// - useWithoutCmd: the usage string without the command name
	// - exampleWithoutCmd: an example usage string without the command name
	//
	// The NewCommand function returns a pointer to a spfcbr.Command object.
	//
	// The NewCommand function does not modify the state of the Cobra application.
	//
	// The NewCommand function allocates memory for the returned Cobra command.
	// The caller is responsible for freeing this memory when it is no longer needed.
	NewCommand(cmd, short, long, useWithoutCmd, exampleWithoutCmd string) *spfcbr.Command
	// AddCommand adds one or more subcommands to the Cobra application.
	//
	// The AddCommand function takes one or more arguments. Each argument is a
	// pointer to a spfcbr.Command object.
	//
	// The AddCommand function does not return any value. It is used to add
	// subcommands to the Cobra application.
	AddCommand(subCmd ...*spfcbr.Command)

	// AddCommandCompletion adds a subcommand to the Cobra application
	// that prints the possible completions for the current command.
	//
	// The AddCommandCompletion function does not return any value. It is
	// used to add a completion subcommand to the Cobra application.
	//
	// The AddCommandCompletion function takes no arguments.
	AddCommandCompletion()
	// AddCommandConfigure adds a subcommand to the Cobra application
	// that configures the Cobra application.
	//
	// The AddCommandConfigure function takes three arguments:
	// - alias: an alias for the configure subcommand
	// - basename: the filename of the configuration file
	// - defaultConfig: a function that returns a reader with the default
	//   configuration
	//
	// The AddCommandConfigure function does not return any value. It is
	// designed to be used as a setter function, which means that the
	// function will not return until the Cobra application's logic has
	// been set.
	AddCommandConfigure(alias, basename string, defaultConfig func() io.Reader)
	// AddCommandPrintErrorCode adds a subcommand to the Cobra application
	// that prints the error code with package path related.
	//
	// The AddCommandPrintErrorCode function takes a single argument of type
	// FuncPrintErrorCode, which is a function that takes two arguments of
	// type string and prints the error code and the related package path.
	//
	// The AddCommandPrintErrorCode function does not return any value. It is
	// designed to be used as a setter function, which means that the
	// function will not return until the Cobra application's logic has
	// been set.
	AddCommandPrintErrorCode(fct FuncPrintErrorCode)

	// Execute executes the Cobra application's logic.
	//
	// The Execute function will execute the application's logic by
	// calling the Cobra application's root command's Execute function.
	//
	// The Execute function will return an error if the application's
	// logic encounters an error during execution.
	//
	// The Execute function does not return any other value. It is
	// designed to be used as a terminal function, which means that
	// the function will not return until the application's logic has
	// been executed or an error has been encountered.
	Execute() error

	// Cobra returns a new Cobra object.
	//
	// The Cobra object is returned with all its fields set to nil.
	// The caller is responsible for initializing the fields of the Cobra object.
	//
	// The Cobra object returned by this function is a root command of the Cobra application.
	// It is the top-level command of the application, and it is responsible for
	// executing the application's logic.
	//
	// The Cobra object returned by this function is not configured by default.
	// The caller is responsible for configuring the Cobra object before executing
	// the application's logic.
	Cobra() *spfcbr.Command

	// ConfigureCheckArgs checks if the arguments passed to the Configure command are valid.
	//
	// It returns an error if the arguments are invalid or if there is a problem with the
	// configuration file generation.
	//
	// basename is the base name of the file to be generated. If basename is empty, the
	// package name will be used as the base name.
	//
	// args is the list of arguments passed to the Configure command.
	//
	// The function returns an error if anything goes wrong.
	ConfigureCheckArgs(basename string, args []string) error
	// ConfigureWriteConfig generates a configuration file based on giving existing config flag
	// override by passed flag in command line and completed with default for non existing values.
	//
	// basename is the base name of the file to be generated. If basename is empty, the
	// package name will be used as the base name.
	//
	// defaultConfig is a function to read the default configuration.
	//
	// printMsg is a function to print the success message after generating the configuration file.
	// If printMsg is nil, the function will not be called.
	//
	// The function returns an error if anything goes wrong.
	ConfigureWriteConfig(basename string, defaultConfig func() io.Reader, printMsg func(pkg, file string)) error
}

Cobra is the main interface for building CLI applications with enhanced features. It wraps spf13/cobra with additional functionality for logging, configuration, and version management while maintaining thread-safety through instance-based design.

func New

func New() Cobra

New returns a new Cobra object.

The Cobra object is returned with all its fields set to nil. The caller is responsible for initializing the fields of the Cobra object.

type FuncInit

type FuncInit func()

FuncInit is a function type for initialization callbacks. It is called during cobra initialization to perform custom setup operations.

type FuncLogger

type FuncLogger func() liblog.Logger

FuncLogger is a function type that returns a logger instance. This pattern allows for lazy initialization of the logger and dependency injection.

type FuncPrintErrorCode

type FuncPrintErrorCode func(item, value string)

FuncPrintErrorCode is a function type for printing error code information. It receives an item identifier and its corresponding value for display.

type FuncViper

type FuncViper func() libvpr.Viper

FuncViper is a function type that returns a viper configuration instance. This pattern allows for lazy initialization and dependency injection of configuration.

Jump to

Keyboard shortcuts

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