Skip to main content

cuenv_tools_nix/
lib.rs

1//! Nix flake tool provider for cuenv.
2//!
3//! Provides Nix-based tool resolution using flakes. Tools are installed into
4//! per-project Nix profiles (managed by the `profile` module) rather than
5//! copying individual binaries, ensuring full Nix closures are available.
6
7pub mod commands;
8pub mod profile;
9
10use async_trait::async_trait;
11use cuenv_core::Result;
12use cuenv_core::tools::{
13    FetchedTool, ResolvedTool, ToolOptions, ToolProvider, ToolResolveRequest, ToolSource,
14};
15use std::path::PathBuf;
16use std::process::Stdio;
17use tokio::process::Command;
18use tracing::{debug, info};
19
20/// Tool provider for Nix flakes.
21///
22/// Resolves tools from Nix flakes. Actual installation into per-project
23/// Nix profiles is handled by the `profile` module during sync.
24pub struct NixToolProvider {
25    /// Named flake references (e.g., "stable" -> "github:NixOS/nixpkgs/nixos-24.11").
26    flakes: std::collections::HashMap<String, String>,
27}
28
29impl Default for NixToolProvider {
30    fn default() -> Self {
31        Self::new()
32    }
33}
34
35impl NixToolProvider {
36    /// Create a new Nix tool provider.
37    #[must_use]
38    pub fn new() -> Self {
39        Self {
40            flakes: std::collections::HashMap::new(),
41        }
42    }
43
44    /// Create a Nix tool provider with named flake references.
45    #[must_use]
46    pub fn with_flakes(flakes: std::collections::HashMap<String, String>) -> Self {
47        Self { flakes }
48    }
49
50    /// Resolve a flake name to its full reference.
51    fn resolve_flake(&self, name: &str) -> Option<&str> {
52        self.flakes.get(name).map(String::as_str)
53    }
54
55    /// Check if nix is available.
56    async fn check_nix_available() -> bool {
57        Command::new("nix")
58            .arg("--version")
59            .stdout(Stdio::null())
60            .stderr(Stdio::null())
61            .status()
62            .await
63            .map(|s| s.success())
64            .unwrap_or(false)
65    }
66}
67
68#[async_trait]
69impl ToolProvider for NixToolProvider {
70    fn name(&self) -> &'static str {
71        "nix"
72    }
73
74    fn description(&self) -> &'static str {
75        "Build tools from Nix flakes"
76    }
77
78    fn can_handle(&self, source: &ToolSource) -> bool {
79        matches!(source, ToolSource::Nix { .. })
80    }
81
82    async fn resolve(&self, request: &ToolResolveRequest<'_>) -> Result<ResolvedTool> {
83        let tool_name = request.tool_name;
84        let version = request.version;
85        let platform = request.platform;
86        let config = request.config;
87
88        let flake_name = config
89            .get("flake")
90            .and_then(|v| v.as_str())
91            .ok_or_else(|| cuenv_core::Error::tool_resolution("Missing 'flake' in config"))?;
92
93        let package = config
94            .get("package")
95            .and_then(|v| v.as_str())
96            .ok_or_else(|| cuenv_core::Error::tool_resolution("Missing 'package' in config"))?;
97
98        let output = config.get("output").and_then(|v| v.as_str());
99
100        info!(%tool_name, %flake_name, %package, %version, %platform, "Resolving Nix package");
101
102        // Check if nix is available
103        if !Self::check_nix_available().await {
104            return Err(cuenv_core::Error::tool_resolution(
105                "Nix is not installed or not in PATH".to_string(),
106            ));
107        }
108
109        // Resolve flake name to full reference
110        let flake_ref = self.resolve_flake(flake_name).ok_or_else(|| {
111            cuenv_core::Error::tool_resolution(format!(
112                "Unknown flake '{}'. Add it to runtime.flakes in your config.",
113                flake_name
114            ))
115        })?;
116
117        debug!(%flake_name, %flake_ref, %package, "Resolved flake reference");
118
119        Ok(ResolvedTool {
120            name: tool_name.to_string(),
121            version: version.to_string(),
122            platform: platform.clone(),
123            source: ToolSource::Nix {
124                flake: flake_ref.to_string(),
125                package: package.to_string(),
126                output: output.map(String::from),
127            },
128        })
129    }
130
131    async fn fetch(&self, resolved: &ResolvedTool, _options: &ToolOptions) -> Result<FetchedTool> {
132        let ToolSource::Nix { flake, package, .. } = &resolved.source else {
133            return Err(cuenv_core::Error::tool_resolution(
134                "NixToolProvider received non-Nix source".to_string(),
135            ));
136        };
137
138        // For Nix, we don't fetch/cache binaries - profiles handle this.
139        // Just validate the package exists by checking if it can be evaluated.
140        let flake_ref = format!("{flake}#{package}");
141        debug!(%flake_ref, "Validating Nix package exists");
142
143        // Use nix eval to quickly check if the package exists (no build required)
144        let output = Command::new("nix")
145            .args(["eval", "--raw", &format!("{flake_ref}.name")])
146            .output()
147            .await
148            .map_err(|e| cuenv_core::Error::tool_resolution(format!("Failed to run nix: {e}")))?;
149
150        if !output.status.success() {
151            // Package might not have a .name attribute, try just evaluating the derivation
152            let output2 = Command::new("nix")
153                .args(["eval", "--raw", &format!("{flake_ref}.type")])
154                .output()
155                .await
156                .map_err(|e| {
157                    cuenv_core::Error::tool_resolution(format!("Failed to run nix: {e}"))
158                })?;
159
160            if !output2.status.success() {
161                return Err(cuenv_core::Error::tool_resolution(format!(
162                    "Nix package {flake_ref} not found or cannot be evaluated"
163                )));
164            }
165        }
166
167        info!(tool = %resolved.name, %flake_ref, "Validated Nix package");
168
169        // Return placeholder - actual binary comes from profile
170        Ok(FetchedTool {
171            name: resolved.name.clone(),
172            binary_path: PathBuf::new(), // Profile manages the actual path
173            sha256: "nix-profile-managed".to_string(),
174        })
175    }
176
177    fn is_cached(&self, _resolved: &ResolvedTool, _options: &ToolOptions) -> bool {
178        // Nix tools are always "cached" via the Nix store.
179        // Profile installation is handled by profile::ensure_profile() during sync.
180        true
181    }
182
183    async fn check_prerequisites(&self) -> Result<()> {
184        let output = Command::new("nix")
185            .arg("--version")
186            .stdout(Stdio::null())
187            .stderr(Stdio::null())
188            .status()
189            .await;
190
191        match output {
192            Ok(status) if status.success() => Ok(()),
193            Ok(_) => Err(cuenv_core::Error::tool_resolution_with_help(
194                "Nix command failed",
195                "Install Nix: https://nixos.org/download.html",
196            )),
197            Err(_) => Err(cuenv_core::Error::tool_resolution_with_help(
198                "Nix is not installed",
199                "Install Nix: https://nixos.org/download.html",
200            )),
201        }
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208    use cuenv_core::tools::{Arch, Os, Platform};
209
210    #[test]
211    fn test_provider_name() {
212        let provider = NixToolProvider::new();
213        assert_eq!(provider.name(), "nix");
214    }
215
216    #[test]
217    fn test_provider_description() {
218        let provider = NixToolProvider::new();
219        assert_eq!(provider.description(), "Build tools from Nix flakes");
220    }
221
222    #[test]
223    fn test_provider_default() {
224        let provider = NixToolProvider::default();
225        assert_eq!(provider.name(), "nix");
226        // Default provider has no flakes registered
227        assert!(provider.resolve_flake("stable").is_none());
228    }
229
230    #[test]
231    fn test_provider_new_empty_flakes() {
232        let provider = NixToolProvider::new();
233        assert!(provider.resolve_flake("anything").is_none());
234    }
235
236    #[test]
237    fn test_resolve_flake() {
238        let mut flakes = std::collections::HashMap::new();
239        flakes.insert(
240            "stable".to_string(),
241            "github:NixOS/nixpkgs/nixos-24.11".to_string(),
242        );
243        flakes.insert(
244            "unstable".to_string(),
245            "github:NixOS/nixpkgs/nixos-unstable".to_string(),
246        );
247
248        let provider = NixToolProvider::with_flakes(flakes);
249
250        assert_eq!(
251            provider.resolve_flake("stable"),
252            Some("github:NixOS/nixpkgs/nixos-24.11")
253        );
254        assert_eq!(
255            provider.resolve_flake("unstable"),
256            Some("github:NixOS/nixpkgs/nixos-unstable")
257        );
258        assert_eq!(provider.resolve_flake("unknown"), None);
259    }
260
261    #[test]
262    fn test_resolve_flake_with_custom_flakes() {
263        let mut flakes = std::collections::HashMap::new();
264        flakes.insert(
265            "my-tools".to_string(),
266            "github:owner/my-tools-flake".to_string(),
267        );
268        flakes.insert("local".to_string(), "path:./flake".to_string());
269
270        let provider = NixToolProvider::with_flakes(flakes);
271
272        assert_eq!(
273            provider.resolve_flake("my-tools"),
274            Some("github:owner/my-tools-flake")
275        );
276        assert_eq!(provider.resolve_flake("local"), Some("path:./flake"));
277    }
278
279    #[test]
280    fn test_can_handle() {
281        let provider = NixToolProvider::new();
282
283        let nix_source = ToolSource::Nix {
284            flake: "github:NixOS/nixpkgs".into(),
285            package: "jq".into(),
286            output: None,
287        };
288        assert!(provider.can_handle(&nix_source));
289
290        let github_source = ToolSource::GitHub {
291            repo: "jqlang/jq".into(),
292            tag: "v1.7.1".into(),
293            asset: "jq-linux-amd64".into(),
294            extract: vec![],
295        };
296        assert!(!provider.can_handle(&github_source));
297    }
298
299    #[test]
300    fn test_can_handle_nix_with_output() {
301        let provider = NixToolProvider::new();
302
303        let nix_source = ToolSource::Nix {
304            flake: "github:NixOS/nixpkgs".into(),
305            package: "hello".into(),
306            output: Some("out".to_string()),
307        };
308        assert!(provider.can_handle(&nix_source));
309    }
310
311    #[test]
312    fn test_can_handle_rustup_source() {
313        let provider = NixToolProvider::new();
314
315        let rustup_source = ToolSource::Rustup {
316            toolchain: "stable".into(),
317            profile: None,
318            components: vec![],
319            targets: vec![],
320        };
321        assert!(!provider.can_handle(&rustup_source));
322    }
323
324    #[test]
325    fn test_can_handle_oci_source() {
326        let provider = NixToolProvider::new();
327
328        let oci_source = ToolSource::Oci {
329            image: "alpine:latest".into(),
330            path: "alpine".into(),
331        };
332        assert!(!provider.can_handle(&oci_source));
333    }
334
335    #[test]
336    fn test_is_cached_always_true() {
337        let provider = NixToolProvider::new();
338        let options = ToolOptions::new();
339
340        // Create a resolved tool with Nix source
341        let resolved = ResolvedTool {
342            name: "jq".to_string(),
343            version: "1.7.1".to_string(),
344            platform: Platform::new(Os::Darwin, Arch::Arm64),
345            source: ToolSource::Nix {
346                flake: "github:NixOS/nixpkgs".to_string(),
347                package: "jq".to_string(),
348                output: None,
349            },
350        };
351
352        // Nix tools are always considered cached
353        assert!(provider.is_cached(&resolved, &options));
354    }
355
356    #[test]
357    fn test_is_cached_non_nix_source() {
358        let provider = NixToolProvider::new();
359        let options = ToolOptions::new();
360
361        // Create a resolved tool with GitHub source
362        let resolved = ResolvedTool {
363            name: "mytool".to_string(),
364            version: "1.0.0".to_string(),
365            platform: Platform::new(Os::Linux, Arch::X86_64),
366            source: ToolSource::GitHub {
367                repo: "owner/repo".to_string(),
368                tag: "v1.0.0".to_string(),
369                asset: "file.zip".to_string(),
370                extract: vec![],
371            },
372        };
373
374        // Even non-Nix sources return true since we just return true unconditionally
375        assert!(provider.is_cached(&resolved, &options));
376    }
377
378    #[test]
379    fn test_with_flakes_empty() {
380        let provider = NixToolProvider::with_flakes(std::collections::HashMap::new());
381        assert!(provider.resolve_flake("any").is_none());
382    }
383
384    #[test]
385    fn test_with_flakes_single() {
386        let mut flakes = std::collections::HashMap::new();
387        flakes.insert("nixpkgs".to_string(), "github:NixOS/nixpkgs".to_string());
388
389        let provider = NixToolProvider::with_flakes(flakes);
390        assert_eq!(
391            provider.resolve_flake("nixpkgs"),
392            Some("github:NixOS/nixpkgs")
393        );
394    }
395
396    #[test]
397    fn test_with_flakes_overwrite() {
398        let mut flakes = std::collections::HashMap::new();
399        flakes.insert("stable".to_string(), "first-value".to_string());
400        flakes.insert("stable".to_string(), "second-value".to_string());
401
402        let provider = NixToolProvider::with_flakes(flakes);
403        // HashMap uses last inserted value
404        assert_eq!(provider.resolve_flake("stable"), Some("second-value"));
405    }
406}