dotstate 0.3.3

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
//! Profile activation/deactivation commands.

use super::ProfileCommand;
use crate::config::Config;
use crate::icons::Icons;
use crate::services::ProfileService;
use crate::utils::symlink_manager::OperationStatus;
use crate::utils::SymlinkManager;
use anyhow::{Context, Result};

/// Execute a profile subcommand.
pub fn execute(command: ProfileCommand) -> Result<()> {
    match command {
        ProfileCommand::Current => cmd_current(),
        ProfileCommand::List => cmd_list(),
        ProfileCommand::Switch { name } => cmd_switch(name),
    }
}

/// Print the current profile name.
pub fn cmd_current() -> Result<()> {
    println!("{}", current_profile_name()?);
    Ok(())
}

fn current_profile_name() -> Result<String> {
    let config_path = crate::utils::get_config_path();
    let config = Config::load_or_create(&config_path).context("Failed to load configuration")?;
    let icons = Icons::from_config(&config);

    if !config.is_repo_configured() {
        eprintln!(
            "{} Repository not configured. Please run 'dotstate' to set up repository.",
            icons.error()
        );
        std::process::exit(1);
    }

    if config.active_profile.is_empty() {
        eprintln!("{} No active profile is set.", icons.error());
        std::process::exit(1);
    }

    Ok(config.active_profile)
}

/// List all profiles, marking the active profile.
pub fn cmd_list() -> Result<()> {
    for line in profile_list_lines()? {
        println!("{line}");
    }
    Ok(())
}

fn profile_list_lines() -> Result<Vec<String>> {
    let config_path = crate::utils::get_config_path();
    let config = Config::load_or_create(&config_path).context("Failed to load configuration")?;
    let icons = Icons::from_config(&config);

    if !config.is_repo_configured() {
        eprintln!(
            "{} Repository not configured. Please run 'dotstate' to set up repository.",
            icons.error()
        );
        std::process::exit(1);
    }

    let profiles = ProfileService::get_profiles(&config.repo_path)?;

    if profiles.is_empty() {
        return Ok(vec![format!("{} No profiles found.", icons.info())]);
    }

    Ok(profiles
        .into_iter()
        .map(|profile| {
            let icon = if profile.name == config.active_profile {
                icons.active_profile()
            } else {
                icons.inactive_profile()
            };
            format!("{icon} {}", profile.name)
        })
        .collect())
}

/// Switch to a different profile and activate it.
pub fn cmd_switch(name: String) -> Result<()> {
    let config_path = crate::utils::get_config_path();
    let mut config =
        Config::load_or_create(&config_path).context("Failed to load configuration")?;
    let icons = Icons::from_config(&config);

    if !config.is_repo_configured() {
        eprintln!(
            "{} Repository not configured. Please run 'dotstate' to set up repository.",
            icons.error()
        );
        std::process::exit(1);
    }

    let manifest = crate::utils::ProfileManifest::load_or_backfill(&config.repo_path)
        .context("Failed to load profile manifest")?;

    if !manifest.profiles.iter().any(|p| p.name == name) {
        eprintln!("{} Profile '{name}' not found.", icons.error());
        std::process::exit(1);
    }

    if config.active_profile == name && config.profile_activated {
        println!("{} Already on profile '{name}'", icons.info());
        return Ok(());
    }

    if config.profile_activated {
        let result = ProfileService::switch_profile(
            &config.repo_path,
            &config.active_profile,
            &name,
            config.backup_enabled,
        )?;

        config.active_profile = name.clone();
        config.profile_activated = true;
        config
            .save(&config_path)
            .context("Failed to save configuration")?;

        println!("{} Switched to profile '{name}'", icons.success());
        println!(
            "   Removed {} symlinks, created {} symlinks",
            result.removed_count, result.created_count
        );
        return Ok(());
    }

    let resolved_files = manifest
        .resolve_files(&name)
        .context("Failed to resolve files for target profile")?;

    if resolved_files.is_empty() {
        eprintln!(
            "{} Target profile '{name}' has no synced files (including inherited/common).",
            icons.error()
        );
        std::process::exit(1);
    }

    let mut symlink_mgr =
        SymlinkManager::new_with_backup(config.repo_path.clone(), config.backup_enabled)?;
    let operations = symlink_mgr.activate_resolved(&name, &resolved_files)?;

    let success_count = operations
        .iter()
        .filter(|op| {
            matches!(
                op.status,
                OperationStatus::Success | OperationStatus::Skipped(_)
            )
        })
        .count();
    let failed_count = operations.len() - success_count;

    if failed_count > 0 {
        eprintln!(
            "{} Activated {success_count} files, {failed_count} failed",
            icons.warning()
        );
        for op in &operations {
            if let OperationStatus::Failed(msg) = &op.status {
                eprintln!("   {} {}: {}", icons.error(), op.target.display(), msg);
            }
        }
        std::process::exit(1);
    }

    config.active_profile = name.clone();
    config.profile_activated = true;
    config
        .save(&config_path)
        .context("Failed to save configuration")?;

    println!("{} Switched to profile '{name}'", icons.success());
    println!("   Activated {success_count} symlinks");

    Ok(())
}

/// Execute the activate command.
pub fn cmd_activate() -> Result<()> {
    let config_path = crate::utils::get_config_path();
    let mut config =
        Config::load_or_create(&config_path).context("Failed to load configuration")?;

    if !config.is_repo_configured() {
        let icons = Icons::from_config(&config);
        eprintln!(
            "{} Repository not configured. Please run 'dotstate' to set up repository.",
            icons.error()
        );
        std::process::exit(1);
    }

    let icons = Icons::from_config(&config);

    // Check if already activated
    if config.profile_activated {
        println!(
            "{} Profile '{}' is already activated.",
            icons.info(),
            config.active_profile
        );
        println!("   No action needed. Use 'dotstate deactivate' to restore original files.");
        return Ok(());
    }

    // Get active profile info from manifest
    let active_profile_name = config.active_profile.clone();
    let manifest = crate::utils::ProfileManifest::load_or_backfill(&config.repo_path)
        .context("Failed to load profile manifest")?;

    // Resolve the full file list (inheritance chain + common, with overrides)
    let resolved_files = manifest
        .resolve_files(&active_profile_name)
        .context("Failed to resolve files for active profile")?;

    if resolved_files.is_empty() {
        eprintln!(
            "{} Active profile '{active_profile_name}' has no synced files (including inherited/common).",
            icons.error()
        );
        eprintln!(
            "{} Run 'dotstate' to select and sync files.",
            icons.lightbulb()
        );
        std::process::exit(1);
    }

    // Show inheritance chain if applicable
    if let Ok(chain) = manifest.inheritance_chain(&active_profile_name) {
        if chain.len() > 1 {
            println!("   Inheritance chain: {}", chain.join(" -> "));
        }
    }

    println!(
        "{} Activating profile '{active_profile_name}'...",
        icons.sync()
    );
    println!(
        "   This will create symlinks for {} files",
        resolved_files.len()
    );

    // Create SymlinkManager and activate with resolved files
    let mut symlink_mgr =
        SymlinkManager::new_with_backup(config.repo_path.clone(), config.backup_enabled)?;

    let operations = symlink_mgr.activate_resolved(&active_profile_name, &resolved_files)?;

    // Report results
    // Count Success and Skipped as successful (Skipped = symlink already correct)
    let success_count = operations
        .iter()
        .filter(|op| {
            matches!(
                op.status,
                OperationStatus::Success | OperationStatus::Skipped(_)
            )
        })
        .count();
    let failed_count = operations.len() - success_count;

    if failed_count > 0 {
        eprintln!(
            "{} Activated {success_count} files, {failed_count} failed",
            icons.warning()
        );
        for op in &operations {
            if let OperationStatus::Failed(msg) = &op.status {
                eprintln!("   {} {}: {}", icons.error(), op.target.display(), msg);
            }
        }
        std::process::exit(1);
    } else {
        // Mark as activated in config
        config.profile_activated = true;
        config
            .save(&config_path)
            .context("Failed to save configuration")?;

        println!(
            "{} Successfully activated profile '{active_profile_name}'",
            icons.success()
        );
        println!("   {success_count} symlinks created");
    }

    Ok(())
}

/// Execute the deactivate command.
pub fn cmd_deactivate() -> Result<()> {
    let config_path = crate::utils::get_config_path();
    let mut config =
        Config::load_or_create(&config_path).context("Failed to load configuration")?;

    if !config.is_repo_configured() {
        let icons = Icons::from_config(&config);
        eprintln!(
            "{} Repository not configured. Please run 'dotstate' to set up repository.",
            icons.error()
        );
        std::process::exit(1);
    }

    let icons = Icons::from_config(&config);

    println!("{} Deactivating dotstate...", icons.sync());
    println!("   This will restore all files from the repository");

    // Create SymlinkManager
    let mut symlink_mgr =
        SymlinkManager::new_with_backup(config.repo_path.clone(), config.backup_enabled)?;

    // Deactivate all symlinks (profile + common), always restore files
    let operations = symlink_mgr.deactivate_profile_with_restore(&config.active_profile, true)?;

    // Report results
    // Count Success and Skipped as successful (Skipped = symlink already gone or not our symlink)
    let success_count = operations
        .iter()
        .filter(|op| {
            matches!(
                op.status,
                OperationStatus::Success | OperationStatus::Skipped(_)
            )
        })
        .count();
    let failed_count = operations.len() - success_count;

    if operations.is_empty() {
        println!(
            "{} No symlinks were tracked. Nothing to deactivate.",
            icons.info()
        );
    } else if failed_count > 0 {
        eprintln!(
            "{} Deactivated {success_count} files, {failed_count} failed",
            icons.warning()
        );
        for op in &operations {
            if let OperationStatus::Failed(msg) = &op.status {
                eprintln!("   {} {}: {}", icons.error(), op.target.display(), msg);
            }
        }
        std::process::exit(1);
    } else {
        // Mark as deactivated in config
        config.profile_activated = false;
        config
            .save(&config_path)
            .context("Failed to save configuration")?;

        println!("{} Successfully deactivated dotstate", icons.success());
        println!("   {success_count} files restored");
        println!(
            "{} Dotstate is now deactivated. Use 'dotstate activate' to reactivate.",
            icons.lightbulb()
        );
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{cmd_switch, current_profile_name, profile_list_lines};
    use crate::config::{Config, RepoMode};
    use crate::utils::profile_manifest::{ProfileInfo, ProfileManifest};
    use std::fs;
    use std::path::{Path, PathBuf};
    use std::sync::{Mutex, OnceLock};
    use tempfile::TempDir;

    struct TestPaths {
        _root: TempDir,
        repo: PathBuf,
        home: PathBuf,
        config: PathBuf,
        backup: PathBuf,
    }

    #[allow(clippy::struct_field_names)]
    struct EnvGuard {
        old_home: Option<String>,
        old_config: Option<String>,
        old_backup: Option<String>,
    }

    impl EnvGuard {
        fn set(paths: &TestPaths) -> Self {
            let old_home = std::env::var("DOTSTATE_TEST_HOME").ok();
            let old_config = std::env::var("DOTSTATE_TEST_CONFIG_DIR").ok();
            let old_backup = std::env::var("DOTSTATE_TEST_BACKUP_DIR").ok();

            std::env::set_var("DOTSTATE_TEST_HOME", &paths.home);
            std::env::set_var("DOTSTATE_TEST_CONFIG_DIR", &paths.config);
            std::env::set_var("DOTSTATE_TEST_BACKUP_DIR", &paths.backup);

            Self {
                old_home,
                old_config,
                old_backup,
            }
        }
    }

    fn env_lock() -> &'static Mutex<()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| Mutex::new(()))
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            match &self.old_home {
                Some(v) => std::env::set_var("DOTSTATE_TEST_HOME", v),
                None => std::env::remove_var("DOTSTATE_TEST_HOME"),
            }
            match &self.old_config {
                Some(v) => std::env::set_var("DOTSTATE_TEST_CONFIG_DIR", v),
                None => std::env::remove_var("DOTSTATE_TEST_CONFIG_DIR"),
            }
            match &self.old_backup {
                Some(v) => std::env::set_var("DOTSTATE_TEST_BACKUP_DIR", v),
                None => std::env::remove_var("DOTSTATE_TEST_BACKUP_DIR"),
            }
        }
    }

    fn setup_paths() -> anyhow::Result<TestPaths> {
        let root = TempDir::new()?;
        let repo = root.path().join("repo");
        let home = root.path().join("home");
        let config = root.path().join("config");
        let backup = root.path().join("backup");

        fs::create_dir_all(repo.join(".git"))?;
        fs::create_dir_all(&home)?;
        fs::create_dir_all(&config)?;
        fs::create_dir_all(&backup)?;

        Ok(TestPaths {
            _root: root,
            repo,
            home,
            config,
            backup,
        })
    }

    fn write_config(
        repo: &Path,
        active_profile: &str,
        profile_activated: bool,
    ) -> anyhow::Result<()> {
        let config_path = crate::utils::get_config_path();
        let config = Config {
            repo_mode: RepoMode::Local,
            repo_path: repo.to_path_buf(),
            active_profile: active_profile.to_string(),
            profile_activated,
            backup_enabled: false,
            icon_set: "unicode".to_string(),
            ..Config::default()
        };
        config.save(&config_path)
    }

    fn write_manifest(repo: &Path) -> anyhow::Result<()> {
        let manifest = ProfileManifest {
            profiles: vec![
                ProfileInfo {
                    name: "default".to_string(),
                    description: None,
                    inherits: None,
                    synced_files: vec![".default-file".to_string()],
                    packages: Vec::new(),
                },
                ProfileInfo {
                    name: "work".to_string(),
                    description: None,
                    inherits: None,
                    synced_files: vec![".work-file".to_string()],
                    packages: Vec::new(),
                },
            ],
            ..ProfileManifest::default()
        };
        fs::create_dir_all(repo.join("default"))?;
        fs::create_dir_all(repo.join("work"))?;
        fs::write(
            repo.join("default").join(".default-file"),
            "default content",
        )?;
        fs::write(repo.join("work").join(".work-file"), "work content")?;
        manifest.save(repo)
    }

    #[test]
    fn current_profile_reads_configured_profile() -> anyhow::Result<()> {
        let _lock = env_lock().lock().unwrap();
        let paths = setup_paths()?;
        let _guard = EnvGuard::set(&paths);
        write_manifest(&paths.repo)?;
        write_config(&paths.repo, "work", false)?;

        assert_eq!(current_profile_name()?, "work");
        Ok(())
    }

    #[test]
    fn profile_list_marks_active_and_inactive_profiles() -> anyhow::Result<()> {
        let _lock = env_lock().lock().unwrap();
        let paths = setup_paths()?;
        let _guard = EnvGuard::set(&paths);
        write_manifest(&paths.repo)?;
        write_config(&paths.repo, "work", false)?;

        let lines = profile_list_lines()?;

        assert_eq!(lines.len(), 2);
        assert!(lines.iter().any(|line| line.starts_with("○ default")));
        assert!(lines.iter().any(|line| line.starts_with("★ work")));
        Ok(())
    }

    #[test]
    fn profile_list_handles_empty_manifest() -> anyhow::Result<()> {
        let _lock = env_lock().lock().unwrap();
        let paths = setup_paths()?;
        let _guard = EnvGuard::set(&paths);
        let manifest = ProfileManifest::default();
        manifest.save(&paths.repo)?;
        write_config(&paths.repo, "default", false)?;

        let lines = profile_list_lines()?;

        assert_eq!(lines.len(), 1);
        assert!(lines[0].contains("No profiles found."));
        Ok(())
    }

    #[test]
    fn switch_activates_target_profile_when_deactivated() -> anyhow::Result<()> {
        let _lock = env_lock().lock().unwrap();
        let paths = setup_paths()?;
        let _guard = EnvGuard::set(&paths);
        write_manifest(&paths.repo)?;
        write_config(&paths.repo, "default", false)?;

        cmd_switch("work".to_string())?;

        let config = Config::load_or_create(&crate::utils::get_config_path())?;
        assert_eq!(config.active_profile, "work");
        assert!(config.profile_activated);

        let target = paths.home.join(".work-file");
        assert!(target.is_symlink());
        assert_eq!(
            fs::read_link(target)?,
            paths.repo.join("work").join(".work-file")
        );
        Ok(())
    }

    #[test]
    fn switch_replaces_symlinks_when_current_profile_is_active() -> anyhow::Result<()> {
        let _lock = env_lock().lock().unwrap();
        let paths = setup_paths()?;
        let _guard = EnvGuard::set(&paths);
        write_manifest(&paths.repo)?;
        write_config(&paths.repo, "default", true)?;

        let manifest = ProfileManifest::load_or_backfill(&paths.repo)?;
        let default_files = manifest.resolve_files("default")?;
        let mut symlink_mgr =
            crate::utils::SymlinkManager::new_with_backup(paths.repo.clone(), false)?;
        symlink_mgr.activate_resolved("default", &default_files)?;

        cmd_switch("work".to_string())?;

        let config = Config::load_or_create(&crate::utils::get_config_path())?;
        assert_eq!(config.active_profile, "work");
        assert!(config.profile_activated);

        assert!(!paths.home.join(".default-file").exists());
        let target = paths.home.join(".work-file");
        assert!(target.is_symlink());
        assert_eq!(
            fs::read_link(target)?,
            paths.repo.join("work").join(".work-file")
        );
        Ok(())
    }
}