nixy-rs 0.3.1

Homebrew-style wrapper for Nix using flake.nix
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
//! Migration from legacy per-profile packages.json to centralized nixy.json.
//!
//! This module handles the automatic migration of existing nixy configurations
//! from the old per-profile structure to the new centralized configuration.
//!
//! ## Old Structure (pre-0.3.0)
//!
//! ```text
//! ~/.config/nixy/
//! ├── active                    # Active profile name
//! └── profiles/
//!     ├── default/
//!     │   ├── flake.nix         # Generated
//!     │   ├── flake.lock        # Managed by nix
//!     │   ├── packages.json     # Package state
//!     │   └── packages/         # Local packages
//!     └── work/
//!         └── ...
//! ```
//!
//! ## New Structure (0.3.0+)
//!
//! ```text
//! ~/.config/nixy/
//! ├── nixy.json                 # Single source of truth (ALL profiles)
//! └── packages/                 # Global local packages directory
//!
//! ~/.local/state/nixy/
//! ├── env -> ...                # Symlink to current profile's build
//! └── profiles/
//!     ├── default/
//!     │   ├── flake.nix         # Generated from nixy.json
//!     │   └── flake.lock        # Managed by nix
//!     └── work/
//!         └── ...
//! ```

use std::fs;
use std::path::Path;

use crate::config::{Config, DEFAULT_PROFILE};
use crate::error::Result;
use crate::flake::template::regenerate_flake_from_profile;
use crate::nixy_config::{NixyConfig, ProfileConfig, NIXY_CONFIG_VERSION};
use crate::state::PackageState;

/// Check if migration is needed.
///
/// Migration is needed when:
/// 1. nixy.json doesn't exist, AND
/// 2. Legacy profiles directory exists with at least one profile, OR
/// 3. Legacy active file exists
pub fn needs_migration(config: &Config) -> bool {
    // If nixy.json already exists, no migration needed
    if config.nixy_json.exists() {
        return false;
    }

    // Check for legacy profiles directory
    if config.profiles_dir.exists() && config.profiles_dir.is_dir() {
        if let Ok(entries) = fs::read_dir(&config.profiles_dir) {
            for entry in entries.flatten() {
                if entry.path().is_dir() {
                    // Found at least one profile directory
                    return true;
                }
            }
        }
    }

    // Check for legacy active file
    if config.active_file.exists() {
        return true;
    }

    // Check for legacy flake.nix in config dir (very old format)
    if config.legacy_flake.exists() {
        return true;
    }

    false
}

/// Migrate from legacy per-profile packages.json to centralized nixy.json.
///
/// This function:
/// 1. Reads all existing profile directories from ~/.config/nixy/profiles/
/// 2. Loads packages.json from each profile
/// 3. Creates a unified nixy.json with all profile data
/// 4. Merges local packages from all profiles to the global packages directory
/// 5. Regenerates flake.nix and copies flake.lock to the new state directory
/// 6. Preserves the active profile setting
pub fn migrate_to_nixy_json(config: &Config) -> Result<NixyConfig> {
    let mut nixy_config = NixyConfig {
        version: NIXY_CONFIG_VERSION,
        active_profile: DEFAULT_PROFILE.to_string(),
        profiles: std::collections::BTreeMap::new(),
    };

    // Read active profile from legacy file
    if config.active_file.exists() {
        if let Ok(active) = fs::read_to_string(&config.active_file) {
            let active = active.trim().to_string();
            if !active.is_empty() {
                nixy_config.active_profile = active;
            }
        }
    }

    // Collect all profile directories and their configs first
    let mut profile_dirs: Vec<(String, std::path::PathBuf, ProfileConfig)> = Vec::new();

    if config.profiles_dir.exists() {
        if let Ok(entries) = fs::read_dir(&config.profiles_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                        let profile_config = migrate_profile(&path)?;
                        profile_dirs.push((name.to_string(), path, profile_config));
                    }
                }
            }
        }
    }

    // First pass: merge all local packages to global directory
    // This ensures global_packages_dir exists before generating any flakes
    for (_, path, _) in &profile_dirs {
        let legacy_packages_dir = path.join("packages");
        if legacy_packages_dir.exists() {
            merge_local_packages(&legacy_packages_dir, &config.global_packages_dir)?;
        }
    }

    // Handle very old format local packages (from config dir)
    if config.legacy_flake.exists() {
        let legacy_packages_dir = config.config_dir.join("packages");
        if legacy_packages_dir.exists() {
            merge_local_packages(&legacy_packages_dir, &config.global_packages_dir)?;
        }
    }

    // Now determine global_packages_dir for flake generation
    let global_packages_dir = if config.global_packages_dir.exists() {
        Some(config.global_packages_dir.as_path())
    } else {
        None
    };

    // Second pass: migrate profiles and generate flakes
    for (name, path, profile_config) in profile_dirs {
        nixy_config
            .profiles
            .insert(name.clone(), profile_config.clone());

        // Create state directory and copy only flake.lock (to preserve versions)
        let state_profile_dir = config.profiles_state_dir.join(&name);
        fs::create_dir_all(&state_profile_dir)?;

        let legacy_lock = path.join("flake.lock");
        if legacy_lock.exists() {
            fs::copy(&legacy_lock, state_profile_dir.join("flake.lock"))?;
        }

        // Regenerate flake.nix with correct paths for new directory structure
        regenerate_flake_from_profile(&state_profile_dir, &profile_config, global_packages_dir)?;
    }

    // Handle very old format (flake.nix directly in config dir)
    if config.legacy_flake.exists() && !nixy_config.profiles.contains_key(DEFAULT_PROFILE) {
        let profile_config = ProfileConfig::default();
        nixy_config
            .profiles
            .insert(DEFAULT_PROFILE.to_string(), profile_config.clone());

        // Note: local packages from config dir were already merged in the first pass above

        // Create state directory and copy only flake.lock
        let state_profile_dir = config.profiles_state_dir.join(DEFAULT_PROFILE);
        fs::create_dir_all(&state_profile_dir)?;

        let legacy_lock = config.config_dir.join("flake.lock");
        if legacy_lock.exists() {
            fs::copy(&legacy_lock, state_profile_dir.join("flake.lock"))?;
        }

        // Regenerate flake.nix with correct paths (global_packages_dir already computed above)
        regenerate_flake_from_profile(&state_profile_dir, &profile_config, global_packages_dir)?;
    }

    // Ensure default profile exists
    if !nixy_config.profiles.contains_key(DEFAULT_PROFILE) {
        nixy_config
            .profiles
            .insert(DEFAULT_PROFILE.to_string(), ProfileConfig::default());
    }

    // Ensure active profile exists in profiles
    if !nixy_config
        .profiles
        .contains_key(&nixy_config.active_profile)
    {
        nixy_config.active_profile = DEFAULT_PROFILE.to_string();
    }

    Ok(nixy_config)
}

/// Migrate a single profile from its directory.
fn migrate_profile(profile_dir: &Path) -> Result<ProfileConfig> {
    let state_path = profile_dir.join("packages.json");

    if state_path.exists() {
        let state = PackageState::load(&state_path)?;
        Ok(ProfileConfig::from(&state))
    } else {
        Ok(ProfileConfig::default())
    }
}

/// Merge local packages from a legacy profile's packages directory to the global directory.
fn merge_local_packages(src_dir: &Path, dst_dir: &Path) -> Result<()> {
    if !src_dir.exists() {
        return Ok(());
    }

    fs::create_dir_all(dst_dir)?;

    if let Ok(entries) = fs::read_dir(src_dir) {
        for entry in entries.flatten() {
            let src_path = entry.path();
            let file_name = entry.file_name();
            let dst_path = dst_dir.join(&file_name);

            // Skip if destination already exists (don't overwrite)
            if dst_path.exists() {
                continue;
            }

            // Skip all symlinks to avoid pulling in files from outside nixy config
            let metadata = match fs::symlink_metadata(&src_path) {
                Ok(m) => m,
                Err(_) => continue,
            };
            if metadata.file_type().is_symlink() {
                continue;
            }

            if metadata.is_dir() {
                copy_dir_recursive(&src_path, &dst_path)?;
            } else if src_path.exists() {
                fs::copy(&src_path, &dst_path)?;
            }
        }
    }

    Ok(())
}

/// Recursively copy a directory.
fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
    fs::create_dir_all(dst)?;

    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let src_path = entry.path();
        let dst_path = dst.join(entry.file_name());

        // Skip all symlinks to avoid pulling in files from outside nixy config
        let metadata = match fs::symlink_metadata(&src_path) {
            Ok(m) => m,
            Err(_) => continue,
        };
        if metadata.file_type().is_symlink() {
            continue;
        }

        if metadata.is_dir() {
            copy_dir_recursive(&src_path, &dst_path)?;
        } else {
            fs::copy(&src_path, &dst_path)?;
        }
    }

    Ok(())
}

/// Run the migration process or initialize nixy.json for fresh installs.
///
/// This is called from main.rs before any command is executed.
/// It checks if migration is needed and performs it automatically.
/// For fresh installs (no legacy data, no nixy.json), it creates a default nixy.json.
pub fn run_migration_if_needed(config: &Config) -> Result<()> {
    // If nixy.json exists, nothing to do
    if config.nixy_json.exists() {
        return Ok(());
    }

    // Check if there's legacy data to migrate
    if needs_migration(config) {
        crate::commands::info("Migrating to new nixy.json configuration format...");

        let nixy_config = migrate_to_nixy_json(config)?;
        nixy_config.save(config)?;

        crate::commands::success("Migration complete! Your configuration has been updated.");
        crate::commands::info(&format!(
            "Configuration is now stored in: {}",
            config.nixy_json.display()
        ));
        crate::commands::info(&format!(
            "Generated files are now in: {}",
            config.profiles_state_dir.display()
        ));
    } else {
        // Fresh install: create default nixy.json
        let nixy_config = NixyConfig::default();
        nixy_config.save(config)?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::{CustomPackage, ResolvedNixpkgPackage};
    use tempfile::TempDir;

    fn test_config(temp: &TempDir) -> Config {
        Config {
            config_dir: temp.path().join("config"),
            nixy_json: temp.path().join("config/nixy.json"),
            global_packages_dir: temp.path().join("config/packages"),
            state_dir: temp.path().join("state"),
            profiles_state_dir: temp.path().join("state/profiles"),
            profiles_dir: temp.path().join("config/profiles"),
            active_file: temp.path().join("config/active"),
            env_link: temp.path().join("state/env"),
            legacy_flake: temp.path().join("config/flake.nix"),
        }
    }

    #[test]
    fn test_needs_migration_false_when_nixy_json_exists() {
        let temp = TempDir::new().unwrap();
        let config = test_config(&temp);

        // Create nixy.json
        fs::create_dir_all(&config.config_dir).unwrap();
        fs::write(&config.nixy_json, "{}").unwrap();

        assert!(!needs_migration(&config));
    }

    #[test]
    fn test_needs_migration_false_when_nothing_exists() {
        let temp = TempDir::new().unwrap();
        let config = test_config(&temp);

        assert!(!needs_migration(&config));
    }

    #[test]
    fn test_needs_migration_true_when_legacy_profile_exists() {
        let temp = TempDir::new().unwrap();
        let config = test_config(&temp);

        // Create legacy profile directory
        fs::create_dir_all(config.profiles_dir.join("default")).unwrap();

        assert!(needs_migration(&config));
    }

    #[test]
    fn test_needs_migration_true_when_active_file_exists() {
        let temp = TempDir::new().unwrap();
        let config = test_config(&temp);

        // Create legacy active file
        fs::create_dir_all(&config.config_dir).unwrap();
        fs::write(&config.active_file, "default").unwrap();

        assert!(needs_migration(&config));
    }

    #[test]
    fn test_needs_migration_true_when_legacy_flake_exists() {
        let temp = TempDir::new().unwrap();
        let config = test_config(&temp);

        // Create legacy flake.nix
        fs::create_dir_all(&config.config_dir).unwrap();
        fs::write(&config.legacy_flake, "{}").unwrap();

        assert!(needs_migration(&config));
    }

    #[test]
    fn test_migrate_empty_profile() {
        let temp = TempDir::new().unwrap();
        let config = test_config(&temp);

        // Create empty legacy profile
        let profile_dir = config.profiles_dir.join("default");
        fs::create_dir_all(&profile_dir).unwrap();

        let nixy_config = migrate_to_nixy_json(&config).unwrap();

        assert!(nixy_config.profiles.contains_key("default"));
        assert_eq!(nixy_config.active_profile, "default");
    }

    #[test]
    fn test_migrate_profile_with_packages() {
        let temp = TempDir::new().unwrap();
        let config = test_config(&temp);

        // Create legacy profile with packages.json
        let profile_dir = config.profiles_dir.join("default");
        fs::create_dir_all(&profile_dir).unwrap();

        let state = PackageState {
            version: 2,
            packages: vec!["hello".to_string()],
            resolved_packages: vec![ResolvedNixpkgPackage {
                name: "nodejs".to_string(),
                version_spec: Some("20".to_string()),
                resolved_version: "20.11.0".to_string(),
                attribute_path: "nodejs_20".to_string(),
                commit_hash: "abc123".to_string(),
                platforms: None,
            }],
            custom_packages: vec![CustomPackage {
                name: "neovim".to_string(),
                input_name: "neovim-nightly".to_string(),
                input_url: "github:nix-community/neovim-nightly-overlay".to_string(),
                package_output: "packages".to_string(),
                source_name: None,
                platforms: None,
            }],
        };
        state.save(&profile_dir.join("packages.json")).unwrap();

        let nixy_config = migrate_to_nixy_json(&config).unwrap();
        let profile = nixy_config.profiles.get("default").unwrap();

        assert!(profile.has_package("hello"));
        assert!(profile.has_package("nodejs"));
        assert!(profile.has_package("neovim"));
    }

    #[test]
    fn test_migrate_preserves_active_profile() {
        let temp = TempDir::new().unwrap();
        let config = test_config(&temp);

        // Create two profiles
        fs::create_dir_all(config.profiles_dir.join("default")).unwrap();
        fs::create_dir_all(config.profiles_dir.join("work")).unwrap();

        // Set work as active
        fs::create_dir_all(&config.config_dir).unwrap();
        fs::write(&config.active_file, "work").unwrap();

        let nixy_config = migrate_to_nixy_json(&config).unwrap();

        assert_eq!(nixy_config.active_profile, "work");
    }

    #[test]
    fn test_migrate_copies_flake_files() {
        let temp = TempDir::new().unwrap();
        let config = test_config(&temp);

        // Create legacy profile with flake files
        let profile_dir = config.profiles_dir.join("default");
        fs::create_dir_all(&profile_dir).unwrap();
        fs::write(profile_dir.join("flake.nix"), "{ }").unwrap();
        fs::write(profile_dir.join("flake.lock"), "{}").unwrap();

        let _ = migrate_to_nixy_json(&config).unwrap();

        // Check files were copied to state directory
        let state_profile_dir = config.profiles_state_dir.join("default");
        assert!(state_profile_dir.join("flake.nix").exists());
        assert!(state_profile_dir.join("flake.lock").exists());
    }

    #[test]
    fn test_migrate_merges_local_packages() {
        let temp = TempDir::new().unwrap();
        let config = test_config(&temp);

        // Create legacy profile with local packages
        let profile_dir = config.profiles_dir.join("default");
        let packages_dir = profile_dir.join("packages");
        fs::create_dir_all(&packages_dir).unwrap();
        fs::write(packages_dir.join("my-pkg.nix"), "{ }").unwrap();

        let _ = migrate_to_nixy_json(&config).unwrap();

        // Check packages were copied to global directory
        assert!(config.global_packages_dir.join("my-pkg.nix").exists());
    }

    #[test]
    fn test_migrate_handles_multiple_profiles() {
        let temp = TempDir::new().unwrap();
        let config = test_config(&temp);

        // Create multiple profiles
        for name in &["default", "work", "personal"] {
            let profile_dir = config.profiles_dir.join(name);
            fs::create_dir_all(&profile_dir).unwrap();

            let mut state = PackageState::default();
            state.packages.push(format!("{}-pkg", name));
            state.save(&profile_dir.join("packages.json")).unwrap();
        }

        let nixy_config = migrate_to_nixy_json(&config).unwrap();

        assert!(nixy_config.profiles.contains_key("default"));
        assert!(nixy_config.profiles.contains_key("work"));
        assert!(nixy_config.profiles.contains_key("personal"));

        assert!(nixy_config
            .profiles
            .get("default")
            .unwrap()
            .has_package("default-pkg"));
        assert!(nixy_config
            .profiles
            .get("work")
            .unwrap()
            .has_package("work-pkg"));
        assert!(nixy_config
            .profiles
            .get("personal")
            .unwrap()
            .has_package("personal-pkg"));
    }

    #[test]
    fn test_migrate_legacy_flake_only() {
        let temp = TempDir::new().unwrap();
        let config = test_config(&temp);

        // Create very old format (flake.nix in config dir)
        fs::create_dir_all(&config.config_dir).unwrap();
        fs::write(&config.legacy_flake, "{ }").unwrap();

        let nixy_config = migrate_to_nixy_json(&config).unwrap();

        // Should create default profile
        assert!(nixy_config.profiles.contains_key("default"));

        // Should copy flake to state directory
        let state_profile_dir = config.profiles_state_dir.join("default");
        assert!(state_profile_dir.join("flake.nix").exists());
    }

    #[test]
    #[cfg(unix)]
    fn test_migrate_skips_broken_symlinks() {
        use std::os::unix::fs::symlink;

        let temp = TempDir::new().unwrap();
        let config = test_config(&temp);

        // Create legacy profile with local packages containing a broken symlink
        let profile_dir = config.profiles_dir.join("default");
        let packages_dir = profile_dir.join("packages");
        fs::create_dir_all(&packages_dir).unwrap();

        // Create a valid file
        fs::write(packages_dir.join("valid.nix"), "{ }").unwrap();

        // Create a broken symlink pointing to non-existent file
        symlink(
            "/nonexistent/path/broken.nix",
            packages_dir.join("broken.nix"),
        )
        .unwrap();

        // Migration should succeed despite the broken symlink
        let nixy_config = migrate_to_nixy_json(&config).unwrap();

        // Should have migrated the profile
        assert!(nixy_config.profiles.contains_key("default"));

        // Valid file should be copied
        assert!(config.global_packages_dir.join("valid.nix").exists());

        // Broken symlink should be skipped (not cause an error)
        assert!(!config.global_packages_dir.join("broken.nix").exists());
    }
}