65 lines
1.3 KiB
Go
65 lines
1.3 KiB
Go
package cli
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/go-yaml/yaml"
|
|
)
|
|
|
|
type Config struct {
|
|
OpenAI struct {
|
|
APIKey string `yaml:"apiKey"`
|
|
} `yaml:"openai"`
|
|
}
|
|
|
|
func getConfigDir() string {
|
|
var configDir string
|
|
|
|
xdgConfigHome := os.Getenv("XDG_CONFIG_HOME")
|
|
if xdgConfigHome != "" {
|
|
configDir = filepath.Join(xdgConfigHome, "lmcli")
|
|
} else {
|
|
userHomeDir, _ := os.UserHomeDir()
|
|
configDir = filepath.Join(userHomeDir, ".config/lmcli")
|
|
}
|
|
|
|
os.MkdirAll(configDir, 0755)
|
|
return configDir
|
|
}
|
|
|
|
func LoadConfig() *Config {
|
|
configFile := filepath.Join(getConfigDir(), "config.yaml")
|
|
|
|
configBytes, err := os.ReadFile(configFile)
|
|
if os.IsNotExist(err) {
|
|
defaultConfig := &Config{}
|
|
defaultConfig.OpenAI.APIKey = "your_key_here"
|
|
|
|
|
|
file, err := os.Create(configFile)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Could not open config file for writing: %v", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
fmt.Printf("Writing default configuration to: %s\n", configFile)
|
|
|
|
bytes, _ := yaml.Marshal(defaultConfig)
|
|
|
|
_, err = file.Write(bytes)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Could not save default configuratoin: %v", err)
|
|
os.Exit(1)
|
|
}
|
|
} else if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Could not read config file: %v", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
config := &Config{}
|
|
yaml.Unmarshal(configBytes, config)
|
|
return config
|
|
}
|