nixy-rs 0.1.4

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
use std::path::Path;

use super::editor::extract_marker_content;
use super::parser::collect_local_packages;

/// Content to preserve from an existing flake
#[derive(Default, Clone)]
pub struct PreservedContent {
    pub custom_inputs: String,
    pub custom_packages: String,
    pub custom_paths: String,
}

impl PreservedContent {
    pub fn from_file(path: &Path) -> Self {
        let content = match std::fs::read_to_string(path) {
            Ok(c) => c,
            Err(_) => return Self::default(),
        };

        Self {
            custom_inputs: extract_marker_content(&content, "nixy:custom-inputs"),
            custom_packages: extract_marker_content(&content, "nixy:custom-packages"),
            custom_paths: extract_marker_content(&content, "nixy:custom-paths"),
        }
    }
}

/// Generate flake.nix content
pub fn generate_flake(
    packages: &[String],
    flake_dir: Option<&Path>,
    preserved: Option<&PreservedContent>,
) -> String {
    let preserved = preserved.cloned().unwrap_or_default();

    // Collect local packages if flake_dir is provided
    let (local_packages, local_flakes) = if let Some(dir) = flake_dir {
        let packages_dir = dir.join("packages");
        if packages_dir.exists() {
            collect_local_packages(&packages_dir)
        } else {
            (Vec::new(), Vec::new())
        }
    } else {
        (Vec::new(), Vec::new())
    };

    // Filter out local packages from standard packages list
    let filtered_packages: Vec<&String> = packages
        .iter()
        .filter(|pkg| {
            !local_packages.iter().any(|lp| &lp.name == *pkg)
                && !local_flakes.iter().any(|lf| &lf.name == *pkg)
        })
        .collect();

    // Build package entries
    let pkg_entries: String = filtered_packages
        .iter()
        .map(|pkg| format!("          {} = pkgs.{};", pkg, pkg))
        .collect::<Vec<_>>()
        .join("\n");

    // Build local inputs
    let mut local_inputs = String::new();
    let mut local_input_params = Vec::new();
    let mut local_overlays = String::new();
    let mut local_packages_entries = String::new();

    // Handle flake-type packages
    for flake in &local_flakes {
        local_inputs.push_str(&format!(
            "    {}.url = \"path:./packages/{}\";\n",
            flake.name, flake.name
        ));
        local_input_params.push(flake.name.clone());
        local_packages_entries.push_str(&format!(
            "          {} = inputs.{}.packages.${{system}}.default;\n",
            flake.name, flake.name
        ));
    }

    // Handle regular local packages
    for pkg in &local_packages {
        if let (Some(input_name), Some(input_url)) = (&pkg.input_name, &pkg.input_url) {
            local_inputs.push_str(&format!("    {}.url = \"{}\";\n", input_name, input_url));
            local_input_params.push(input_name.clone());
        }

        if let Some(overlay) = &pkg.overlay {
            local_overlays.push_str(&format!("          {}\n", overlay));
        }

        local_packages_entries
            .push_str(&format!("          {} = {};\n", pkg.name, pkg.package_expr));
    }

    // Build buildEnv paths
    let mut buildenv_paths: Vec<String> = filtered_packages.iter().map(|p| p.to_string()).collect();
    buildenv_paths.extend(local_packages.iter().map(|p| p.name.clone()));
    buildenv_paths.extend(local_flakes.iter().map(|f| f.name.clone()));

    let buildenv_paths_str: String = buildenv_paths
        .iter()
        .map(|p| format!("              {}", p))
        .collect::<Vec<_>>()
        .join("\n");

    // Build output parameters
    let output_params = if local_input_params.is_empty() {
        "self, nixpkgs".to_string()
    } else {
        format!("self, nixpkgs, {}", local_input_params.join(", "))
    };

    // Build overlays section
    let overlays_content = if !local_overlays.is_empty() {
        format!(
            "overlays = [
          # [nixy:local-overlays]
{}          # [/nixy:local-overlays]
        ];",
            local_overlays
        )
    } else {
        String::new()
    };

    // Build pkgs definition
    let pkgs_def = if !local_overlays.is_empty() {
        format!(
            "pkgsFor = system: import nixpkgs {{
        inherit system;
        {}
      }};
",
            overlays_content
        )
    } else {
        String::new()
    };

    let pkgs_binding = if !local_overlays.is_empty() {
        "let pkgs = pkgsFor system;"
    } else {
        "let pkgs = nixpkgs.legacyPackages.${system};"
    };

    // Add trailing newlines to preserved content if non-empty
    let custom_inputs = if preserved.custom_inputs.is_empty() {
        String::new()
    } else {
        format!("{}\n", preserved.custom_inputs.trim_end())
    };

    let custom_packages = if preserved.custom_packages.is_empty() {
        String::new()
    } else {
        format!("{}\n", preserved.custom_packages.trim_end())
    };

    let custom_paths = if preserved.custom_paths.is_empty() {
        String::new()
    } else {
        format!("{}\n", preserved.custom_paths.trim_end())
    };

    // Add newlines to entries if non-empty
    let pkg_entries = if pkg_entries.is_empty() {
        String::new()
    } else {
        format!("{}\n", pkg_entries)
    };

    let local_inputs = if local_inputs.is_empty() {
        String::new()
    } else {
        local_inputs
    };

    let local_packages_entries = if local_packages_entries.is_empty() {
        String::new()
    } else {
        local_packages_entries
    };

    let buildenv_paths_str = if buildenv_paths_str.is_empty() {
        String::new()
    } else {
        format!("{}\n", buildenv_paths_str)
    };

    format!(
        r#"{{
  description = "nixy managed packages";

  inputs = {{
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    # [nixy:local-inputs]
{local_inputs}    # [/nixy:local-inputs]
    # [nixy:custom-inputs]
{custom_inputs}    # [/nixy:custom-inputs]
  }};

  outputs = {{ {output_params} }}@inputs:
    let
      systems = [ "x86_64-linux" "aarch64-linux" "x86_64-darwin" "aarch64-darwin" ];
      forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f system);
      {pkgs_def}
    in {{
      # Profile packages (nixy install)
      packages = forAllSystems (system:
        {pkgs_binding}
        in rec {{
          # [nixy:packages]
{pkg_entries}          # [/nixy:packages]
          # [nixy:local-packages]
{local_packages_entries}          # [/nixy:local-packages]
          # [nixy:custom-packages]
{custom_packages}          # [/nixy:custom-packages]

          # Unified environment for atomic install (nixy sync)
          default = pkgs.buildEnv {{
            name = "nixy-env";
            paths = [
              # [nixy:env-paths]
{buildenv_paths_str}              # [/nixy:env-paths]
              # [nixy:custom-paths]
{custom_paths}              # [/nixy:custom-paths]
            ];
            extraOutputsToInstall = [ "man" "doc" "info" ];
          }};
        }});
    }};
}}
"#
    )
}

/// Check if flake has custom modifications outside nixy markers
pub fn has_custom_modifications(flake_path: &Path, packages: &[String], flake_dir: &Path) -> bool {
    let actual_content = match std::fs::read_to_string(flake_path) {
        Ok(c) => c,
        Err(_) => return false,
    };

    let preserved = PreservedContent::from_file(flake_path);
    let clean_content = generate_flake(packages, Some(flake_dir), Some(&preserved));

    actual_content != clean_content
}

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

    #[test]
    fn test_generate_empty_flake() {
        let flake = generate_flake(&[], None, None);

        // Should have required markers
        assert!(flake.contains("# [nixy:packages]"));
        assert!(flake.contains("# [/nixy:packages]"));
        assert!(flake.contains("# [nixy:local-packages]"));
        assert!(flake.contains("# [/nixy:local-packages]"));
        assert!(flake.contains("# [nixy:custom-packages]"));
        assert!(flake.contains("# [/nixy:custom-packages]"));
        assert!(flake.contains("# [nixy:env-paths]"));
        assert!(flake.contains("# [/nixy:env-paths]"));
        assert!(flake.contains("# [nixy:custom-paths]"));
        assert!(flake.contains("# [/nixy:custom-paths]"));
        assert!(flake.contains("# [nixy:local-inputs]"));
        assert!(flake.contains("# [/nixy:local-inputs]"));
        assert!(flake.contains("# [nixy:custom-inputs]"));
        assert!(flake.contains("# [/nixy:custom-inputs]"));

        // Should have buildEnv
        assert!(flake.contains("default = pkgs.buildEnv"));
        assert!(flake.contains("name = \"nixy-env\""));
        assert!(flake.contains("extraOutputsToInstall"));

        // Should NOT have devShells
        assert!(!flake.contains("devShells"));
    }

    #[test]
    fn test_generate_flake_with_packages() {
        let packages = vec!["ripgrep".to_string(), "fzf".to_string(), "bat".to_string()];
        let flake = generate_flake(&packages, None, None);

        // Should have package entries
        assert!(flake.contains("ripgrep = pkgs.ripgrep;"));
        assert!(flake.contains("fzf = pkgs.fzf;"));
        assert!(flake.contains("bat = pkgs.bat;"));

        // Should have packages in env-paths
        let env_paths_section =
            extract_section(&flake, "# [nixy:env-paths]", "# [/nixy:env-paths]");
        assert!(env_paths_section.contains("ripgrep"));
        assert!(env_paths_section.contains("fzf"));
        assert!(env_paths_section.contains("bat"));
    }

    #[test]
    fn test_generate_flake_preserves_custom_content() {
        let preserved = PreservedContent {
            custom_inputs: "    my-overlay.url = \"github:user/repo\";".to_string(),
            custom_packages: "          my-pkg = pkgs.hello;".to_string(),
            custom_paths: "              my-pkg".to_string(),
        };

        let flake = generate_flake(&[], None, Some(&preserved));

        // Should preserve custom content
        assert!(flake.contains("my-overlay.url = \"github:user/repo\""));
        assert!(flake.contains("my-pkg = pkgs.hello"));

        // Check custom-paths section
        let custom_paths_section =
            extract_section(&flake, "# [nixy:custom-paths]", "# [/nixy:custom-paths]");
        assert!(custom_paths_section.contains("my-pkg"));
    }

    #[test]
    fn test_flake_has_correct_nixpkgs_url() {
        let flake = generate_flake(&[], None, None);
        assert!(flake.contains("nixpkgs.url = \"github:NixOS/nixpkgs/nixos-unstable\""));
    }

    #[test]
    fn test_flake_has_all_systems() {
        let flake = generate_flake(&[], None, None);
        assert!(flake.contains("x86_64-linux"));
        assert!(flake.contains("aarch64-linux"));
        assert!(flake.contains("x86_64-darwin"));
        assert!(flake.contains("aarch64-darwin"));
    }

    #[test]
    fn test_flake_uses_legacy_packages() {
        let flake = generate_flake(&[], None, None);
        assert!(flake.contains("nixpkgs.legacyPackages.${system}"));
    }

    #[test]
    fn test_buildenv_has_extra_outputs() {
        let flake = generate_flake(&[], None, None);
        assert!(flake.contains("extraOutputsToInstall = [ \"man\" \"doc\" \"info\" ]"));
    }

    // Tests matching bash test_nixy.sh

    #[test]
    fn test_flake_has_no_devshells() {
        // test_flake_has_no_devshells
        let packages = vec!["ripgrep".to_string()];
        let flake = generate_flake(&packages, None, None);

        // Flakes should NOT have devShells
        assert!(!flake.contains("devShells"));
        // But should have packages section
        assert!(flake.contains("packages = forAllSystems"));
    }

    #[test]
    fn test_flake_structure_has_markers() {
        // test_flake_structure_has_markers
        let flake = generate_flake(&[], None, None);

        assert!(flake.contains("# [nixy:packages]"));
        assert!(flake.contains("# [/nixy:packages]"));
        assert!(flake.contains("# [nixy:local-packages]"));
        assert!(flake.contains("# [/nixy:local-packages]"));
    }

    #[test]
    fn test_flake_has_custom_markers() {
        // test_flake_has_custom_markers
        let flake = generate_flake(&[], None, None);

        assert!(flake.contains("# [nixy:custom-inputs]"));
        assert!(flake.contains("# [/nixy:custom-inputs]"));
        assert!(flake.contains("# [nixy:custom-packages]"));
        assert!(flake.contains("# [/nixy:custom-packages]"));
        assert!(flake.contains("# [nixy:custom-paths]"));
        assert!(flake.contains("# [/nixy:custom-paths]"));
    }

    #[test]
    fn test_flake_has_buildenv_default() {
        // test_flake_has_buildenv_default
        let flake = generate_flake(&[], None, None);

        assert!(flake.contains("default = pkgs.buildEnv"));
        assert!(flake.contains("name = \"nixy-env\""));
        assert!(flake.contains("# [nixy:env-paths]"));
        assert!(flake.contains("# [/nixy:env-paths]"));
    }

    #[test]
    fn test_buildenv_contains_all_packages() {
        // test_buildenv_contains_all_packages
        let packages = vec!["ripgrep".to_string(), "fzf".to_string(), "bat".to_string()];
        let flake = generate_flake(&packages, None, None);

        let env_paths_section =
            extract_section(&flake, "# [nixy:env-paths]", "# [/nixy:env-paths]");
        assert!(env_paths_section.contains("ripgrep"));
        assert!(env_paths_section.contains("fzf"));
        assert!(env_paths_section.contains("bat"));
    }

    #[test]
    fn test_individual_packages_still_accessible() {
        // test_individual_packages_still_accessible
        let packages = vec!["ripgrep".to_string(), "fzf".to_string()];
        let flake = generate_flake(&packages, None, None);

        // Individual package attributes should still exist
        assert!(flake.contains("ripgrep = pkgs.ripgrep;"));
        assert!(flake.contains("fzf = pkgs.fzf;"));
    }

    #[test]
    fn test_empty_flake_has_empty_buildenv() {
        // test_empty_flake_has_empty_buildenv
        let flake = generate_flake(&[], None, None);

        // Empty flake should have buildEnv structure with empty paths
        assert!(flake.contains("default = pkgs.buildEnv"));
        assert!(flake.contains("paths = ["));
        assert!(flake.contains("extraOutputsToInstall = [ \"man\" \"doc\" \"info\" ]"));
    }

    #[test]
    fn test_flake_has_env_paths_markers() {
        // test_flake_structure_has_env_paths_markers
        let flake = generate_flake(&[], None, None);

        assert!(flake.contains("# [nixy:env-paths]"));
        assert!(flake.contains("# [/nixy:env-paths]"));
    }

    #[test]
    fn test_custom_inputs_preserved() {
        // test_custom_inputs_preserved_during_regeneration
        let preserved = PreservedContent {
            custom_inputs: "    my-overlay.url = \"github:user/my-overlay\";".to_string(),
            custom_packages: String::new(),
            custom_paths: String::new(),
        };

        let flake = generate_flake(&[], None, Some(&preserved));
        assert!(flake.contains("my-overlay.url = \"github:user/my-overlay\""));

        // Adding packages should preserve custom inputs
        let flake_with_pkg = generate_flake(&["ripgrep".to_string()], None, Some(&preserved));
        assert!(flake_with_pkg.contains("my-overlay.url = \"github:user/my-overlay\""));
        assert!(flake_with_pkg.contains("ripgrep = pkgs.ripgrep;"));
    }

    #[test]
    fn test_custom_packages_preserved() {
        // test_custom_packages_preserved_during_regeneration
        let preserved = PreservedContent {
            custom_inputs: String::new(),
            custom_packages:
                "          my-custom-pkg = pkgs.hello.overrideAttrs { pname = \"my-custom\"; };"
                    .to_string(),
            custom_paths: String::new(),
        };

        let flake = generate_flake(&[], None, Some(&preserved));
        assert!(flake.contains("my-custom-pkg"));

        // Adding packages should preserve custom packages
        let flake_with_pkg = generate_flake(&["ripgrep".to_string()], None, Some(&preserved));
        assert!(flake_with_pkg.contains("my-custom-pkg"));
        assert!(flake_with_pkg.contains("ripgrep = pkgs.ripgrep;"));
    }

    #[test]
    fn test_custom_paths_preserved() {
        // test_custom_paths_preserved_during_regeneration
        let preserved = PreservedContent {
            custom_inputs: String::new(),
            custom_packages: String::new(),
            custom_paths: "              my-custom-pkg".to_string(),
        };

        let flake = generate_flake(&[], None, Some(&preserved));
        let custom_paths_section =
            extract_section(&flake, "# [nixy:custom-paths]", "# [/nixy:custom-paths]");
        assert!(custom_paths_section.contains("my-custom-pkg"));
    }

    #[test]
    fn test_has_custom_modifications_detects_changes() {
        use std::fs;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let flake_dir = temp.path();
        let flake_path = flake_dir.join("flake.nix");

        // Write a clean flake
        let clean_flake = generate_flake(&["ripgrep".to_string()], Some(flake_dir), None);
        fs::write(&flake_path, &clean_flake).unwrap();

        // No modifications should be detected
        assert!(!has_custom_modifications(
            &flake_path,
            &["ripgrep".to_string()],
            flake_dir
        ));

        // Add a modification outside markers
        let modified =
            clean_flake.replace("nixpkgs.url", "# OUTSIDE MARKER COMMENT\n    nixpkgs.url");
        fs::write(&flake_path, &modified).unwrap();

        // Modifications should be detected
        assert!(has_custom_modifications(
            &flake_path,
            &["ripgrep".to_string()],
            flake_dir
        ));
    }

    #[test]
    fn test_preserved_content_from_file() {
        use std::fs;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let flake_path = temp.path().join("flake.nix");

        // Create a flake with custom content
        let preserved = PreservedContent {
            custom_inputs: "    custom-input.url = \"github:test/test\";".to_string(),
            custom_packages: "          custom-pkg = pkgs.hello;".to_string(),
            custom_paths: "              custom-pkg".to_string(),
        };
        let flake = generate_flake(&[], None, Some(&preserved));
        fs::write(&flake_path, &flake).unwrap();

        // Read preserved content back
        let read_preserved = PreservedContent::from_file(&flake_path);
        assert!(read_preserved.custom_inputs.contains("custom-input.url"));
        assert!(read_preserved
            .custom_packages
            .contains("custom-pkg = pkgs.hello"));
        assert!(read_preserved.custom_paths.contains("custom-pkg"));
    }

    #[test]
    fn test_preserved_content_from_nonexistent_file() {
        let preserved = PreservedContent::from_file(Path::new("/nonexistent/file.nix"));
        assert!(preserved.custom_inputs.is_empty());
        assert!(preserved.custom_packages.is_empty());
        assert!(preserved.custom_paths.is_empty());
    }

    fn extract_section(content: &str, start: &str, end: &str) -> String {
        let mut in_section = false;
        let mut result = String::new();

        for line in content.lines() {
            if line.contains(end) {
                break;
            }
            if in_section {
                result.push_str(line);
                result.push('\n');
            }
            if line.contains(start) {
                in_section = true;
            }
        }

        result
    }
}