gitFlow/internal/config/config.go
dimitar d52e0715f2 feat: phase 2 — CLI commands and configuration resolution
Add the Cobra-based command surface and the flag/env/config-file
resolution layer that all commands share.

Configuration (internal/config):
- Load() resolves settings with the documented precedence flags > env >
  config file > defaults, via viper: GITFLOW_-prefixed env vars with
  dot-to-underscore mapping, plus ~/.gitflow.yaml (or $GITFLOW_CONFIG)
- RegisterFlags/NewFlagSet own the flag definitions so every command and
  the tests share a single source of truth
- Config/Validate/Dump cover dir, interval, format (table/json/compact),
  exclude globs, max depth, worker count, and the AI block (enabled,
  provider, model, api_key_env, base_url); ConfigFile records the loaded
  path; Dump renders the effective config as human-readable YAML with the
  interval as a duration string

App orchestration (internal/app):
- New() validates the configuration at the boundary (fail fast)
- ScanOnce() runs discovery then a concurrent status scan, warning on
  stderr and continuing when discovery is only partially successful
  (e.g. permission-denied subtrees), and bundles everything into a
  ScanResult

CLI (cmd/gitflow):
- root command with scan / config / version subcommands
- scan: resolves config, prompts for the parent directory when stdin is a
  TTY and --dir was not given (per the README), runs a single pass, and
  renders the result — interim plain/JSON output until phase 3 lands the
  presenter package
- config: prints the effective configuration
- version: prints the build version (ldflags-injectable)
- signalContext() wires SIGINT/SIGTERM into a cancellable context for
  graceful shutdown

Testing:
- config: defaults, flag overrides, env overrides, flag-beats-env
  precedence, config file loading (including duration and slice values),
  GITFLOW_CONFIG path override, validation failures, and Dump output
- app: config validation on New, end-to-end ScanOnce over a real temp
  repo, and missing-directory errors

Verified: go build, go vet, go test -race, gofmt clean; manual smoke of
`gitflow version`, `gitflow config`, and `gitflow scan -d <dir>` against a
scratch directory with a dirty repo.
2026-08-02 08:38:55 +02:00

204 lines
5.9 KiB
Go

// Package config resolves and validates gitflow settings from CLI flags,
// environment variables, and an optional YAML configuration file.
//
// Precedence (highest first): flags, environment variables, config file,
// built-in defaults.
package config
import (
"errors"
"fmt"
"os"
"strings"
"time"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
)
// AIConfig holds AI agent settings.
type AIConfig struct {
Enabled bool `yaml:"enabled"`
Provider string `yaml:"provider"` // openai or ollama
Model string `yaml:"model"` // model name; empty lets the provider choose
APIKeyEnv string `yaml:"api_key_env"` // env var holding the API key
BaseURL string `yaml:"base_url"` // provider endpoint override
}
// Config is the fully resolved runtime configuration.
type Config struct {
Dir string `yaml:"dir"`
Interval time.Duration `yaml:"interval"`
Format string `yaml:"format"`
Exclude []string `yaml:"exclude,omitempty"`
MaxDepth int `yaml:"max_depth"`
Workers int `yaml:"workers"`
AI AIConfig `yaml:"ai"`
ConfigFile string `yaml:"-"` // path of the loaded config file, if any
}
// flagKeys maps CLI flag names to their viper keys.
var flagKeys = []struct{ flag, key string }{
{"dir", "dir"},
{"interval", "interval"},
{"format", "format"},
{"exclude", "exclude"},
{"max-depth", "max_depth"},
{"workers", "workers"},
{"ai", "ai.enabled"},
{"ai-provider", "ai.provider"},
{"ai-model", "ai.model"},
}
// RegisterFlags defines every gitflow flag on f. Call Load with the same
// FlagSet to resolve the effective configuration.
func RegisterFlags(f *pflag.FlagSet) {
f.StringP("dir", "d", ".", "parent directory to scan")
f.DurationP("interval", "i", 0, "rescan interval (e.g. 30s, 5m); 0 runs once")
f.StringP("format", "f", "table", "output format: table, json, or compact")
f.StringSlice("exclude", nil, "glob patterns of directories to skip (repeatable)")
f.Int("max-depth", 0, "maximum directory depth to scan (0 = unlimited)")
f.Int("workers", 8, "number of concurrent git scans")
f.Bool("ai", false, "enable AI suggestions")
f.String("ai-provider", "openai", "AI provider: openai or ollama")
f.String("ai-model", "gpt-4o", "AI model name")
}
// NewFlagSet returns a FlagSet with every gitflow flag registered.
func NewFlagSet() *pflag.FlagSet {
fs := pflag.NewFlagSet("gitflow", pflag.ContinueOnError)
RegisterFlags(fs)
return fs
}
// Load resolves the effective configuration from flags, environment, and
// config file, then validates it.
func Load(flags *pflag.FlagSet) (*Config, error) {
v := viper.New()
applyDefaults(v)
v.SetEnvPrefix("GITFLOW")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AutomaticEnv()
if err := readConfigFile(v); err != nil {
return nil, err
}
bindFlags(v, flags)
cfg := &Config{
Dir: v.GetString("dir"),
Interval: v.GetDuration("interval"),
Format: v.GetString("format"),
Exclude: v.GetStringSlice("exclude"),
MaxDepth: v.GetInt("max_depth"),
Workers: v.GetInt("workers"),
ConfigFile: v.ConfigFileUsed(),
AI: AIConfig{
Enabled: v.GetBool("ai.enabled"),
Provider: v.GetString("ai.provider"),
Model: v.GetString("ai.model"),
APIKeyEnv: v.GetString("ai.api_key_env"),
BaseURL: v.GetString("ai.base_url"),
},
}
if err := cfg.Validate(); err != nil {
return nil, err
}
return cfg, nil
}
func applyDefaults(v *viper.Viper) {
v.SetDefault("dir", ".")
v.SetDefault("interval", 0)
v.SetDefault("format", "table")
v.SetDefault("exclude", []string{})
v.SetDefault("max_depth", 0)
v.SetDefault("workers", 8)
v.SetDefault("ai.enabled", false)
v.SetDefault("ai.provider", "openai")
v.SetDefault("ai.model", "gpt-4o")
v.SetDefault("ai.api_key_env", "OPENAI_API_KEY")
v.SetDefault("ai.base_url", "")
}
// readConfigFile loads ~/.gitflow.yaml (or $GITFLOW_CONFIG when set). A
// missing config file is not an error; a malformed one is.
func readConfigFile(v *viper.Viper) error {
if path := os.Getenv("GITFLOW_CONFIG"); path != "" {
v.SetConfigFile(path)
} else {
v.SetConfigName(".gitflow")
v.SetConfigType("yaml")
v.AddConfigPath("$HOME")
v.AddConfigPath(".")
}
if err := v.ReadInConfig(); err != nil {
var notFound viper.ConfigFileNotFoundError
if errors.As(err, &notFound) {
return nil
}
return fmt.Errorf("config: %w", err)
}
return nil
}
func bindFlags(v *viper.Viper, flags *pflag.FlagSet) {
for _, fk := range flagKeys {
if fl := flags.Lookup(fk.flag); fl != nil {
_ = v.BindPFlag(fk.key, fl)
}
}
}
// Validate rejects configuration that cannot be used.
func (c *Config) Validate() error {
if c.Dir == "" {
return errors.New("config: dir must not be empty")
}
switch c.Format {
case "table", "json", "compact":
default:
return fmt.Errorf("config: unsupported format %q (want table, json, or compact)", c.Format)
}
if c.Interval < 0 {
return errors.New("config: interval must not be negative")
}
if c.MaxDepth < 0 {
return errors.New("config: max-depth must not be negative")
}
if c.Workers < 1 {
return errors.New("config: workers must be at least 1")
}
if c.AI.Enabled && c.AI.Provider == "" {
return errors.New("config: ai provider must not be empty")
}
return nil
}
// Dump renders the effective configuration as human-readable YAML, with the
// interval shown as a duration string.
func (c *Config) Dump() (string, error) {
v := map[string]any{
"config_file": c.ConfigFile,
"dir": c.Dir,
"interval": c.Interval.String(),
"format": c.Format,
"exclude": c.Exclude,
"max_depth": c.MaxDepth,
"workers": c.Workers,
"ai": map[string]any{
"enabled": c.AI.Enabled,
"provider": c.AI.Provider,
"model": c.AI.Model,
"api_key_env": c.AI.APIKeyEnv,
"base_url": c.AI.BaseURL,
},
}
out, err := yaml.Marshal(v)
if err != nil {
return "", err
}
return string(out), nil
}