nixy-rs 0.4.3

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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
use crate::cli::InstallArgs;
use crate::config::Config;
use crate::error::{Error, Result};
use crate::flake::template::{regenerate_flake, regenerate_flake_from_profile};
use crate::nix::Nix;
use crate::nixhub::{parse_package_spec, NixhubClient};
use crate::nixy_config::{nixy_json_exists, NixyConfig};
use crate::profile::get_flake_dir;
use crate::rollback::{self, RollbackContext};
use crate::state::{
    get_state_path, normalize_platforms, CustomPackage, PackageState, ResolvedNixpkgPackage,
};

use super::{info, success, warn};

pub fn run(config: &Config, args: InstallArgs) -> Result<()> {
    // Validate and normalize platform names early
    let platforms = if args.platform.is_empty() {
        None
    } else {
        Some(normalize_platforms(&args.platform).map_err(Error::Usage)?)
    };

    // Standard nixpkgs install (via Nixhub)
    let pkg_spec_str = args.package.ok_or_else(|| {
        Error::Usage(
            "Usage: nixy install <package>[@version] or nixy install <flake-ref>".to_string(),
        )
    })?;

    // Check if this looks like a flake reference (github:user/repo, path:./foo, etc.)
    // If so, route through install_from_flake_url instead of Nixhub
    if pkg_spec_str.contains(':') {
        let (flake_url, pkg, source_name) =
            if let Some((url, pkg_name)) = pkg_spec_str.split_once('#') {
                (url.to_string(), pkg_name.to_string(), pkg_name.to_string())
            } else {
                // No fragment: validate the flake's "default" package output,
                // but use the URL-derived name (e.g., the repository name) as
                // the human-readable package name in nixy's config to avoid
                // collisions when multiple flakes all export "default".
                let name = derive_package_name_from_url(&pkg_spec_str);
                (pkg_spec_str.clone(), name, "default".to_string())
            };
        return install_from_flake_url(config, &flake_url, &pkg, &source_name, platforms);
    }

    // Parse package spec (e.g., "nodejs@20" or "ripgrep")
    let pkg_spec = parse_package_spec(&pkg_spec_str);

    // Use NixyConfig if available (new format), otherwise fall back to legacy
    if nixy_json_exists(config) {
        return install_with_nixy_config(
            config,
            &pkg_spec.name,
            pkg_spec.version.as_deref(),
            platforms,
        );
    }

    // Legacy: Get flake directory and use PackageState
    let flake_dir = get_flake_dir(config)?;
    let state_path = get_state_path(&flake_dir);

    // Load state
    let mut state = PackageState::load(&state_path)?;

    // Check if package is already installed
    if state.has_package(&pkg_spec.name) {
        success(&format!("Package '{}' is already installed", pkg_spec.name));
        return Ok(());
    }

    // Resolve package via Nixhub
    let version_display = pkg_spec.version.as_deref().unwrap_or("latest");
    info(&format!(
        "Resolving {}@{} via Nixhub...",
        pkg_spec.name, version_display
    ));

    let client = NixhubClient::new();
    let resolved = client.resolve_for_current_system(
        &pkg_spec.name,
        pkg_spec.version.as_deref().unwrap_or("latest"),
    )?;

    info(&format!(
        "Found {} version {} (commit {})",
        resolved.name,
        resolved.version,
        &resolved.commit_hash[..8.min(resolved.commit_hash.len())]
    ));

    // Save original state for rollback
    let original_state = state.clone();

    // Add resolved package to state
    state.add_resolved_package(ResolvedNixpkgPackage {
        name: resolved.name.clone(),
        version_spec: pkg_spec.version.clone(),
        resolved_version: resolved.version.clone(),
        attribute_path: resolved.attribute_path.clone(),
        commit_hash: resolved.commit_hash.clone(),
        platforms: platforms.clone(),
    });
    state.save(&state_path)?;

    // Regenerate flake.nix (rollback state if this fails)
    if let Err(e) = regenerate_flake(&flake_dir, &state) {
        original_state.save(&state_path)?;
        warn("Failed to regenerate flake.nix. Reverted changes.");
        return Err(e);
    }

    // Set up rollback context for Ctrl+C handling
    rollback::set_context(RollbackContext::legacy(
        flake_dir.clone(),
        state_path.clone(),
        original_state.clone(),
    ));

    info(&format!(
        "Installing {}@{}...",
        resolved.name, resolved.version
    ));
    if let Err(e) = super::sync::run(config) {
        // Clear rollback context since we're handling the error here
        rollback::clear_context();
        // Sync failed, revert state and flake
        original_state.save(&state_path)?;
        let _ = regenerate_flake(&flake_dir, &original_state);
        warn("Sync failed. Reverted changes.");
        return Err(e);
    }

    // Clear rollback context on success
    rollback::clear_context();

    Ok(())
}

/// Install a package using the new nixy.json format
fn install_with_nixy_config(
    config: &Config,
    name: &str,
    version: Option<&str>,
    platforms: Option<Vec<String>>,
) -> Result<()> {
    let mut nixy_config = NixyConfig::load(config)?;
    let active_profile = nixy_config.active_profile.clone();

    // Check if package is already installed (scope the borrow)
    {
        let profile = nixy_config
            .get_active_profile()
            .ok_or_else(|| Error::ProfileNotFound(active_profile.clone()))?;
        if profile.has_package(name) {
            success(&format!("Package '{}' is already installed", name));
            return Ok(());
        }
    }

    // Resolve package via Nixhub
    let version_display = version.unwrap_or("latest");
    info(&format!(
        "Resolving {}@{} via Nixhub...",
        name, version_display
    ));

    let client = NixhubClient::new();
    let resolved = client.resolve_for_current_system(name, version.unwrap_or("latest"))?;

    info(&format!(
        "Found {} version {} (commit {})",
        resolved.name,
        resolved.version,
        &resolved.commit_hash[..8.min(resolved.commit_hash.len())]
    ));

    // Save original config for rollback BEFORE mutating
    let original_config = nixy_config.clone();

    // Add resolved package to profile
    {
        let profile = nixy_config
            .get_active_profile_mut()
            .ok_or_else(|| Error::ProfileNotFound(active_profile.clone()))?;
        profile.add_resolved_package(ResolvedNixpkgPackage {
            name: resolved.name.clone(),
            version_spec: version.map(String::from),
            resolved_version: resolved.version.clone(),
            attribute_path: resolved.attribute_path.clone(),
            commit_hash: resolved.commit_hash.clone(),
            platforms: platforms.clone(),
        });
    }
    nixy_config.save(config)?;

    // Regenerate flake.nix
    let flake_dir = get_flake_dir(config)?;
    let global_packages_dir = if config.global_packages_dir.exists() {
        Some(config.global_packages_dir.as_path())
    } else {
        None
    };
    let profile_for_flake = nixy_config.get_active_profile().unwrap();
    if let Err(e) =
        regenerate_flake_from_profile(&flake_dir, profile_for_flake, global_packages_dir)
    {
        original_config.save(config)?;
        warn("Failed to regenerate flake.nix. Reverted changes.");
        return Err(e);
    }

    // Set up rollback context for Ctrl+C handling
    rollback::set_context(RollbackContext::nixy_config(
        flake_dir.clone(),
        config.nixy_json.clone(),
        original_config.clone(),
        global_packages_dir,
    ));

    info(&format!(
        "Installing {}@{}...",
        resolved.name, resolved.version
    ));
    if let Err(e) = super::sync::run(config) {
        // Clear rollback context since we're handling the error here
        rollback::clear_context();
        // Sync failed, revert config
        original_config.save(config)?;
        let original_profile = original_config.get_active_profile().unwrap();
        let _ = regenerate_flake_from_profile(&flake_dir, original_profile, global_packages_dir);
        warn("Sync failed. Reverted changes.");
        return Err(e);
    }

    // Clear rollback context on success
    rollback::clear_context();

    Ok(())
}

/// Try to validate a flake package, with smart fallback.
///
/// First tries `source_name` (usually "default" when no fragment is given).
/// If that fails and `source_name == "default"` and `pkg != "default"`,
/// tries `pkg` as a fallback (e.g., the repo name like "realm").
///
/// Returns `(effective_source_name, pkg_output)` on success.
fn validate_and_resolve_flake_package(
    flake_url: &str,
    pkg: &str,
    source_name: &str,
    input_name: &str,
) -> Result<(String, String)> {
    // Try the requested source_name first
    if let Some(pkg_output) = Nix::validate_flake_package(flake_url, source_name)? {
        return Ok((source_name.to_string(), pkg_output));
    }

    // Fallback: if source_name is "default" and pkg is different, try pkg as the attribute
    let tried_fallback = source_name == "default" && pkg != "default";
    if tried_fallback {
        info(&format!("Package 'default' not found, trying '{}'...", pkg));
        if let Some(pkg_output) = Nix::validate_flake_package(flake_url, pkg)? {
            return Ok((pkg.to_string(), pkg_output));
        }
    }

    // Both failed — build a helpful error message
    let display_name = if tried_fallback {
        format!("'{}' or '{}'", source_name, pkg)
    } else {
        format!("'{}'", source_name)
    };

    let available = Nix::list_flake_packages(flake_url, None)
        .unwrap_or_default()
        .into_iter()
        .take(10)
        .collect::<Vec<_>>();

    if available.is_empty() {
        Err(Error::Usage(format!(
            "Package {} not found in '{}'",
            display_name, input_name
        )))
    } else {
        let available_str = available.join(", ");
        Err(Error::Usage(format!(
            "Package {} not found in '{}'. Available packages: {}\n\
             Tip: use {}#<package> to specify the package explicitly",
            display_name, input_name, available_str, flake_url
        )))
    }
}

/// Install from a flake URL (e.g., github:user/repo)
///
/// `pkg` is the human-readable package name used in nixy's config.
/// `source_name` is the flake output attribute to validate and install
/// (e.g., "default" when no fragment is given, or the explicit fragment).
fn install_from_flake_url(
    config: &Config,
    flake_url: &str,
    pkg: &str,
    source_name: &str,
    platforms: Option<Vec<String>>,
) -> Result<()> {
    // Use NixyConfig if available (new format)
    if nixy_json_exists(config) {
        return install_from_flake_url_with_nixy_config(
            config,
            flake_url,
            pkg,
            source_name,
            platforms,
        );
    }

    // Legacy format
    let flake_dir = get_flake_dir(config)?;
    let state_path = get_state_path(&flake_dir);

    // Load state
    let mut state = PackageState::load(&state_path)?;

    // Check if package is already installed
    if state.has_package(pkg) {
        success(&format!("Package '{}' is already installed", pkg));
        return Ok(());
    }

    info(&format!("Using flake URL: {}", flake_url));
    let input_name = derive_input_name_from_url(flake_url);

    // Validate the package exists (with smart fallback for no-fragment URLs)
    info(&format!(
        "Validating package '{}' in {}...",
        source_name, input_name
    ));
    let (effective_source_name, pkg_output) =
        validate_and_resolve_flake_package(flake_url, pkg, source_name, &input_name)?;

    // Save original state for rollback
    let original_state = state.clone();

    // Add custom package to state
    let stored_source_name = if effective_source_name != pkg {
        Some(effective_source_name.to_string())
    } else {
        None
    };
    state.add_custom_package(CustomPackage {
        name: pkg.to_string(),
        input_name: input_name.clone(),
        input_url: flake_url.to_string(),
        package_output: pkg_output,
        source_name: stored_source_name,
        platforms,
    });
    state.save(&state_path)?;

    // Regenerate flake.nix (rollback state if this fails)
    if let Err(e) = regenerate_flake(&flake_dir, &state) {
        original_state.save(&state_path)?;
        warn("Failed to regenerate flake.nix. Reverted changes.");
        return Err(e);
    }

    // Set up rollback context for Ctrl+C handling
    rollback::set_context(RollbackContext::legacy(
        flake_dir.clone(),
        state_path.clone(),
        original_state.clone(),
    ));

    info(&format!("Installing {} from {}...", pkg, input_name));
    if let Err(e) = super::sync::run(config) {
        // Clear rollback context since we're handling the error here
        rollback::clear_context();
        // Sync failed, revert state and flake
        original_state.save(&state_path)?;
        let _ = regenerate_flake(&flake_dir, &original_state);
        warn("Sync failed. Reverted changes.");
        return Err(e);
    }

    // Clear rollback context on success
    rollback::clear_context();

    Ok(())
}

/// Install from a flake URL using the new nixy.json format
fn install_from_flake_url_with_nixy_config(
    config: &Config,
    flake_url: &str,
    pkg: &str,
    source_name: &str,
    platforms: Option<Vec<String>>,
) -> Result<()> {
    let mut nixy_config = NixyConfig::load(config)?;
    let active_profile = nixy_config.active_profile.clone();

    // Check if package is already installed (scope the borrow)
    {
        let profile = nixy_config
            .get_active_profile()
            .ok_or_else(|| Error::ProfileNotFound(active_profile.clone()))?;
        if profile.has_package(pkg) {
            success(&format!("Package '{}' is already installed", pkg));
            return Ok(());
        }
    }

    info(&format!("Using flake URL: {}", flake_url));
    let input_name = derive_input_name_from_url(flake_url);

    // Validate the package exists using the source attribute name
    info(&format!(
        "Validating package '{}' in {}...",
        source_name, input_name
    ));
    let (effective_source_name, pkg_output) =
        validate_and_resolve_flake_package(flake_url, pkg, source_name, &input_name)?;

    // Save original config for rollback BEFORE mutating
    let original_config = nixy_config.clone();

    // Add custom package to profile
    let stored_source_name = if effective_source_name != pkg {
        Some(effective_source_name.to_string())
    } else {
        None
    };
    {
        let profile = nixy_config
            .get_active_profile_mut()
            .ok_or_else(|| Error::ProfileNotFound(active_profile.clone()))?;
        profile.add_custom_package(CustomPackage {
            name: pkg.to_string(),
            input_name: input_name.clone(),
            input_url: flake_url.to_string(),
            package_output: pkg_output,
            source_name: stored_source_name,
            platforms,
        });
    }
    nixy_config.save(config)?;

    // Regenerate flake.nix
    let flake_dir = get_flake_dir(config)?;
    let global_packages_dir = if config.global_packages_dir.exists() {
        Some(config.global_packages_dir.as_path())
    } else {
        None
    };
    let profile_for_flake = nixy_config.get_active_profile().unwrap();
    if let Err(e) =
        regenerate_flake_from_profile(&flake_dir, profile_for_flake, global_packages_dir)
    {
        original_config.save(config)?;
        warn("Failed to regenerate flake.nix. Reverted changes.");
        return Err(e);
    }

    // Set up rollback context for Ctrl+C handling
    rollback::set_context(RollbackContext::nixy_config(
        flake_dir.clone(),
        config.nixy_json.clone(),
        original_config.clone(),
        global_packages_dir,
    ));

    info(&format!("Installing {} from {}...", pkg, input_name));
    if let Err(e) = super::sync::run(config) {
        // Clear rollback context since we're handling the error here
        rollback::clear_context();
        original_config.save(config)?;
        let original_profile = original_config.get_active_profile().unwrap();
        let _ = regenerate_flake_from_profile(&flake_dir, original_profile, global_packages_dir);
        warn("Sync failed. Reverted changes.");
        return Err(e);
    }

    // Clear rollback context on success
    rollback::clear_context();

    Ok(())
}

/// Sanitize a string for use as an input name
fn sanitize_input_name(s: &str) -> String {
    let sanitized: String = s
        .chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '-' {
                c
            } else {
                '-'
            }
        })
        .collect();
    sanitized.trim_matches('-').to_string()
}

/// Derive a package name from a flake URL (uses the last path component, e.g., repo name)
/// For "github:user/repo" → "repo", for "path:./foo/bar" → "bar"
fn derive_package_name_from_url(url: &str) -> String {
    // Strip the scheme (everything before and including ':')
    let path = url.split_once(':').map(|(_, p)| p).unwrap_or(url);
    // Take the last path component
    let name = path
        .trim_end_matches('/')
        .rsplit('/')
        .next()
        .unwrap_or("default")
        .trim_end_matches(".git");
    if name.is_empty() {
        "default".to_string()
    } else {
        sanitize_input_name(name)
    }
}

/// Derive an input name from a flake URL
fn derive_input_name_from_url(url: &str) -> String {
    // Try to extract owner-repo from URL
    let parts: Vec<&str> = url.split('/').collect();
    if parts.len() >= 2 {
        let owner = parts[parts.len() - 2];
        let repo = parts[parts.len() - 1].trim_end_matches(".git");
        sanitize_input_name(&format!("{}-{}", owner, repo))
    } else {
        "custom-flake".to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_sanitize_input_name() {
        assert_eq!(sanitize_input_name("nixpkgs"), "nixpkgs");
        assert_eq!(sanitize_input_name("foo-bar"), "foo-bar");
        assert_eq!(sanitize_input_name("foo_bar"), "foo-bar");
        assert_eq!(sanitize_input_name("foo/bar"), "foo-bar");
        assert_eq!(sanitize_input_name("--foo--"), "foo");
    }

    #[test]
    fn test_derive_input_name_from_url() {
        assert_eq!(
            derive_input_name_from_url("github:NixOS/nixpkgs"),
            "github-NixOS-nixpkgs"
        );
        assert_eq!(
            derive_input_name_from_url("github:user/repo.git"),
            "github-user-repo"
        );
    }

    #[test]
    fn test_flake_reference_detection() {
        // Strings containing ':' should be detected as flake references
        assert!("github:user/repo".contains(':'));
        assert!("gitlab:user/repo".contains(':'));
        assert!("path:/some/path".contains(':'));
        assert!("git+https://example.com/repo".contains(':'));

        // Plain package names should NOT be detected
        assert!(!"hello".contains(':'));
        assert!(!"nodejs".contains(':'));
        assert!(!"ripgrep".contains(':'));
        // Version specs with @ should NOT be detected
        assert!(!"nodejs@20".contains(':'));
    }

    #[test]
    fn test_flake_reference_split() {
        // With fragment: should extract package name and use it as source_name
        let spec = "github:user/repo#some-pkg";
        let (url, pkg, source_name) = if let Some((u, p)) = spec.split_once('#') {
            (u.to_string(), p.to_string(), p.to_string())
        } else {
            let name = derive_package_name_from_url(spec);
            (spec.to_string(), name, "default".to_string())
        };
        assert_eq!(url, "github:user/repo");
        assert_eq!(pkg, "some-pkg");
        assert_eq!(source_name, "some-pkg");

        // Without fragment: should derive package name from URL,
        // but use "default" as the source attribute for validation
        let spec = "github:user/repo";
        let (url, pkg, source_name) = if let Some((u, p)) = spec.split_once('#') {
            (u.to_string(), p.to_string(), p.to_string())
        } else {
            let name = derive_package_name_from_url(spec);
            (spec.to_string(), name, "default".to_string())
        };
        assert_eq!(url, "github:user/repo");
        assert_eq!(pkg, "repo");
        assert_eq!(source_name, "default");
    }

    #[test]
    fn test_derive_package_name_from_url() {
        assert_eq!(derive_package_name_from_url("github:user/repo"), "repo");
        assert_eq!(derive_package_name_from_url("github:user/repo.git"), "repo");
        assert_eq!(
            derive_package_name_from_url("gitlab:org/project"),
            "project"
        );
        assert_eq!(derive_package_name_from_url("path:./foo/bar"), "bar");
        assert_eq!(derive_package_name_from_url("path:./single"), "single");
    }

    #[test]
    fn test_regenerate_flake() {
        let temp = TempDir::new().unwrap();
        let flake_dir = temp.path();

        let mut state = PackageState::default();
        state.add_package("hello");

        regenerate_flake(flake_dir, &state).unwrap();

        let flake_path = flake_dir.join("flake.nix");
        assert!(flake_path.exists());

        let content = fs::read_to_string(&flake_path).unwrap();
        assert!(content.contains("hello = pkgs.hello;"));
    }
}