dotstate 0.3.4

A modern, secure, and user-friendly dotfile manager built with Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// Current version of the config file format.
/// Increment this when making breaking changes to the schema.
const CURRENT_VERSION: u32 = 1;

/// Repository setup mode
/// Determines how the repository was configured and how sync operations authenticate
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum RepoMode {
    /// Repository created/managed via GitHub API (requires token for sync)
    #[default]
    GitHub,
    /// User-provided repository (uses system git credentials for sync)
    Local,
}

/// Update check configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateConfig {
    /// Whether to check for updates on startup (default: true)
    #[serde(default = "default_update_check_enabled")]
    pub check_enabled: bool,
    /// Check interval in hours (default: 24)
    #[serde(default = "default_update_check_interval")]
    pub check_interval_hours: u64,
}

impl Default for UpdateConfig {
    fn default() -> Self {
        Self {
            check_enabled: default_update_check_enabled(),
            check_interval_hours: default_update_check_interval(),
        }
    }
}

fn default_update_check_enabled() -> bool {
    true
}

fn default_update_check_interval() -> u64 {
    24
}

/// Main configuration structure
/// Note: Profiles are stored in the repository manifest (.dotstate-profiles.toml), not in this config file.
/// This config only stores local settings like backup preferences and active profile name.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// Schema version for migration support. Missing = v0.
    #[serde(default)]
    pub version: u32,
    /// Repository setup mode (GitHub API or local/user-provided)
    #[serde(default)]
    pub repo_mode: RepoMode,
    /// GitHub repository information (only used in GitHub mode)
    pub github: Option<GitHubConfig>,
    /// Current active profile/set
    pub active_profile: String,
    /// Repository root path (where dotfiles are stored locally)
    pub repo_path: PathBuf,
    /// Repository name on GitHub (default: dotstate-storage)
    #[serde(default = "default_repo_name")]
    pub repo_name: String,
    /// Default branch name (default: main)
    #[serde(default = "default_branch_name")]
    pub default_branch: String,
    /// Whether to create backups before syncing (default: true)
    #[serde(default = "default_backup_enabled")]
    pub backup_enabled: bool,
    /// Whether the active profile is currently activated (symlinks created)
    #[serde(default)]
    pub profile_activated: bool,
    /// Custom file paths that the user has added (persists even if removed from sync)
    #[serde(default)]
    pub custom_files: Vec<String>,
    /// Update check configuration
    #[serde(default)]
    pub updates: UpdateConfig,
    /// Color theme: "dark", "light", or "nocolor" (default: dark)
    #[serde(default = "default_theme")]
    pub theme: String,
    /// Icon set: "nerd", "unicode", or "ascii" (default: auto-detect)
    #[serde(default = "default_icon_set")]
    pub icon_set: String,
    /// Keymap configuration (preset and overrides)
    #[serde(default)]
    pub keymap: crate::keymap::Keymap,
    /// Whether to embed credentials (token) in the git remote URL.
    /// Default: true (for backward compatibility and to bypass gitconfig URL rewrites).
    /// Set to false if your environment rejects URLs with embedded credentials.
    #[serde(default = "default_embed_credentials")]
    pub embed_credentials_in_url: bool,
}

fn default_embed_credentials() -> bool {
    true
}

fn default_theme() -> String {
    "dark".to_string()
}

fn default_icon_set() -> String {
    "auto".to_string()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitHubConfig {
    /// Repository owner (username or org)
    pub owner: String,
    /// Repository name
    pub repo: String,
    /// OAuth token or PAT
    pub token: Option<String>,
}

// Profile struct removed - profiles are now stored in the repository manifest (.dotstate-profiles.toml)
// Use crate::utils::ProfileManifest and ProfileInfo instead

#[must_use]
pub fn default_repo_name() -> String {
    "dotstate-storage".to_string()
}

fn default_branch_name() -> String {
    "main".to_string()
}

fn default_backup_enabled() -> bool {
    true
}

impl Default for Config {
    fn default() -> Self {
        Self {
            version: CURRENT_VERSION,
            repo_mode: RepoMode::default(),
            github: None,
            active_profile: String::new(),
            backup_enabled: true,
            profile_activated: true,
            repo_path: dirs::home_dir()
                .unwrap_or_else(|| PathBuf::from("."))
                .join(".config")
                .join("dotstate")
                .join("storage"),
            repo_name: default_repo_name(),
            default_branch: "main".to_string(),
            custom_files: Vec::new(),
            updates: UpdateConfig::default(),
            theme: default_theme(),
            icon_set: default_icon_set(),
            keymap: crate::keymap::Keymap::default(),
            embed_credentials_in_url: default_embed_credentials(),
        }
    }
}

impl Config {
    /// Load configuration from file or create default
    /// If config doesn't exist, attempts to discover profiles from the repo manifest
    /// Automatically migrates old config versions to the current version.
    pub fn load_or_create(config_path: &Path) -> Result<Self> {
        if config_path.exists() {
            tracing::debug!("Loading config from: {:?}", config_path);
            let content = std::fs::read_to_string(config_path)
                .with_context(|| format!("Failed to read config file: {config_path:?}"))?;
            let mut config: Config =
                toml::from_str(&content).with_context(|| "Failed to parse config file")?;

            // Migrate if needed
            if config.version < CURRENT_VERSION {
                let old_version = config.version;
                tracing::info!(
                    "Migrating config from v{} to v{}",
                    old_version,
                    CURRENT_VERSION
                );
                config = Self::migrate(config)?;

                // Backup, save, cleanup
                crate::utils::migrate_file(config_path, old_version, "toml", || {
                    config.save(config_path)
                })?;
            }

            // Set defaults for missing fields (for backward compatibility)
            if config.repo_name.is_empty() {
                config.repo_name = default_repo_name();
            }
            if config.default_branch.is_empty() {
                config.default_branch = default_branch_name();
            }
            // backup_enabled defaults to true if not present
            // (handled by serde default)

            // If active_profile is empty and repo exists, try to set it from manifest
            if config.active_profile.is_empty() && config.repo_path.exists() {
                if let Ok(manifest) =
                    crate::utils::ProfileManifest::load_or_backfill(&config.repo_path)
                {
                    if let Some(first_profile) = manifest.profiles.first() {
                        config.active_profile = first_profile.name.clone();
                        config.save(config_path)?;
                    }
                }
            }

            tracing::info!("Config loaded successfully");
            Ok(config)
        } else {
            // Config doesn't exist - create default
            tracing::info!(
                "Config not found, creating default config at: {:?}",
                config_path
            );
            let mut config = Self::default();

            // Try to discover active profile from the repo manifest if repo_path exists
            if config.repo_path.exists() {
                if let Ok(manifest) =
                    crate::utils::ProfileManifest::load_or_backfill(&config.repo_path)
                {
                    if let Some(first_profile) = manifest.profiles.first() {
                        config.active_profile = first_profile.name.clone();
                    }
                }
            }

            config.save(config_path)?;
            Ok(config)
        }
    }

    /// Save configuration to file with secure permissions.
    /// Uses atomic write (temp file + rename) to prevent corruption on crash.
    pub fn save(&self, config_path: &Path) -> Result<()> {
        let content = toml::to_string_pretty(self).with_context(|| "Failed to serialize config")?;
        let temp_path = config_path.with_extension("toml.tmp");

        if let Some(parent) = config_path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("Failed to create config directory: {parent:?}"))?;
        }

        // Write to temp file first
        std::fs::write(&temp_path, &content)
            .with_context(|| format!("Failed to write temp config: {temp_path:?}"))?;

        // Set secure permissions on temp file (600: owner read/write only)
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = std::fs::metadata(&temp_path)
                .with_context(|| format!("Failed to get file metadata: {temp_path:?}"))?
                .permissions();
            perms.set_mode(0o600);
            std::fs::set_permissions(&temp_path, perms)
                .with_context(|| format!("Failed to set file permissions: {temp_path:?}"))?;
        }

        // Atomic rename (on POSIX systems)
        std::fs::rename(&temp_path, config_path)
            .with_context(|| format!("Failed to rename temp config to {config_path:?}"))?;

        Ok(())
    }

    /// Check if the repository is configured (either GitHub or Local mode)
    #[must_use]
    pub fn is_repo_configured(&self) -> bool {
        match self.repo_mode {
            RepoMode::GitHub => self.github.is_some(),
            RepoMode::Local => self.repo_path.join(".git").exists(),
        }
    }

    /// Reset config to unconfigured state
    /// Used when setup fails partway through to ensure clean retry
    pub fn reset_to_unconfigured(&mut self) {
        self.github = None;
        self.active_profile = String::new();
        self.profile_activated = false;
        self.repo_name = default_repo_name();
        // Keep repo_path as the default location - it will be recreated on next setup
        // Keep other settings like backup_enabled, theme, keymap
    }

    /// Get GitHub token from environment variable or config
    /// Priority: `DOTSTATE_GITHUB_TOKEN` env var > config token
    /// Returns None if neither is set
    pub fn get_github_token(&self) -> Option<String> {
        // First, check environment variable
        if let Ok(token) = std::env::var("DOTSTATE_GITHUB_TOKEN") {
            if !token.is_empty() {
                tracing::debug!(
                    "Using GitHub token from DOTSTATE_GITHUB_TOKEN environment variable"
                );
                return Some(token);
            }
        }

        // Fall back to config token
        self.github
            .as_ref()
            .and_then(|gh| gh.token.as_ref())
            .cloned()
    }

    /// Get the icon set based on config value
    /// Returns the configured icon set, or auto-detects if set to "auto"
    #[must_use]
    pub fn get_icon_set(&self) -> crate::icons::IconSet {
        use crate::icons::IconSet;

        match self.icon_set.to_lowercase().as_str() {
            "nerd" | "nerdfont" | "nerdfonts" => IconSet::NerdFonts,
            "unicode" => IconSet::Unicode,
            "emoji" => IconSet::Emoji,
            "ascii" | "plain" => IconSet::Ascii,
            _ => IconSet::detect(), // Auto-detect or fallback to detection
        }
    }

    // Profile-related methods removed - use ProfileManifest directly
    // Helper method removed as it's not used - profiles are accessed via App::get_profiles() instead

    // ==================== Migration Methods ====================

    /// Run all necessary migrations to bring config to current version.
    fn migrate(mut config: Self) -> Result<Self> {
        if config.version == 0 {
            config = Self::migrate_v0_to_v1(config)?;
        }
        // Future migrations:
        // if config.version == 1 { config = Self::migrate_v1_to_v2(config)?; }
        Ok(config)
    }

    /// Migrate from v0 (no version field) to v1.
    /// This is a no-op migration that just sets the version field.
    fn migrate_v0_to_v1(mut config: Self) -> Result<Self> {
        tracing::debug!("Migrating config v0 -> v1");
        config.version = 1;
        Ok(config)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_config_default() {
        let config = Config::default();
        assert_eq!(config.active_profile, "");
        assert_eq!(config.repo_mode, RepoMode::GitHub);
    }

    #[test]
    fn test_config_save_and_load() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.toml");
        let repo_path = temp_dir.path().join("repo");

        // Create a config with a non-existent repo_path to avoid manifest loading
        let config = Config {
            repo_path: repo_path.clone(),
            ..Default::default()
        };
        config.save(&config_path).unwrap();

        let loaded = Config::load_or_create(&config_path).unwrap();
        // Both should have empty active_profile since repo_path doesn't exist
        assert_eq!(config.active_profile, loaded.active_profile);
        assert_eq!(loaded.active_profile, "");
    }

    #[test]
    fn test_repo_mode_serialization() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.toml");
        let repo_path = temp_dir.path().join("repo");

        // Test GitHub mode
        let config = Config {
            repo_path: repo_path.clone(),
            repo_mode: RepoMode::GitHub,
            ..Default::default()
        };
        config.save(&config_path).unwrap();

        let loaded = Config::load_or_create(&config_path).unwrap();
        assert_eq!(loaded.repo_mode, RepoMode::GitHub);

        // Test Local mode
        let config = Config {
            repo_path: repo_path.clone(),
            repo_mode: RepoMode::Local,
            ..Default::default()
        };
        config.save(&config_path).unwrap();

        let loaded = Config::load_or_create(&config_path).unwrap();
        assert_eq!(loaded.repo_mode, RepoMode::Local);
    }

    #[test]
    fn test_old_config_defaults_to_github_mode() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.toml");
        let repo_path = temp_dir.path().join("repo");

        // Write an old-style config without repo_mode
        let old_config = format!(
            r#"
active_profile = ""
repo_path = "{}"
repo_name = "dotstate-storage"
default_branch = "main"
backup_enabled = true
profile_activated = true
custom_files = []
"#,
            repo_path.display()
        );
        std::fs::write(&config_path, old_config).unwrap();

        // Load should default repo_mode to GitHub
        let loaded = Config::load_or_create(&config_path).unwrap();
        assert_eq!(loaded.repo_mode, RepoMode::GitHub);
    }

    #[test]
    fn test_update_config_defaults() {
        let update_config = UpdateConfig::default();
        assert!(update_config.check_enabled);
        assert_eq!(update_config.check_interval_hours, 24);
    }

    #[test]
    fn test_config_includes_update_config() {
        let config = Config::default();
        assert!(config.updates.check_enabled);
        assert_eq!(config.updates.check_interval_hours, 24);
    }

    #[test]
    fn test_update_config_serialization() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.toml");
        let repo_path = temp_dir.path().join("repo");

        let mut config = Config {
            repo_path,
            ..Default::default()
        };
        config.updates.check_enabled = false;
        config.updates.check_interval_hours = 48;
        config.save(&config_path).unwrap();

        let loaded = Config::load_or_create(&config_path).unwrap();
        assert!(!loaded.updates.check_enabled);
        assert_eq!(loaded.updates.check_interval_hours, 48);
    }

    #[test]
    fn test_old_config_defaults_update_config() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.toml");
        let repo_path = temp_dir.path().join("repo");

        // Write an old-style config without updates section
        let old_config = format!(
            r#"
active_profile = ""
repo_path = "{}"
repo_name = "dotstate-storage"
default_branch = "main"
backup_enabled = true
profile_activated = true
custom_files = []
"#,
            repo_path.display()
        );
        std::fs::write(&config_path, old_config).unwrap();

        // Load should default updates to enabled with 24h interval
        let loaded = Config::load_or_create(&config_path).unwrap();
        assert!(loaded.updates.check_enabled);
        assert_eq!(loaded.updates.check_interval_hours, 24);
    }

    #[test]
    fn test_update_config_custom_interval() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.toml");
        let repo_path = temp_dir.path().join("repo");

        // Write config with custom update interval
        let config_content = format!(
            r#"
active_profile = ""
repo_path = "{}"
repo_name = "dotstate-storage"
default_branch = "main"
backup_enabled = true
profile_activated = true
custom_files = []

[updates]
check_enabled = true
check_interval_hours = 168
"#,
            repo_path.display()
        );
        std::fs::write(&config_path, config_content).unwrap();

        let loaded = Config::load_or_create(&config_path).unwrap();
        assert!(loaded.updates.check_enabled);
        assert_eq!(loaded.updates.check_interval_hours, 168); // 1 week
    }

    #[test]
    fn test_update_config_disabled() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.toml");
        let repo_path = temp_dir.path().join("repo");

        // Write config with updates disabled
        let config_content = format!(
            r#"
active_profile = ""
repo_path = "{}"
repo_name = "dotstate-storage"
default_branch = "main"
backup_enabled = true
profile_activated = true
custom_files = []

[updates]
check_enabled = false
"#,
            repo_path.display()
        );
        std::fs::write(&config_path, config_content).unwrap();

        let loaded = Config::load_or_create(&config_path).unwrap();
        assert!(!loaded.updates.check_enabled);
        // Should still have default interval even when disabled
        assert_eq!(loaded.updates.check_interval_hours, 24);
    }

    #[test]
    fn test_config_migration_v0_to_v1() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.toml");
        let repo_path = temp_dir.path().join("repo");

        // Write a v0 config (no version field)
        let v0_config = format!(
            r#"
active_profile = "test"
repo_path = "{}"
repo_name = "dotstate-storage"
default_branch = "main"
backup_enabled = true
profile_activated = true
custom_files = []
"#,
            repo_path.display()
        );
        std::fs::write(&config_path, v0_config).unwrap();

        // Load should auto-migrate to v1
        let loaded = Config::load_or_create(&config_path).unwrap();
        assert_eq!(loaded.version, 1);
        assert_eq!(loaded.active_profile, "test");

        // File should be updated with version
        let content = std::fs::read_to_string(&config_path).unwrap();
        assert!(content.contains("version = 1"));

        // Backup should be cleaned up
        let backup_path = config_path.with_extension("toml.backup-v0");
        assert!(!backup_path.exists());
    }

    #[test]
    fn test_config_already_at_current_version() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.toml");
        let repo_path = temp_dir.path().join("repo");

        // Write a v1 config
        let v1_config = format!(
            r#"
version = 1
active_profile = "test"
repo_path = "{}"
repo_name = "dotstate-storage"
default_branch = "main"
backup_enabled = true
profile_activated = true
custom_files = []
"#,
            repo_path.display()
        );
        std::fs::write(&config_path, v1_config).unwrap();

        // Load should not create backup (no migration needed)
        let loaded = Config::load_or_create(&config_path).unwrap();
        assert_eq!(loaded.version, 1);

        // No backup should exist
        let backup_path = config_path.with_extension("toml.backup-v0");
        assert!(!backup_path.exists());
    }

    #[test]
    fn test_new_config_has_current_version() {
        let config = Config::default();
        assert_eq!(config.version, 1);
    }
}