nixy-rs 0.2.0

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
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
//! Flake.nix template generation.
//!
//! This module generates `flake.nix` content from the package state. It handles:
//! - Standard nixpkgs packages
//! - Custom packages from external flakes
//! - Local packages (`.nix` files in `packages/` directory)
//! - Local flakes (subdirectories with `flake.nix`)
//!
//! The generated flake uses `buildEnv` to create a unified environment with
//! all installed packages.

use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::Path;

use super::parser::collect_local_packages;
use super::{LocalFlake, LocalPackage};
use crate::error::Result;
use crate::state::{CustomPackage, PackageState, ResolvedNixpkgPackage};

/// Intermediate representation for building flake content
struct FlakeBuilder {
    /// Additional flake inputs (beyond nixpkgs)
    inputs: String,
    /// Set of input names already added
    seen_inputs: HashSet<String>,
    /// Overlay expressions for pkgs customization
    overlays: String,
    /// Standard package entries (pkg = pkgs.pkg) - legacy packages
    standard_entries: String,
    /// Resolved package entries from Nixhub (with specific nixpkgs commits)
    resolved_entries: String,
    /// Local package entries
    local_entries: String,
    /// Custom package entries from external flakes
    custom_entries: String,
    /// Package names for buildEnv paths
    buildenv_paths: Vec<String>,
}

impl FlakeBuilder {
    fn new() -> Self {
        Self {
            inputs: String::new(),
            seen_inputs: HashSet::new(),
            overlays: String::new(),
            standard_entries: String::new(),
            resolved_entries: String::new(),
            local_entries: String::new(),
            custom_entries: String::new(),
            buildenv_paths: Vec::new(),
        }
    }

    /// Add standard nixpkgs packages (legacy, from default nixpkgs)
    fn add_standard_packages(&mut self, packages: &[&String]) {
        let entries: Vec<String> = packages
            .iter()
            .map(|pkg| format!("          {} = pkgs.{};", pkg, pkg))
            .collect();

        if !entries.is_empty() {
            self.standard_entries = format!("{}\n", entries.join("\n"));
        }

        self.buildenv_paths
            .extend(packages.iter().map(|p| p.to_string()));
    }

    /// Add resolved nixpkgs packages (with specific commits from Nixhub)
    fn add_resolved_packages(&mut self, packages: &[ResolvedNixpkgPackage]) {
        if packages.is_empty() {
            return;
        }

        // Group packages by commit hash
        let mut by_commit: HashMap<&str, Vec<&ResolvedNixpkgPackage>> = HashMap::new();
        for pkg in packages {
            by_commit.entry(&pkg.commit_hash).or_default().push(pkg);
        }

        // Add inputs and entries for each commit
        for (commit, pkgs) in &by_commit {
            let input_name = format!("nixpkgs-{}", &commit[..8.min(commit.len())]);

            // Add input if not already seen
            if self.seen_inputs.insert(input_name.clone()) {
                self.inputs.push_str(&format!(
                    "    {}.url = \"github:NixOS/nixpkgs/{}\";\n",
                    input_name, commit
                ));
            }

            // Add package entries
            for pkg in pkgs {
                self.resolved_entries.push_str(&format!(
                    "          {} = inputs.{}.legacyPackages.${{system}}.{};\n",
                    pkg.name, input_name, pkg.attribute_path
                ));
                self.buildenv_paths.push(pkg.name.clone());
            }
        }
    }

    /// Add local flake-type packages from packages/ directory
    fn add_local_flakes(&mut self, flakes: &[LocalFlake]) {
        for flake in flakes {
            self.inputs.push_str(&format!(
                "    {}.url = \"path:./packages/{}\";\n",
                flake.name, flake.name
            ));
            self.seen_inputs.insert(flake.name.clone());
            self.local_entries.push_str(&format!(
                "          {} = inputs.{}.packages.${{system}}.default;\n",
                flake.name, flake.name
            ));
            self.buildenv_paths.push(flake.name.clone());
        }
    }

    /// Add local .nix file packages from packages/ directory
    fn add_local_packages(&mut self, packages: &[LocalPackage]) {
        for pkg in packages {
            if let (Some(input_name), Some(input_url)) = (&pkg.input_name, &pkg.input_url) {
                if self.seen_inputs.insert(input_name.clone()) {
                    self.inputs
                        .push_str(&format!("    {}.url = \"{}\";\n", input_name, input_url));
                }
            }

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

            self.local_entries
                .push_str(&format!("          {} = {};\n", pkg.name, pkg.package_expr));
            self.buildenv_paths.push(pkg.name.clone());
        }
    }

    /// Add custom packages from external flakes
    fn add_custom_packages(&mut self, packages: &[CustomPackage]) {
        for pkg in packages {
            if self.seen_inputs.insert(pkg.input_name.clone()) {
                self.inputs.push_str(&format!(
                    "    {}.url = \"{}\";\n",
                    pkg.input_name, pkg.input_url
                ));
            }

            self.custom_entries.push_str(&format!(
                "          {} = inputs.{}.{}.${{system}}.{};\n",
                pkg.name,
                pkg.input_name,
                pkg.package_output,
                pkg.source_package_name()
            ));
            self.buildenv_paths.push(pkg.name.clone());
        }
    }

    /// Build the output function parameters
    fn build_output_params(&self) -> String {
        if self.seen_inputs.is_empty() {
            "self, nixpkgs".to_string()
        } else {
            let mut inputs_list: Vec<_> = self.seen_inputs.iter().cloned().collect();
            inputs_list.sort();
            format!("self, nixpkgs, {}", inputs_list.join(", "))
        }
    }

    /// Build the pkgs definition (with or without overlays)
    fn build_pkgs_definition(&self) -> (String, &'static str) {
        if self.overlays.is_empty() {
            (
                String::new(),
                "let pkgs = nixpkgs.legacyPackages.${system};",
            )
        } else {
            let overlays_content = format!("overlays = [\n{}        ];", self.overlays);
            let pkgs_def = format!(
                "pkgsFor = system: import nixpkgs {{
        inherit system;
        {}
      }};
",
                overlays_content
            );
            (pkgs_def, "let pkgs = pkgsFor system;")
        }
    }

    /// Build the buildEnv paths section
    fn build_paths_section(&self) -> String {
        if self.buildenv_paths.is_empty() {
            String::new()
        } else {
            let paths: Vec<String> = self
                .buildenv_paths
                .iter()
                .map(|p| format!("              {}", p))
                .collect();
            format!("{}\n", paths.join("\n"))
        }
    }

    /// Generate the final flake.nix content
    fn build(self) -> String {
        let output_params = self.build_output_params();
        let (pkgs_def, pkgs_binding) = self.build_pkgs_definition();
        let buildenv_paths_str = self.build_paths_section();

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

  inputs = {{
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
{all_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 {{
      packages = forAllSystems (system:
        {pkgs_binding}
        in rec {{
{pkg_entries}{resolved_entries}{local_entries}{custom_entries}
          default = pkgs.buildEnv {{
            name = "nixy-env";
            paths = [
{buildenv_paths_str}            ];
            extraOutputsToInstall = [ "man" "doc" "info" ];
          }};
        }});
    }};
}}
"#,
            all_inputs = self.inputs,
            output_params = output_params,
            pkgs_def = pkgs_def,
            pkgs_binding = pkgs_binding,
            pkg_entries = self.standard_entries,
            resolved_entries = self.resolved_entries,
            local_entries = self.local_entries,
            custom_entries = self.custom_entries,
            buildenv_paths_str = buildenv_paths_str,
        )
    }
}

/// Generate flake.nix content from package state
pub fn generate_flake(state: &PackageState, flake_dir: Option<&Path>) -> String {
    // 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 legacy packages list
    let filtered_legacy_packages: Vec<&String> = state
        .packages
        .iter()
        .filter(|pkg| {
            !local_packages.iter().any(|lp| &lp.name == *pkg)
                && !local_flakes.iter().any(|lf| &lf.name == *pkg)
        })
        .collect();

    // Filter out local packages from resolved packages list
    let filtered_resolved_packages: Vec<ResolvedNixpkgPackage> = state
        .resolved_packages
        .iter()
        .filter(|pkg| {
            !local_packages.iter().any(|lp| lp.name == pkg.name)
                && !local_flakes.iter().any(|lf| lf.name == pkg.name)
        })
        .cloned()
        .collect();

    let mut builder = FlakeBuilder::new();
    builder.add_standard_packages(&filtered_legacy_packages);
    builder.add_resolved_packages(&filtered_resolved_packages);
    builder.add_local_flakes(&local_flakes);
    builder.add_local_packages(&local_packages);
    builder.add_custom_packages(&state.custom_packages);
    builder.build()
}

/// Regenerate flake.nix from state
pub fn regenerate_flake(flake_dir: &Path, state: &PackageState) -> Result<()> {
    let flake_path = flake_dir.join("flake.nix");
    fs::create_dir_all(flake_dir)?;
    let content = generate_flake(state, Some(flake_dir));
    fs::write(&flake_path, content)?;
    Ok(())
}

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

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

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

        // Should NOT have markers
        assert!(!flake.contains("# [nixy:"));
        assert!(!flake.contains("# [/nixy:"));

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

    #[test]
    fn test_generate_flake_with_packages() {
        let mut state = PackageState::default();
        state.add_package("ripgrep");
        state.add_package("fzf");
        state.add_package("bat");

        let flake = generate_flake(&state, 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 paths
        assert!(flake.contains("ripgrep"));
        assert!(flake.contains("fzf"));
        assert!(flake.contains("bat"));
    }

    #[test]
    fn test_generate_flake_with_custom_packages() {
        let mut state = PackageState::default();
        state.add_custom_package(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,
        });

        let flake = generate_flake(&state, None);

        // Should have custom input
        assert!(
            flake.contains("neovim-nightly.url = \"github:nix-community/neovim-nightly-overlay\"")
        );

        // Should have custom package entry
        assert!(flake.contains("neovim = inputs.neovim-nightly.packages.${system}.neovim;"));

        // Should have neovim in paths
        assert!(flake.contains("neovim"));
    }

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

    #[test]
    fn test_flake_has_all_systems() {
        let state = PackageState::default();
        let flake = generate_flake(&state, 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 state = PackageState::default();
        let flake = generate_flake(&state, None);
        assert!(flake.contains("nixpkgs.legacyPackages.${system}"));
    }

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

    #[test]
    fn test_flake_has_no_devshells() {
        let mut state = PackageState::default();
        state.add_package("ripgrep");
        let flake = generate_flake(&state, None);

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

    #[test]
    fn test_flake_has_no_markers() {
        let mut state = PackageState::default();
        state.add_package("hello");
        state.add_custom_package(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,
        });

        let flake = generate_flake(&state, None);

        // Should NOT have any markers
        assert!(!flake.contains("# [nixy:"));
        assert!(!flake.contains("# [/nixy:"));
    }

    #[test]
    fn test_multiple_custom_packages_share_input() {
        let mut state = PackageState::default();
        state.add_custom_package(CustomPackage {
            name: "hello".to_string(),
            input_name: "nixpkgs-unstable".to_string(),
            input_url: "github:NixOS/nixpkgs/nixos-unstable".to_string(),
            package_output: "legacyPackages".to_string(),
            source_name: None,
        });
        state.add_custom_package(CustomPackage {
            name: "world".to_string(),
            input_name: "nixpkgs-unstable".to_string(),
            input_url: "github:NixOS/nixpkgs/nixos-unstable".to_string(),
            package_output: "legacyPackages".to_string(),
            source_name: None,
        });

        let flake = generate_flake(&state, None);

        // Input should only appear once
        let count = flake.matches("nixpkgs-unstable.url").count();
        assert_eq!(count, 1, "Input should only appear once");
    }

    #[test]
    fn test_buildenv_contains_all_packages() {
        let mut state = PackageState::default();
        state.add_package("ripgrep");
        state.add_package("fzf");
        state.add_custom_package(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,
        });

        let flake = generate_flake(&state, None);

        // Extract paths section
        let paths_start = flake.find("paths = [").unwrap();
        let paths_end = flake[paths_start..].find("];").unwrap();
        let paths_section = &flake[paths_start..paths_start + paths_end];

        assert!(paths_section.contains("ripgrep"));
        assert!(paths_section.contains("fzf"));
        assert!(paths_section.contains("neovim"));
    }

    #[test]
    fn test_empty_flake_has_empty_buildenv() {
        let state = PackageState::default();
        let flake = generate_flake(&state, 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_generate_flake_with_resolved_packages() {
        let mut state = PackageState::default();
        state.add_resolved_package(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: "abc123def456".to_string(),
        });

        let flake = generate_flake(&state, None);

        // Should have nixpkgs input with commit hash
        assert!(flake.contains("nixpkgs-abc123de.url = \"github:NixOS/nixpkgs/abc123def456\""));

        // Should have package entry using attribute_path
        assert!(
            flake.contains("nodejs = inputs.nixpkgs-abc123de.legacyPackages.${system}.nodejs_20;")
        );

        // Should have nodejs in paths
        let paths_start = flake.find("paths = [").unwrap();
        let paths_end = flake[paths_start..].find("];").unwrap();
        let paths_section = &flake[paths_start..paths_start + paths_end];
        assert!(paths_section.contains("nodejs"));
    }

    #[test]
    fn test_resolved_packages_share_commit_input() {
        let mut state = PackageState::default();
        state.add_resolved_package(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: "abc123def456".to_string(),
        });
        state.add_resolved_package(ResolvedNixpkgPackage {
            name: "python".to_string(),
            version_spec: Some("3.11".to_string()),
            resolved_version: "3.11.5".to_string(),
            attribute_path: "python311".to_string(),
            commit_hash: "abc123def456".to_string(), // Same commit
        });

        let flake = generate_flake(&state, None);

        // Input should only appear once
        let count = flake.matches("nixpkgs-abc123de.url").count();
        assert_eq!(count, 1, "Same commit input should only appear once");

        // Both packages should use the same input
        assert!(
            flake.contains("nodejs = inputs.nixpkgs-abc123de.legacyPackages.${system}.nodejs_20;")
        );
        assert!(
            flake.contains("python = inputs.nixpkgs-abc123de.legacyPackages.${system}.python311;")
        );
    }

    #[test]
    fn test_resolved_packages_different_commits() {
        let mut state = PackageState::default();
        state.add_resolved_package(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: "abc123def456".to_string(),
        });
        state.add_resolved_package(ResolvedNixpkgPackage {
            name: "python".to_string(),
            version_spec: Some("3.11".to_string()),
            resolved_version: "3.11.5".to_string(),
            attribute_path: "python311".to_string(),
            commit_hash: "xyz789ghi012".to_string(), // Different commit
        });

        let flake = generate_flake(&state, None);

        // Should have two different nixpkgs inputs
        assert!(flake.contains("nixpkgs-abc123de.url = \"github:NixOS/nixpkgs/abc123def456\""));
        assert!(flake.contains("nixpkgs-xyz789gh.url = \"github:NixOS/nixpkgs/xyz789ghi012\""));

        // Each package should use its own input
        assert!(
            flake.contains("nodejs = inputs.nixpkgs-abc123de.legacyPackages.${system}.nodejs_20;")
        );
        assert!(
            flake.contains("python = inputs.nixpkgs-xyz789gh.legacyPackages.${system}.python311;")
        );
    }

    #[test]
    fn test_mixed_legacy_and_resolved_packages() {
        let mut state = PackageState::default();
        // Legacy package (uses default nixpkgs)
        state.add_package("ripgrep");
        // Resolved package (uses specific commit)
        state.add_resolved_package(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: "abc123def456".to_string(),
        });

        let flake = generate_flake(&state, None);

        // Should have default nixpkgs for legacy
        assert!(flake.contains("nixpkgs.url = \"github:NixOS/nixpkgs/nixos-unstable\""));
        assert!(flake.contains("ripgrep = pkgs.ripgrep;"));

        // Should have specific commit for resolved
        assert!(flake.contains("nixpkgs-abc123de.url = \"github:NixOS/nixpkgs/abc123def456\""));
        assert!(
            flake.contains("nodejs = inputs.nixpkgs-abc123de.legacyPackages.${system}.nodejs_20;")
        );

        // Both should be in paths
        let paths_start = flake.find("paths = [").unwrap();
        let paths_end = flake[paths_start..].find("];").unwrap();
        let paths_section = &flake[paths_start..paths_start + paths_end];
        assert!(paths_section.contains("ripgrep"));
        assert!(paths_section.contains("nodejs"));
    }
}