config

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: May 16, 2025 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package config provides configuration handling for the gitbak application.

This package manages all configuration parameters for gitbak, including parsing command-line flags, loading environment variables, and providing default values. It ensures configuration values are consistent and valid before they are used by the application.

Core Components

  • Config: Main configuration type that holds all gitbak settings
  • VersionInfo: Type for version, commit, and build date information

Configuration Sources

Configuration values are loaded with the following precedence:

  1. Command-line flags (highest priority)
  2. Environment variables
  3. Default values (lowest priority)

Environment Variables

The following environment variables are supported:

INTERVAL_MINUTES   Minutes between commit checks (default: 5)
BRANCH_NAME        Branch name to use (default: gitbak-<timestamp>)
COMMIT_PREFIX      Commit message prefix (default: "[gitbak]")
CREATE_BRANCH      Whether to create a new branch (default: true)
CONTINUE_SESSION   Continue an existing gitbak session (default: false)
VERBOSE            Whether to show informational messages (default: true)
SHOW_NO_CHANGES    Show messages when no changes detected (default: false)
DEBUG              Enable debug logging (default: false)
REPO_PATH          Path to repository (default: current directory)
MAX_RETRIES        Max consecutive identical errors before exiting (default: 3)
LOG_FILE           Path to log file (default: ~/.local/share/gitbak/logs/gitbak-<hash>.log)

Command-line Flags

The following command-line flags are supported:

-interval        Minutes between commit checks
-branch          Branch name to use
-prefix          Commit message prefix
-no-branch       Stay on current branch instead of creating a new one
-continue        Continue existing session
-show-no-changes Show messages when no changes detected
-quiet           Hide informational messages
-repo            Path to repository
-max-retries     Max consecutive identical errors before exiting
-debug           Enable debug logging
-log-file        Path to log file
-version         Print version information and exit
-logo            Display ASCII logo and exit

Usage

Basic usage pattern:

cfg := config.New()
cfg.LoadFromEnvironment()

if err := cfg.ParseFlags(); err != nil {
    // Handle error
}

// Configuration is now ready to use
fmt.Printf("Interval: %.2f minutes\n", cfg.IntervalMinutes)
fmt.Printf("Branch: %s\n", cfg.BranchName)

Thread Safety

The Config type is not designed to be thread-safe. Configuration is typically loaded at startup and then used in a read-only fashion by the application. Concurrent modifications to a Config instance are not supported.

Future improvements may include thread-safe access patterns (in the vein of the ThreadSafeConfig)- but for now, the focus is on simplicity and ease of use.

Index

Constants

View Source
const (
	// DefaultIntervalMinutes is the default time (in minutes) between checking for changes.
	// This interval determines how frequently gitbak looks for changes to commit.
	// Lower values provide more frequent checkpoints but can increase resource usage.
	// The value can be a fractional number (e.g., 0.5 for 30 seconds).
	DefaultIntervalMinutes = 5.0

	// DefaultCommitPrefix is the default prefix added to all commit messages.
	// This prefix helps identify commits made by gitbak and is used to extract
	// commit numbers when continuing a session. The commit message format is:
	// "[gitbak] Automatic checkpoint #N (YYYY-MM-DD HH:MM:SS)"
	DefaultCommitPrefix = "[gitbak] Automatic checkpoint"

	// DefaultMaxRetries is the default number of consecutive identical errors
	// allowed before gitbak exits. A value of 0 means retry indefinitely.
	// The error counter resets when errors change or successful operations occur.
	DefaultMaxRetries = 3
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {

	// RepoPath is the path to the Git repository to monitor.
	// If empty, the current working directory is used.
	RepoPath string

	// IntervalMinutes is how often (in minutes) to check for changes.
	// Uses float64 to support fractional minutes (e.g., 0.5 for 30 seconds).
	IntervalMinutes float64

	// BranchName is the Git branch to use for checkpoint commits.
	// If empty and CreateBranch is true, a timestamp-based name is generated.
	BranchName string

	// CommitPrefix is prepended to all commit messages.
	// Used to identify gitbak commits and extract commit numbers.
	CommitPrefix string

	// CreateBranch determines whether to create a new branch or use existing one.
	// If true, a new branch named BranchName will be created.
	CreateBranch bool

	// ContinueSession enables continuation mode for resuming a previous session.
	// When true, gitbak finds the last commit number and continues numbering from there.
	ContinueSession bool

	// Verbose controls the amount of informational output.
	// When true, gitbak provides detailed status updates.
	Verbose bool

	// ShowNoChanges determines whether to report when no changes are detected.
	// When true, gitbak logs a message at each interval even if nothing changed.
	ShowNoChanges bool

	// NonInteractive disables any prompts and uses default responses.
	// Useful for running gitbak in automated environments.
	NonInteractive bool

	// MaxRetries defines how many consecutive identical errors are allowed before exiting.
	// A value of 0 means retry indefinitely.
	// Errors of different types or successful operations reset this counter.
	MaxRetries int

	// Debug enables detailed logging.
	// When true, gitbak logs additional information helpful for troubleshooting.
	Debug bool

	// LogFile specifies where to write debug logs.
	// If empty, logs are written to a default location based on repository path.
	LogFile string

	// Version indicates whether to show version information and exit.
	// When true, gitbak prints version details and exits without running.
	Version bool

	// When true, gitbak prints the logo and exits without running.
	ShowLogo bool

	// ShowHelp indicates whether to display the help message and exit.
	// When true, gitbak prints help information and exits without running.
	ShowHelp bool

	// VersionInfo contains version, commit, and build date information.
	// This is typically injected at build time.
	VersionInfo VersionInfo

	// ParsedNoBranch tracks the state of the -no-branch flag.
	// Used during flag parsing to handle flag inversion.
	ParsedNoBranch *bool

	// ParsedQuiet tracks the state of the -quiet flag.
	// Used during flag parsing to handle flag inversion.
	ParsedQuiet *bool
}

Config holds all gitbak application settings. This struct combines settings from command-line flags, environment variables, and default values to control all aspects of gitbak behavior.

func New

func New() *Config

New creates a new Config with default values

func (*Config) Config

func (c *Config) Config() Config

Migration helper for the standard Config type to implement ConfigProvider This allows using a regular Config as a ConfigProvider during transition.

func (*Config) Finalize

func (c *Config) Finalize() error

Finalize validates and finalizes the configuration

func (*Config) LoadFromEnvironment

func (c *Config) LoadFromEnvironment()

LoadFromEnvironment updates config from environment variables

func (*Config) ParseFlags

func (c *Config) ParseFlags() error

ParseFlags parses the command-line arguments and updates the config

func (*Config) PrintUsage

func (c *Config) PrintUsage(fs *flag.FlagSet, w io.Writer)

PrintUsage prints a formatted help message with command descriptions, examples, and grouped flags

func (*Config) SetupFlags

func (c *Config) SetupFlags(fs *flag.FlagSet)

SetupFlags sets up command-line flags to override config values

func (*Config) SetupTestFlags

func (c *Config) SetupTestFlags(fs *flag.FlagSet)

SetupTestFlags conditionally adds test-specific flags to the flag set.

type ConfigAdapter

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

ConfigAdapter implements the backward compatibility layer that allows existing code to continue working with Config while using the ThreadSafeConfig underneath.

func NewConfigAdapter

func NewConfigAdapter(provider ConfigProvider) (*ConfigAdapter, error)

NewConfigAdapter creates an adapter for the given provider. Returns an error if the provider is nil.

func (*ConfigAdapter) Access

func (ca *ConfigAdapter) Access(access func(cfg Config) error) error

Access forwards Config object access to the provider. This is a helper method that allows safe access to the underlying configuration, particularly useful during refactoring.

func (*ConfigAdapter) GetRepoPath

func (ca *ConfigAdapter) GetRepoPath() string

GetRepoPath is an example of a convenient accessor. Accessors like this can be added as needed during refactoring to allow for gradual migration without breaking existing code.

type ConfigProvider

type ConfigProvider interface {
	// Config returns the current configuration
	Config() Config
}

ConfigProvider defines an interface for retrieving configuration. This allows us to use either a regular Config or ThreadSafeConfig interchangeably throughout the application.

type ThreadSafeConfig

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

ThreadSafeConfig provides thread-safe access to configuration settings. It uses read-write locks to ensure safe concurrent access while maintaining the idiomatic Go approach to configuration management.

func NewThreadSafeConfig

func NewThreadSafeConfig() *ThreadSafeConfig

NewThreadSafeConfig creates a new thread-safe configuration with default values. This is the starting point for creating a thread-safe configuration instance.

func (*ThreadSafeConfig) Config

func (c *ThreadSafeConfig) Config() Config

Config returns a copy of the current configuration. This method is safe for concurrent use and can be called from any goroutine after Initialize() has been called.

func (*ThreadSafeConfig) Initialize

func (c *ThreadSafeConfig) Initialize() error

Initialize prepares the configuration for use by loading from environment, parsing flags, and finalizing. This method should only be called once, typically during application startup.

func (*ThreadSafeConfig) IsReady

func (c *ThreadSafeConfig) IsReady() bool

IsReady returns whether the configuration has been successfully initialized and is ready for use.

func (*ThreadSafeConfig) PrintUsage

func (c *ThreadSafeConfig) PrintUsage(w io.Writer)

PrintUsage prints a formatted help message with flag descriptions. This method is primarily used for command-line help and is thread-safe.

func (*ThreadSafeConfig) WithVersionInfo

func (c *ThreadSafeConfig) WithVersionInfo(info VersionInfo) *ThreadSafeConfig

WithVersionInfo sets the version info on the config and returns the config. This follows the builder pattern for configuration setup.

type VersionInfo

type VersionInfo struct {
	// Version is the semantic version number (e.g., "v1.2.3").
	Version string

	// Commit is the Git commit hash from which the binary was built.
	Commit string

	// Date is the build timestamp in human-readable format.
	Date string
}

VersionInfo contains build-time version metadata. This information is typically injected during the build process and is used to display version information to users.

Jump to

Keyboard shortcuts

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