internal/provider_migrate.go

301 lines · 8222 bytes

  1package internal
  2
  3import (
  4	"fmt"
  5	"os"
  6	"path/filepath"
  7	"sort"
  8	"strings"
  9)
 10
 11const stackedProviderConfigValue = "stacked"
 12
 13func isStackedProviderConfig(raw string) bool {
 14	switch strings.ToLower(strings.TrimSpace(raw)) {
 15	case "stacked", "stack", "auto", "all":
 16		return true
 17	default:
 18		return false
 19	}
 20}
 21
 22func isFactoryDefaultProvider(raw string) bool {
 23	raw = strings.TrimSpace(raw)
 24	if raw == "" {
 25		return true
 26	}
 27	if isStackedProviderConfig(raw) {
 28		return true
 29	}
 30
 31	names, declined := parseProviderConfig(raw)
 32	if declined {
 33		return false
 34	}
 35	switch len(names) {
 36	case 0:
 37		return true
 38	case 1:
 39		switch names[0] {
 40		case "senshi", "allanime":
 41			return true
 42		}
 43	}
 44	return false
 45}
 46
 47func providerListsEqual(a, b []string) bool {
 48	if len(a) != len(b) {
 49		return false
 50	}
 51	for i := range a {
 52		if a[i] != b[i] {
 53			return false
 54		}
 55	}
 56	return true
 57}
 58
 59func migrateProviderConfig(raw string) (string, bool) {
 60	raw = strings.TrimSpace(raw)
 61	if isFactoryDefaultProvider(raw) {
 62		if raw == stackedProviderConfigValue {
 63			return raw, false
 64		}
 65		return stackedProviderConfigValue, true
 66	}
 67
 68	if isStackedProviderConfig(raw) {
 69		if raw != stackedProviderConfigValue {
 70			return stackedProviderConfigValue, true
 71		}
 72		return raw, false
 73	}
 74
 75	names, declined := parseProviderConfig(raw)
 76	if len(names) > 1 {
 77		return stackedProviderConfigValue, true
 78	}
 79
 80	canonical := canonicalProviderConfigValue(raw)
 81	if canonical != raw {
 82		return canonical, true
 83	}
 84	_ = declined
 85	return raw, false
 86}
 87
 88func readStoredCurdVersion(storagePath string) string {
 89	path := storageVersionFilePath(storagePath)
 90	raw, err := os.ReadFile(path)
 91	if err != nil {
 92		return ""
 93	}
 94	return strings.TrimSpace(string(raw))
 95}
 96
 97func writeStoredCurdVersion(storagePath, version string) error {
 98	storagePath = strings.TrimSpace(storagePath)
 99	version = strings.TrimSpace(version)
100	if storagePath == "" || version == "" {
101		return nil
102	}
103	if err := os.MkdirAll(storagePath, 0755); err != nil {
104		return err
105	}
106	return os.WriteFile(storageVersionFilePath(storagePath), []byte(version+"\n"), 0644)
107}
108
109// configOptionsIntroducedInVersion maps config keys to the first curd release that
110// introduced them. Only these keys are eligible for automatic append on upgrade.
111// Baseline options (Player, StoragePath, …) are NOT listed — they only appear via
112// createDefaultConfig for brand-new installs, never re-appended into sparse configs.
113//
114// When adding a new option:
115//  1. Add it to CurdConfig + defaultConfigMap()
116//  2. Register it here under the release version that ships it
117//  3. Bump VERSION.txt so MigrateOnVersionUpgrade runs for existing users
118func configOptionsIntroducedInVersion() map[string]string {
119	return map[string]string{
120		// 2.0.3 — playback fallback timeout + vim selection motions
121		"MpvPlaybackStartTimeout": "2.0.3",
122		"VimKeys":                 "2.0.3",
123		// 2.0.4 — idle background update checks
124		"CheckUpdates": "2.0.4",
125		// 2.0.5 — MPV episode playlist + alternate audio entries
126		"MpvEpisodePlaylist": "2.0.5",
127	}
128}
129
130// injectConfigOptionsSince appends defaults for options introduced in versions
131// (fromVersion, toVersion] that are still missing from configMap.
132// Example: from 2.0.2 → 2.0.3 injects only keys introduced in 2.0.3, not every
133// historical default.
134func injectConfigOptionsSince(configMap map[string]string, fromVersion, toVersion string) []string {
135	if configMap == nil {
136		return nil
137	}
138	defaults := defaultConfigMap()
139	introduced := configOptionsIntroducedInVersion()
140
141	keys := make([]string, 0, len(introduced))
142	for key := range introduced {
143		keys = append(keys, key)
144	}
145	sort.Strings(keys)
146
147	added := make([]string, 0)
148	for _, key := range keys {
149		since := introduced[key]
150		// Only options born after the user's previous version and at/before this release.
151		if !versionLess(fromVersion, since) {
152			continue // introduced at or before fromVersion — user already "passed" that release
153		}
154		if !versionLessOrEqual(since, toVersion) {
155			continue // not shipped yet in toVersion
156		}
157		if _, exists := configMap[key]; exists {
158			continue
159		}
160		value, ok := defaults[key]
161		if !ok {
162			continue
163		}
164		configMap[key] = value
165		added = append(added, key)
166	}
167	return added
168}
169
170// appendConfigKeys appends only the given keys to the config file so existing
171// user options and ordering are left untouched.
172func appendConfigKeys(configPath string, configMap map[string]string, keys []string) error {
173	if strings.TrimSpace(configPath) == "" || len(keys) == 0 {
174		return nil
175	}
176	file, err := os.OpenFile(configPath, os.O_APPEND|os.O_WRONLY, 0644)
177	if err != nil {
178		return err
179	}
180	defer file.Close()
181
182	for _, key := range keys {
183		value, ok := configMap[key]
184		if !ok {
185			continue
186		}
187		if _, err := fmt.Fprintf(file, "%s=%s\n", key, value); err != nil {
188			return err
189		}
190	}
191	return nil
192}
193
194// MigrateOnVersionUpgrade updates stored state and config when curd is upgraded.
195// On version change it appends only config options registered as introduced in
196// versions (storedVersion, appVersion], then runs provider migrations.
197// Same-version launches do not rewrite the config file.
198// Returns whether the config file was updated.
199func MigrateOnVersionUpgrade(configPath string, config *CurdConfig, appVersion string) (bool, error) {
200	if config == nil {
201		return false, nil
202	}
203
204	appVersion = strings.TrimSpace(appVersion)
205	if appVersion == "" {
206		appVersion = CurdVersion()
207	}
208
209	storagePath := os.ExpandEnv(config.StoragePath)
210	if storagePath == "" {
211		storagePath = filepath.Join(os.ExpandEnv("$HOME"), ".local", "share", "curd")
212	}
213
214	storedVersion := readStoredCurdVersion(storagePath)
215	configUpdated := false
216	versionChanged := storedVersion != appVersion
217
218	if versionChanged && strings.TrimSpace(configPath) != "" {
219		configMap, err := LoadConfigFromFile(configPath)
220		if err != nil {
221			return false, err
222		}
223
224		// Respect AddMissingOptions=false as a hard opt-out of writing new keys.
225		addMissing := true
226		if config != nil {
227			addMissing = config.AddMissingOptions
228		}
229		if val, exists := configMap["AddMissingOptions"]; exists {
230			if parsed, parseErr := parseConfigBool(val); parseErr == nil {
231				addMissing = parsed
232			}
233		}
234
235		if addMissing {
236			if added := injectConfigOptionsSince(configMap, storedVersion, appVersion); len(added) > 0 {
237				if err := appendConfigKeys(configPath, configMap, added); err != nil {
238					return false, fmt.Errorf("append new config options: %w", err)
239				}
240				configUpdated = true
241				Log(fmt.Sprintf("Injected config options for upgrade %s → %s: %s",
242					storedVersion, appVersion, strings.Join(added, ", ")))
243			}
244		}
245
246		if nextProvider, changed := migrateProviderConfig(configMap["Provider"]); changed {
247			configMap["Provider"] = nextProvider
248			// Provider value already exists in the file — rewrite the full map once.
249			if err := SaveConfigToFile(configPath, configMap); err != nil {
250				return configUpdated, err
251			}
252			configUpdated = true
253		}
254
255		// Refresh in-memory config so new keys (e.g. VimKeys) apply immediately.
256		next := PopulateConfig(configMap)
257		normalizeTrackingConfig(&next)
258		*config = next
259	} else if versionChanged {
260		// No config path, still run in-memory provider migration.
261		if nextProvider, changed := migrateProviderConfig(config.Provider); changed {
262			config.Provider = nextProvider
263			configUpdated = true
264		}
265	}
266
267	if err := writeStoredCurdVersion(storagePath, appVersion); err != nil {
268		return configUpdated, fmt.Errorf("write curd version file: %w", err)
269	}
270
271	return configUpdated, nil
272}
273
274func parseConfigBool(value string) (bool, error) {
275	switch strings.ToLower(strings.TrimSpace(value)) {
276	case "true", "1", "yes", "y", "on":
277		return true, nil
278	case "false", "0", "no", "n", "off":
279		return false, nil
280	default:
281		return false, fmt.Errorf("invalid bool %q", value)
282	}
283}
284
285func providerConfigDisplayLabel(raw string) string {
286	if isStackedProviderConfig(raw) {
287		names := defaultEnabledProviderStack()
288		if len(names) == 0 {
289			return "Default with fallback"
290		}
291		return fmt.Sprintf("Default with fallback (%s)", strings.Join(names, " → "))
292	}
293	names, _ := parseProviderConfig(raw)
294	if len(names) == 1 {
295		return names[0]
296	}
297	if len(names) > 1 {
298		return strings.Join(names, " → ")
299	}
300	return raw
301}