Add TOML config file support to mcrctl
Loads defaults from ~/.config/mcrctl.toml (or XDG_CONFIG_HOME). Resolution order: flag > env (MCR_TOKEN) > config file. Adds --config flag to specify an explicit path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
56
cmd/mcrctl/config.go
Normal file
56
cmd/mcrctl/config.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
toml "github.com/pelletier/go-toml/v2"
|
||||
)
|
||||
|
||||
// config holds CLI defaults loaded from a TOML file.
|
||||
type config struct {
|
||||
Server string `toml:"server"`
|
||||
GRPC string `toml:"grpc"`
|
||||
Token string `toml:"token"`
|
||||
CACert string `toml:"ca_cert"`
|
||||
}
|
||||
|
||||
// loadConfig reads a TOML config file from the given path. If path is
|
||||
// empty it searches the default location (~/.config/mcrctl.toml). A
|
||||
// missing file at the default location is not an error — an explicit
|
||||
// --config path that doesn't exist is.
|
||||
func loadConfig(path string) (config, error) {
|
||||
explicit := path != ""
|
||||
if !explicit {
|
||||
path = defaultConfigPath()
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(path) //nolint:gosec // operator-supplied config path
|
||||
if err != nil {
|
||||
if !explicit && os.IsNotExist(err) {
|
||||
return config{}, nil
|
||||
}
|
||||
return config{}, fmt.Errorf("reading config: %w", err)
|
||||
}
|
||||
|
||||
var cfg config
|
||||
if err := toml.Unmarshal(data, &cfg); err != nil {
|
||||
return config{}, fmt.Errorf("parsing config %s: %w", path, err)
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// defaultConfigPath returns ~/.config/mcrctl.toml, respecting
|
||||
// XDG_CONFIG_HOME if set.
|
||||
func defaultConfigPath() string {
|
||||
dir := os.Getenv("XDG_CONFIG_HOME")
|
||||
if dir == "" {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "mcrctl.toml"
|
||||
}
|
||||
dir = filepath.Join(home, ".config")
|
||||
}
|
||||
return filepath.Join(dir, "mcrctl.toml")
|
||||
}
|
||||
Reference in New Issue
Block a user