config.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. // Package config loads and resolves ZenMux accounts from a YAML file.
  2. package config
  3. import (
  4. "errors"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path/filepath"
  9. "sort"
  10. "strings"
  11. "gopkg.in/yaml.v3"
  12. )
  13. // Account identifies a single ZenMux account the CLI can query.
  14. type Account struct {
  15. Name string `yaml:"name"`
  16. APIKey string `yaml:"api_key"`
  17. }
  18. // Config is the on-disk YAML schema.
  19. type Config struct {
  20. Accounts []Account `yaml:"accounts"`
  21. }
  22. // Sentinel errors. Wrapped with %w so callers can distinguish them.
  23. var (
  24. ErrParse = errors.New("config parse error")
  25. ErrAccountNotFound = errors.New("account not found")
  26. ErrNoAccount = errors.New("no account available")
  27. )
  28. // DefaultPath returns the default config file path, honoring XDG_CONFIG_HOME
  29. // when set, and falling back to ~/.config/zenmux-usage/config.yaml.
  30. // Returns an empty string when the home directory cannot be determined.
  31. func DefaultPath() string {
  32. if xdg := os.Getenv("XDG_CONFIG_HOME"); xdg != "" {
  33. return filepath.Join(xdg, "zenmux-usage", "config.yaml")
  34. }
  35. home, err := os.UserHomeDir()
  36. if err != nil || home == "" {
  37. return ""
  38. }
  39. return filepath.Join(home, ".config", "zenmux-usage", "config.yaml")
  40. }
  41. // Load reads path, parses the YAML, validates the schema, and writes any
  42. // non-fatal warnings (e.g. unknown fields) to warnW.
  43. //
  44. // Returns a wrapped ErrParse on any schema or validation failure.
  45. // Filesystem errors (missing file, permission denied) are returned as-is
  46. // so callers can distinguish "no config" from "bad config".
  47. func Load(path string, warnW io.Writer) (*Config, error) {
  48. raw, err := os.ReadFile(path)
  49. if err != nil {
  50. return nil, err
  51. }
  52. // Decode into a generic map to detect unknown keys, then into the typed
  53. // struct for the actual parse. yaml.v3's KnownFields(true) would fail
  54. // hard on unknowns, but we want a warning, not a fatal error.
  55. var loose map[string]any
  56. if err := yaml.Unmarshal(raw, &loose); err != nil {
  57. return nil, fmt.Errorf("%w: %v", ErrParse, err)
  58. }
  59. var cfg Config
  60. if err := yaml.Unmarshal(raw, &cfg); err != nil {
  61. return nil, fmt.Errorf("%w: %v", ErrParse, err)
  62. }
  63. warnUnknownFields(loose, warnW)
  64. if err := validate(&cfg); err != nil {
  65. return nil, err
  66. }
  67. return &cfg, nil
  68. }
  69. func validate(cfg *Config) error {
  70. if len(cfg.Accounts) == 0 {
  71. return fmt.Errorf("%w: accounts list must contain at least one entry", ErrParse)
  72. }
  73. seen := make(map[string]struct{}, len(cfg.Accounts))
  74. for i, acc := range cfg.Accounts {
  75. if strings.TrimSpace(acc.Name) == "" {
  76. return fmt.Errorf("%w: accounts[%d].name is empty", ErrParse, i)
  77. }
  78. if strings.TrimSpace(acc.APIKey) == "" {
  79. return fmt.Errorf("%w: accounts[%d] (%q) has empty api_key", ErrParse, i, acc.Name)
  80. }
  81. if _, dup := seen[acc.Name]; dup {
  82. return fmt.Errorf("%w: duplicate account name %q", ErrParse, acc.Name)
  83. }
  84. seen[acc.Name] = struct{}{}
  85. }
  86. return nil
  87. }
  88. var (
  89. knownTopLevel = map[string]struct{}{"accounts": {}}
  90. knownAccount = map[string]struct{}{"name": {}, "api_key": {}}
  91. )
  92. // warnUnknownFields writes one warning line to warnW for each unrecognized
  93. // top-level key and each unrecognized per-account key. Nothing is emitted
  94. // when warnW is nil.
  95. func warnUnknownFields(loose map[string]any, warnW io.Writer) {
  96. if warnW == nil {
  97. return
  98. }
  99. var unknownTop []string
  100. for k := range loose {
  101. if _, ok := knownTopLevel[k]; !ok {
  102. unknownTop = append(unknownTop, k)
  103. }
  104. }
  105. sort.Strings(unknownTop)
  106. for _, k := range unknownTop {
  107. fmt.Fprintf(warnW, "zenmux-usage: warning: unknown config field %q (ignored)\n", k)
  108. }
  109. rawAccounts, ok := loose["accounts"].([]any)
  110. if !ok {
  111. return
  112. }
  113. for i, raw := range rawAccounts {
  114. accMap, ok := raw.(map[string]any)
  115. if !ok {
  116. continue
  117. }
  118. var unknownAcc []string
  119. for k := range accMap {
  120. if _, ok := knownAccount[k]; !ok {
  121. unknownAcc = append(unknownAcc, k)
  122. }
  123. }
  124. sort.Strings(unknownAcc)
  125. for _, k := range unknownAcc {
  126. fmt.Fprintf(warnW, "zenmux-usage: warning: unknown field %q in accounts[%d] (ignored)\n", k, i)
  127. }
  128. }
  129. }
  130. // ResolveFlags captures the CLI inputs that influence account resolution.
  131. type ResolveFlags struct {
  132. APIKey string // --api-key value, empty when unset
  133. AccountName string // --account value, empty when unset
  134. EnvAPIKey string // ZENMUX_MANAGEMENT_API_KEY, empty when unset
  135. }
  136. // Resolve produces the ordered list of accounts to fetch, encoding the
  137. // precedence rules from the spec:
  138. //
  139. // 1. flags.APIKey set → a single synthetic "cli" account.
  140. // 2. cfg is non-nil → all accounts, optionally filtered by flags.AccountName.
  141. // 3. flags.EnvAPIKey set → a single synthetic "env" account.
  142. // 4. Otherwise → ErrNoAccount.
  143. //
  144. // An unknown AccountName returns a wrapped ErrAccountNotFound.
  145. func Resolve(cfg *Config, flags ResolveFlags) ([]Account, error) {
  146. if flags.APIKey != "" {
  147. return []Account{{Name: "cli", APIKey: flags.APIKey}}, nil
  148. }
  149. if cfg != nil {
  150. if flags.AccountName != "" {
  151. for _, acc := range cfg.Accounts {
  152. if acc.Name == flags.AccountName {
  153. return []Account{acc}, nil
  154. }
  155. }
  156. available := make([]string, len(cfg.Accounts))
  157. for i, acc := range cfg.Accounts {
  158. available[i] = acc.Name
  159. }
  160. return nil, fmt.Errorf("%w: %q (available: %s)",
  161. ErrAccountNotFound, flags.AccountName, strings.Join(available, ", "))
  162. }
  163. out := make([]Account, len(cfg.Accounts))
  164. copy(out, cfg.Accounts)
  165. return out, nil
  166. }
  167. if flags.EnvAPIKey != "" {
  168. return []Account{{Name: "env", APIKey: flags.EnvAPIKey}}, nil
  169. }
  170. return nil, ErrNoAccount
  171. }