internal/config.go

188 lines · 5294 bytes

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