internal/config.go

212 lines · 5937 bytes

  1package internal
  2
  3import (
  4	"bufio"
  5	"fmt"
  6	"os"
  7	"path/filepath"
  8	"reflect"
  9	"strconv"
 10	"strings"
 11)
 12
 13// CurdConfig struct with field names that match the config keys
 14type CurdConfig struct {
 15	Player                  string `config:"Player"`
 16	SubsLanguage            string `config:"SubsLanguage"`
 17	SubOrDub                string `config:"SubOrDub"`
 18	StoragePath             string `config:"StoragePath"`
 19	PercentageToMarkComplete int    `config:"PercentageToMarkComplete"`
 20	NextEpisodePrompt       bool   `config:"NextEpisodePrompt"`
 21	SkipOp                  bool   `config:"SkipOp"`
 22	SkipEd                  bool   `config:"SkipEd"`
 23	SkipFiller              bool   `config:"SkipFiller"`
 24	SkipRecap               bool   `config:"SkipRecap"`
 25	RofiSelection           bool   `config:"RofiSelection"`
 26	ScoreOnCompletion       bool   `config:"ScoreOnCompletion"`
 27	SaveMpvSpeed            bool   `config:"SaveMpvSpeed"`
 28	DiscordPresence         bool   `config:"DiscordPresence"`
 29}
 30
 31// Default configuration values as a map
 32func defaultConfigMap() map[string]string {
 33	return map[string]string{
 34		"Player":                  "mpv",
 35		"StoragePath":             "$HOME/.local/share/curd",
 36		"SubsLanguage":            "english",
 37		"SubOrDub":                "sub",
 38		"PercentageToMarkComplete": "85",
 39		"NextEpisodePrompt":       "false",
 40		"SkipOp":                  "true",
 41		"SkipEd":                  "true",
 42		"SkipFiller":              "true",
 43		"SkipRecap":               "true",
 44		"RofiSelection":           "false",
 45		"ScoreOnCompletion":       "true",
 46		"SaveMpvSpeed":            "true",
 47		"DiscordPresence":         "true",
 48	}
 49}
 50
 51var globalConfig *CurdConfig
 52
 53func SetGlobalConfig(config *CurdConfig) {
 54	globalConfig = config
 55}
 56
 57func GetGlobalConfig() *CurdConfig {
 58	return globalConfig
 59}
 60
 61
 62// LoadConfig reads or creates the config file, adds missing fields, and returns the populated CurdConfig struct
 63func LoadConfig(configPath string) (CurdConfig, error) {
 64	configPath = os.ExpandEnv(configPath) // Substitute environment variables like $HOME
 65
 66	// Check if config file exists
 67	if _, err := os.Stat(configPath); os.IsNotExist(err) {
 68		// Create the config file with default values if it doesn't exist
 69		CurdOut("Config file not found. Creating default config...")
 70		if err := createDefaultConfig(configPath); err != nil {
 71			return CurdConfig{}, fmt.Errorf("error creating default config file: %v", err)
 72		}
 73	}
 74
 75	// Load the config from file
 76	configMap, err := loadConfigFromFile(configPath)
 77	if err != nil {
 78		return CurdConfig{}, fmt.Errorf("error loading config file: %v", err)
 79	}
 80
 81	// Add missing fields to the config map
 82	updated := false
 83	defaultConfigMap := defaultConfigMap()
 84	for key, defaultValue := range defaultConfigMap {
 85		if _, exists := configMap[key]; !exists {
 86			configMap[key] = defaultValue
 87			updated = true
 88		}
 89	}
 90
 91	// Write updated config back to file if there were any missing fields
 92	if updated {
 93		if err := saveConfigToFile(configPath, configMap); err != nil {
 94			return CurdConfig{}, fmt.Errorf("error saving updated config file: %v", err)
 95		}
 96	}
 97
 98	// Populate the CurdConfig struct from the config map
 99	config := populateConfig(configMap)
100
101	return config, nil
102}
103
104// Create a config file with default values in key=value format
105// Ensure the directory exists before creating the file
106func createDefaultConfig(path string) error {
107	defaultConfig := defaultConfigMap()
108
109	// Ensure the directory exists
110	dir := filepath.Dir(path)
111	if err := os.MkdirAll(dir, 0755); err != nil {
112		return fmt.Errorf("error creating directory: %v", err)
113	}
114
115	file, err := os.Create(path)
116	if err != nil {
117		return fmt.Errorf("error creating file: %v", err)
118	}
119	defer file.Close()
120
121	writer := bufio.NewWriter(file)
122	for key, value := range defaultConfig {
123		line := fmt.Sprintf("%s=%s\n", key, value)
124		if _, err := writer.WriteString(line); err != nil {
125			return fmt.Errorf("error writing to file: %v", err)
126		}
127	}
128	if err := writer.Flush(); err != nil {
129		return fmt.Errorf("error flushing writer: %v", err)
130	}
131	return nil
132}
133
134// Load config file from disk into a map (key=value format)
135func loadConfigFromFile(path string) (map[string]string, error) {
136	file, err := os.Open(path)
137	if err != nil {
138		return nil, err
139	}
140	defer file.Close()
141
142	configMap := make(map[string]string)
143	scanner := bufio.NewScanner(file)
144
145	for scanner.Scan() {
146		line := strings.TrimSpace(scanner.Text())
147		if line == "" || strings.HasPrefix(line, "#") {
148			continue // Skip empty lines and comments
149		}
150
151		parts := strings.SplitN(line, "=", 2)
152		if len(parts) == 2 {
153			key := strings.TrimSpace(parts[0])
154			value := strings.TrimSpace(parts[1])
155			configMap[key] = value
156		}
157	}
158
159	if err := scanner.Err(); err != nil {
160		return nil, err
161	}
162
163	return configMap, nil
164}
165
166// Save updated config map to file in key=value format
167func saveConfigToFile(path string, configMap map[string]string) error {
168	file, err := os.Create(path)
169	if err != nil {
170		return err
171	}
172	defer file.Close()
173
174	writer := bufio.NewWriter(file)
175	for key, value := range configMap {
176		line := fmt.Sprintf("%s=%s\n", key, value)
177		if _, err := writer.WriteString(line); err != nil {
178			return err
179		}
180	}
181	return writer.Flush()
182}
183
184// Populate the CurdConfig struct from a map
185func populateConfig(configMap map[string]string) CurdConfig {
186	config := CurdConfig{}
187	configValue := reflect.ValueOf(&config).Elem()
188
189	for i := 0; i < configValue.NumField(); i++ {
190		field := configValue.Type().Field(i)
191		tag := field.Tag.Get("config")
192
193		if value, exists := configMap[tag]; exists {
194			fieldValue := configValue.FieldByName(field.Name)
195
196			if fieldValue.CanSet() {
197				switch fieldValue.Kind() {
198				case reflect.String:
199					fieldValue.SetString(value)
200				case reflect.Int:
201					intVal, _ := strconv.Atoi(value)
202					fieldValue.SetInt(int64(intVal))
203				case reflect.Bool:
204					boolVal, _ := strconv.ParseBool(value)
205					fieldValue.SetBool(boolVal)
206				}
207			}
208		}
209	}
210
211	return config
212}