lmcli/pkg/cli/config.go

64 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 InitializeConfig() *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 {
Fatal("Could not open config file for writing: %v", err)
return nil
}
fmt.Printf("Writing default configuration to: %s\n", configFile)
bytes, _ := yaml.Marshal(defaultConfig)
_, err = file.Write(bytes)
if err != nil {
Fatal("Could not save default configuratoin: %v", err)
return nil
}
} else if err != nil {
Fatal("Could not read config file: %v", err)
return nil
}
config := &Config{}
yaml.Unmarshal(configBytes, config)
return config
}