nixy-rs 0.2.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
//! Nix command wrapper for nixy.
//!
//! This module provides a safe interface to Nix CLI commands. All Nix operations
//! (build, search, flake update, etc.) go through this module.
//!
//! Key features:
//! - Automatically enables required experimental features (flakes, nix-command)
//! - Captures stderr for better error messages
//! - Handles path escaping for flake references

use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use crate::config::NIX_FLAGS;
use crate::error::{Error, Result};

/// Wrapper for Nix command execution
pub struct Nix;

/// Format a path as a flake reference with optional output
/// Handles paths with spaces by using proper escaping
fn flake_ref(path: &Path, output: Option<&str>) -> String {
    let path_str = path.to_string_lossy();
    // URL-encode spaces for nix flake references
    let encoded = path_str.replace(' ', "%20");
    match output {
        Some(out) => format!("{}#{}", encoded, out),
        None => encoded.to_string(),
    }
}

impl Nix {
    /// Check if nix is installed
    pub fn check_installed() -> Result<()> {
        Command::new("nix")
            .arg("--version")
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .map_err(|_| Error::NixNotInstalled)?;
        Ok(())
    }

    /// Get the current system (e.g., "x86_64-darwin", "aarch64-linux")
    pub fn current_system() -> Result<String> {
        let output = Command::new("nix")
            .args(NIX_FLAGS)
            .args([
                "eval",
                "--impure",
                "--expr",
                "builtins.currentSystem",
                "--raw",
            ])
            .output()
            .map_err(|e| Error::NixCommand(e.to_string()))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(Error::NixCommand(format!(
                "Failed to get current system: {}",
                stderr.trim()
            )));
        }

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    /// Build a flake and create an out-link
    pub fn build(flake_dir: &Path, output: &str, out_link: &Path) -> Result<()> {
        let ref_str = flake_ref(flake_dir, Some(output));
        let out_link_str = out_link.to_string_lossy();

        let status = Command::new("nix")
            .args(NIX_FLAGS)
            .env("NIXPKGS_ALLOW_UNFREE", "1")
            .args(["build", &ref_str, "--out-link", &out_link_str, "--impure"])
            .status()
            .map_err(|e| Error::NixCommand(e.to_string()))?;

        if !status.success() {
            return Err(Error::NixCommand(
                "Failed to build environment. See output above for details.".to_string(),
            ));
        }

        Ok(())
    }

    /// Search for packages in nixpkgs (passes through to stdout/stderr)
    #[allow(dead_code)]
    pub fn search(query: &str) -> Result<()> {
        let status = Command::new("nix")
            .args(NIX_FLAGS)
            .args(["search", "nixpkgs", query])
            .status()
            .map_err(|e| Error::NixCommand(e.to_string()))?;

        if !status.success() {
            return Err(Error::NixCommand(format!(
                "Search failed for query '{}'",
                query
            )));
        }

        Ok(())
    }

    /// Update flake inputs
    pub fn flake_update(flake_dir: &Path, inputs: &[String]) -> Result<()> {
        let mut cmd = Command::new("nix");
        cmd.args(NIX_FLAGS).arg("flake").arg("update");

        for input in inputs {
            cmd.arg(input);
        }

        cmd.arg("--flake").arg(flake_dir);

        let status = cmd.status().map_err(|e| Error::NixCommand(e.to_string()))?;

        if !status.success() {
            return Err(Error::NixCommand(
                "Failed to update flake. See output above for details.".to_string(),
            ));
        }

        Ok(())
    }

    /// Update all flake inputs
    pub fn flake_update_all(flake_dir: &Path) -> Result<()> {
        let status = Command::new("nix")
            .args(NIX_FLAGS)
            .args(["flake", "update", "--flake"])
            .arg(flake_dir)
            .status()
            .map_err(|e| Error::NixCommand(e.to_string()))?;

        if !status.success() {
            return Err(Error::NixCommand(
                "Failed to update flake. See output above for details.".to_string(),
            ));
        }

        Ok(())
    }

    /// Look up a flake URL from the nix registry
    pub fn registry_lookup(name: &str) -> Result<Option<String>> {
        let output = Command::new("nix")
            .args(NIX_FLAGS)
            .args(["registry", "list"])
            .output()
            .map_err(|e| Error::NixCommand(e.to_string()))?;

        if !output.status.success() {
            return Ok(None);
        }

        let target = format!("flake:{}", name);
        let stdout = String::from_utf8_lossy(&output.stdout);

        for line in stdout.lines() {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 3 && parts[1] == target {
                return Ok(Some(parts[2].to_string()));
            }
        }

        Ok(None)
    }

    /// Validate that a package exists in nixpkgs
    #[allow(dead_code)]
    pub fn validate_package(pkg: &str) -> Result<bool> {
        let attr = format!("nixpkgs#{}.type", pkg);

        let output = Command::new("nix")
            .args(NIX_FLAGS)
            .args(["eval", &attr])
            .output()
            .map_err(|e| Error::NixCommand(e.to_string()))?;

        if !output.status.success() {
            return Ok(false);
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        Ok(stdout.contains("derivation"))
    }

    /// Validate that a package exists in a flake
    /// Returns the output type ("packages" or "legacyPackages") if found
    pub fn validate_flake_package(flake_url: &str, pkg: &str) -> Result<Option<String>> {
        let system = Self::current_system()?;

        // Try packages.<system>.<pkg> first
        let attr = format!("{}#packages.{}.{}.type", flake_url, system, pkg);
        let output = Command::new("nix")
            .args(NIX_FLAGS)
            .args(["eval", &attr])
            .output()
            .map_err(|e| Error::NixCommand(e.to_string()))?;

        if output.status.success() && String::from_utf8_lossy(&output.stdout).contains("derivation")
        {
            return Ok(Some("packages".to_string()));
        }

        // Try legacyPackages.<system>.<pkg>
        let attr = format!("{}#legacyPackages.{}.{}.type", flake_url, system, pkg);
        let output = Command::new("nix")
            .args(NIX_FLAGS)
            .args(["eval", &attr])
            .output()
            .map_err(|e| Error::NixCommand(e.to_string()))?;

        if output.status.success() && String::from_utf8_lossy(&output.stdout).contains("derivation")
        {
            return Ok(Some("legacyPackages".to_string()));
        }

        Ok(None)
    }

    /// List packages in a flake
    pub fn list_flake_packages(flake_url: &str, output_type: Option<&str>) -> Result<Vec<String>> {
        let system = Self::current_system()?;

        let candidates = match output_type {
            Some(t) => vec![format!("{}.{}", t, system)],
            None => vec![
                format!("packages.{}", system),
                format!("legacyPackages.{}", system),
            ],
        };

        for attr_path in candidates {
            let attr = format!("{}#{}", flake_url, attr_path);
            let output = Command::new("nix")
                .args(NIX_FLAGS)
                .args([
                    "eval",
                    &attr,
                    "--apply",
                    r#"pkgs: builtins.concatStringsSep "\n" (builtins.attrNames pkgs)"#,
                    "--raw",
                ])
                .output()
                .map_err(|e| Error::NixCommand(e.to_string()))?;

            if output.status.success() {
                return Ok(String::from_utf8_lossy(&output.stdout)
                    .lines()
                    .map(String::from)
                    .collect());
            }
        }

        Ok(Vec::new())
    }

    /// Prefetch a flake and return its store path
    pub fn flake_prefetch(url: &str) -> Result<PathBuf> {
        let output = Command::new("nix")
            .args(NIX_FLAGS)
            .args(["flake", "prefetch", "--json", url])
            .output()
            .map_err(|e| Error::NixCommand(e.to_string()))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(Error::NixCommand(format!(
                "Failed to prefetch flake '{}': {}",
                url,
                stderr.trim()
            )));
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let json: serde_json::Value =
            serde_json::from_str(&stdout).map_err(|e| Error::NixCommand(e.to_string()))?;

        json["storePath"]
            .as_str()
            .map(PathBuf::from)
            .ok_or_else(|| Error::NixCommand("Missing storePath in flake prefetch output".into()))
    }

    /// Get package source path via meta.position
    /// Returns the file path (without line number) from the position attribute
    pub fn get_package_source_path(commit: &str, attr: &str, system: &str) -> Result<PathBuf> {
        let flake_ref = format!(
            "github:NixOS/nixpkgs/{}#legacyPackages.{}.{}.meta.position",
            commit, system, attr
        );

        let output = Command::new("nix")
            .args(NIX_FLAGS)
            .args(["eval", "--raw", &flake_ref])
            .output()
            .map_err(|e| Error::NixCommand(e.to_string()))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(Error::NixCommand(format!(
                "Failed to get source path for '{}': {}",
                attr,
                stderr.trim()
            )));
        }

        let position = String::from_utf8_lossy(&output.stdout);
        // Position format is "path:line", we only want the path.
        // Using rsplit_once is safe here because Nix store paths never contain colons
        // (Nix doesn't run on Windows, and Unix paths don't use colons as path separators).
        let path = position
            .rsplit_once(':')
            .map(|(p, _)| p)
            .unwrap_or(&position);

        Ok(PathBuf::from(path))
    }

    /// Get flake inputs from flake.lock
    pub fn get_flake_inputs(lock_file: &Path) -> Result<Vec<String>> {
        let lock_path = lock_file.to_string_lossy();
        let expr = format!(
            r#"builtins.attrNames (builtins.fromJSON (builtins.readFile "{}")).nodes.root.inputs"#,
            lock_path
        );

        let output = Command::new("nix")
            .args(NIX_FLAGS)
            .args([
                "eval",
                "--impure",
                "--expr",
                &expr,
                "--apply",
                r#"names: builtins.concatStringsSep "\n" names"#,
                "--raw",
            ])
            .output()
            .map_err(|e| Error::NixCommand(e.to_string()))?;

        if !output.status.success() {
            return Err(Error::InvalidFlakeLock);
        }

        Ok(String::from_utf8_lossy(&output.stdout)
            .lines()
            .filter(|s| !s.is_empty())
            .map(String::from)
            .collect())
    }
}

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

    #[test]
    fn test_flake_ref_simple_path() {
        let path = PathBuf::from("/home/user/.config/nixy");
        let result = flake_ref(&path, Some("default"));
        assert_eq!(result, "/home/user/.config/nixy#default");
    }

    #[test]
    fn test_flake_ref_path_with_spaces() {
        // Paths like ~/Library/Application Support/nixy should have spaces encoded
        let path = PathBuf::from("/Users/user/Library/Application Support/nixy");
        let result = flake_ref(&path, Some("default"));
        assert_eq!(
            result,
            "/Users/user/Library/Application%20Support/nixy#default"
        );
    }

    #[test]
    fn test_flake_ref_without_output() {
        let path = PathBuf::from("/home/user/.config/nixy");
        let result = flake_ref(&path, None);
        assert_eq!(result, "/home/user/.config/nixy");
    }

    #[test]
    fn test_flake_ref_with_nested_output() {
        let path = PathBuf::from("/home/user/.config/nixy");
        let result = flake_ref(&path, Some("packages.x86_64-linux"));
        assert_eq!(result, "/home/user/.config/nixy#packages.x86_64-linux");
    }

    #[test]
    fn test_flake_ref_multiple_spaces() {
        let path = PathBuf::from("/tmp/nixy test dir/config");
        let result = flake_ref(&path, Some("default"));
        assert_eq!(result, "/tmp/nixy%20test%20dir/config#default");
    }
}