package main import ( "errors" "fmt" "io/fs" "os" "github.com/adrg/xdg" "gopkg.in/yaml.v3" ) type config struct { Languages []struct { Name string `yaml:"name"` Timeframes []string `yaml:"timeframes"` } `yaml:"languages"` } func loadConfig() (*config, error) { cfgPath, err := xdg.ConfigFile("trending/config.yaml") if err != nil { return nil, fmt.Errorf("could not get config file path: %w", err) } fi, err := os.Open(cfgPath) if err != nil { if !errors.Is(err, fs.ErrNotExist) { return nil, fmt.Errorf("could not open config file: %w", err) } if err := createDefaultConfig(cfgPath); err != nil { return nil, fmt.Errorf("could not create default config: %w", err) } return loadConfig() } defer fi.Close() var cfg config if err := yaml.NewDecoder(fi).Decode(&cfg); err != nil { return nil, fmt.Errorf("could not decode config: %w", err) } return &cfg, nil } func createDefaultConfig(cfgPath string) error { fi, err := os.Create(cfgPath) if err != nil { return err } defer fi.Close() _, err = fi.Write(defaultConfig) return err } var defaultConfig = []byte(`languages: - name: go timeframes: - daily - weekly - monthly - name: rust timeframes: - daily - weekly - monthly `)