cuenv 0.40.6

Event-driven CLI with inline TUI for cuenv
Documentation
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
//! Tools command implementations for multi-source tool management.
//!
//! This module provides commands for downloading, activating, and listing tools
//! from multiple sources (GitHub releases, Nix packages, OCI images).

use crate::cli::CliError;
use cuenv_core::lockfile::{LOCKFILE_NAME, Lockfile};
use cuenv_core::tools::{
    Platform, ResolvedToolActivationStep, ToolActivationOperation, ToolActivationResolveOptions,
    ToolExtract, ToolOptions, ToolRegistry, ToolSource, apply_resolved_tool_activation,
    resolve_tool_activation, validate_tool_activation,
};
use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};

/// Create a tool registry with available providers.
fn create_registry() -> ToolRegistry {
    let mut registry = ToolRegistry::new();

    // Register Nix provider
    registry.register(cuenv_tools_nix::NixToolProvider::new());

    // Register GitHub provider
    registry.register(cuenv_tools_github::GitHubToolProvider::new());

    // Register Rustup provider
    registry.register(cuenv_tools_rustup::RustupToolProvider::new());

    // Register URL provider
    registry.register(cuenv_tools_url::UrlToolProvider::new());

    registry
}

/// Execute the `tools download` command.
///
/// Downloads tools for the current platform from the lockfile.
///
/// # Errors
///
/// Returns an error if the lockfile is not found or if any tool download fails.
#[allow(clippy::print_stdout, clippy::print_stderr)] // Download progress messages, no secrets
pub async fn execute_tools_download() -> Result<(), CliError> {
    // Find the lockfile
    let lockfile_path = find_lockfile(None).ok_or_else(|| {
        CliError::config_with_help(
            "No cuenv.lock found",
            "Run 'cuenv sync lock' to create the lockfile",
        )
    })?;

    // Load the lockfile
    let lockfile = Lockfile::load(&lockfile_path)
        .map_err(|e| CliError::other(format!("Failed to load lockfile: {e}")))?
        .ok_or_else(|| {
            CliError::config_with_help(
                "Lockfile is empty",
                "Run 'cuenv sync lock' to populate the lockfile",
            )
        })?;

    // Get current platform
    let platform = Platform::current();
    let platform_str = platform.to_string();

    // Create tool options
    let options = ToolOptions::default();

    // Create the registry
    let registry = create_registry();

    // Check prerequisites for all providers we'll use
    let mut providers_used = HashSet::new();
    for tool in lockfile.tools.values() {
        if let Some(locked) = tool.platforms.get(&platform_str) {
            providers_used.insert(locked.provider.clone());
        }
    }

    for provider_name in &providers_used {
        if let Some(provider) = registry.get(provider_name) {
            provider.check_prerequisites().await.map_err(|e| {
                CliError::config_with_help(
                    format!("Provider '{}' not available: {}", provider_name, e),
                    "Check that the required tools are installed",
                )
            })?;
        }
    }

    // Download tools
    let mut downloaded = 0;
    let mut skipped = 0;
    let mut errors: Vec<String> = Vec::new();

    for (name, tool) in &lockfile.tools {
        let Some(locked) = tool.platforms.get(&platform_str) else {
            // Tool not available for this platform
            continue;
        };

        let Some(source) = lockfile_entry_to_source(name, &tool.version, locked) else {
            eprintln!(
                "Warning: Unknown provider '{}' for tool '{}'",
                locked.provider, name
            );
            continue;
        };

        // Get the provider
        let Some(provider) = registry.find_for_source(&source) else {
            eprintln!(
                "Warning: No provider found for source type of tool '{}'",
                name
            );
            continue;
        };

        // Create resolved tool
        let resolved = cuenv_core::tools::ResolvedTool {
            name: name.clone(),
            version: tool.version.clone(),
            platform: platform.clone(),
            source,
        };

        // Check if already cached
        if provider.is_cached(&resolved, &options) {
            skipped += 1;
            continue;
        }

        // Fetch the tool
        println!("Downloading {} v{}...", name, tool.version);
        match provider.fetch(&resolved, &options).await {
            Ok(fetched) => {
                println!(
                    "  -> {} ({})",
                    fetched.binary_path.display(),
                    fetched.sha256
                );
                downloaded += 1;
            }
            Err(e) => {
                eprintln!("  Error downloading '{}': {}", name, e);
                errors.push(format!("{}: {}", name, e));
            }
        }
    }

    println!();
    println!(
        "Downloaded {} tools, {} already cached",
        downloaded, skipped
    );

    if !errors.is_empty() {
        return Err(CliError::other(format!(
            "Failed to download tools: {}",
            errors.join(", ")
        )));
    }

    Ok(())
}

/// Ensure all tools from the lockfile are downloaded for the current platform.
///
/// This is called automatically before tool activation in exec/task commands.
/// If no lockfile exists or tools are already cached, this is a no-op.
///
/// If `project_path` is provided, the lockfile search starts from that directory.
/// Otherwise, it starts from the current working directory.
///
/// # Errors
///
/// Returns an error if tools cannot be downloaded due to provider issues.
pub async fn ensure_tools_downloaded(project_path: Option<&Path>) -> Result<(), CliError> {
    // Find the lockfile - not finding one is not an error
    let Some(lockfile_path) = find_runtime_lockfile(project_path) else {
        tracing::debug!("No lockfile found - skipping tool download");
        return Ok(());
    };

    // Load the lockfile
    let Some(lockfile) = Lockfile::load(&lockfile_path)
        .map_err(|e| CliError::other(format!("Failed to load lockfile: {e}")))?
    else {
        tracing::debug!("Empty lockfile - skipping tool download");
        return Ok(());
    };

    if lockfile.tools.is_empty() {
        tracing::debug!("No tools in lockfile - skipping download");
        return Ok(());
    }

    // Validate lockfile activation hints before any download activity.
    let activation_options = ToolActivationResolveOptions::new(&lockfile, &lockfile_path);
    validate_tool_activation(&activation_options).map_err(|e| {
        CliError::config_with_help(
            format!("Invalid tool activation configuration: {e}"),
            "Run 'cuenv sync lock' to refresh cuenv.lock",
        )
    })?;

    // Get current platform
    let platform = Platform::current();
    let platform_str = platform.to_string();

    // Create tool options
    let options = ToolOptions::default();

    // Create the registry
    let registry = create_registry();

    // Check prerequisites for all providers we'll use
    let mut providers_used = HashSet::new();
    for tool in lockfile.tools.values() {
        if let Some(locked) = tool.platforms.get(&platform_str) {
            providers_used.insert(locked.provider.clone());
        }
    }

    for provider_name in &providers_used {
        if let Some(provider) = registry.get(provider_name)
            && let Err(e) = provider.check_prerequisites().await
        {
            tracing::warn!(
                "Provider '{}' prerequisites check failed: {} - skipping tools from this provider",
                provider_name,
                e
            );
        }
    }

    // Download tools that aren't cached
    let mut downloaded = 0;
    let mut errors: Vec<String> = Vec::new();

    for (name, tool) in &lockfile.tools {
        let Some(locked) = tool.platforms.get(&platform_str) else {
            // Tool not available for this platform
            continue;
        };

        // Convert lockfile data to ToolSource
        let Some(source) = lockfile_entry_to_source(name, &tool.version, locked) else {
            tracing::debug!(
                "Unknown provider '{}' for tool '{}' - skipping",
                locked.provider,
                name
            );
            continue;
        };

        // Get the provider
        let Some(provider) = registry.find_for_source(&source) else {
            tracing::debug!("No provider found for tool '{}' - skipping", name);
            continue;
        };

        // Create resolved tool
        let resolved = cuenv_core::tools::ResolvedTool {
            name: name.clone(),
            version: tool.version.clone(),
            platform: platform.clone(),
            source,
        };

        // Check if already cached
        if provider.is_cached(&resolved, &options) {
            continue;
        }

        // Fetch the tool
        tracing::info!("Downloading {} v{}...", name, tool.version);
        match provider.fetch(&resolved, &options).await {
            Ok(fetched) => {
                tracing::info!(
                    "Downloaded {} -> {} ({})",
                    name,
                    fetched.binary_path.display(),
                    fetched.sha256
                );
                downloaded += 1;
            }
            Err(e) => {
                tracing::warn!("Failed to download '{}': {}", name, e);
                errors.push(format!("{}: {}", name, e));
            }
        }
    }

    if downloaded > 0 {
        tracing::info!("Downloaded {} tools", downloaded);
    }

    if !errors.is_empty() {
        return Err(CliError::other(format!(
            "Failed to download tools: {}",
            errors.join(", ")
        )));
    }

    Ok(())
}

/// Convert a lockfile entry to a ToolSource.
fn lockfile_entry_to_source(
    _name: &str,
    _version: &str,
    locked: &cuenv_core::lockfile::LockedToolPlatform,
) -> Option<ToolSource> {
    match locked.provider.as_str() {
        "oci" => {
            let image = locked
                .source
                .get("image")
                .and_then(|v| v.as_str())
                .unwrap_or_default();
            let path = locked
                .source
                .get("path")
                .and_then(|v| v.as_str())
                .unwrap_or_default();
            Some(ToolSource::Oci {
                image: image.to_string(),
                path: path.to_string(),
            })
        }
        "github" => {
            let repo = locked
                .source
                .get("repo")
                .and_then(|v| v.as_str())
                .unwrap_or_default();
            let tag = locked
                .source
                .get("tag")
                .and_then(|v| v.as_str())
                .unwrap_or_default();
            let asset = locked
                .source
                .get("asset")
                .and_then(|v| v.as_str())
                .unwrap_or_default();
            let extract = parse_github_extract_list(&locked.source);
            Some(ToolSource::GitHub {
                repo: repo.to_string(),
                tag: tag.to_string(),
                asset: asset.to_string(),
                extract,
            })
        }
        "nix" => {
            let flake = locked
                .source
                .get("flake")
                .and_then(|v| v.as_str())
                .unwrap_or_default();
            let package = locked
                .source
                .get("package")
                .and_then(|v| v.as_str())
                .unwrap_or_default();
            let output = locked
                .source
                .get("output")
                .and_then(|v| v.as_str())
                .map(String::from);
            Some(ToolSource::Nix {
                flake: flake.to_string(),
                package: package.to_string(),
                output,
            })
        }
        "rustup" => {
            let toolchain = locked
                .source
                .get("toolchain")
                .and_then(|v| v.as_str())
                .unwrap_or("stable");
            let profile = locked
                .source
                .get("profile")
                .and_then(|v| v.as_str())
                .map(String::from);
            let components = locked
                .source
                .get("components")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(String::from))
                        .collect()
                })
                .unwrap_or_default();
            let targets = locked
                .source
                .get("targets")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(String::from))
                        .collect()
                })
                .unwrap_or_default();
            Some(ToolSource::Rustup {
                toolchain: toolchain.to_string(),
                profile,
                components,
                targets,
            })
        }
        "url" => {
            let url = locked
                .source
                .get("url")
                .and_then(|v| v.as_str())
                .unwrap_or_default();
            let extract = parse_github_extract_list(&locked.source);
            Some(ToolSource::Url {
                url: url.to_string(),
                extract,
            })
        }
        _ => None,
    }
}

fn parse_github_extract_list(source: &serde_json::Value) -> Vec<ToolExtract> {
    let mut extract = source
        .get("extract")
        .cloned()
        .and_then(|value| serde_json::from_value::<Vec<ToolExtract>>(value).ok())
        .unwrap_or_default();

    if extract.is_empty()
        && let Some(path) = source.get("path").and_then(|v| v.as_str())
    {
        if path_looks_like_library(path) {
            extract.push(ToolExtract::Lib {
                path: path.to_string(),
                env: None,
            });
        } else {
            extract.push(ToolExtract::Bin {
                path: path.to_string(),
                as_name: None,
            });
        }
    }

    extract
}

fn path_looks_like_library(path: &str) -> bool {
    let ext_is = |target: &str| {
        std::path::Path::new(path)
            .extension()
            .and_then(|ext| ext.to_str())
            .is_some_and(|ext| ext.eq_ignore_ascii_case(target))
    };
    ext_is("dylib") || ext_is("so") || path.to_ascii_lowercase().contains(".so.") || ext_is("dll")
}

/// Resolve inferred activation steps from the lockfile for the current platform.
///
/// Returns `Ok(None)` when no lockfile exists or no activation steps resolve.
///
/// # Errors
///
/// Returns an error when lockfile parsing fails or activation hints are invalid.
pub fn resolve_tool_activation_steps(
    project_path: Option<&Path>,
) -> Result<Option<Vec<ResolvedToolActivationStep>>, CliError> {
    let Some(lockfile_path) = find_runtime_lockfile(project_path) else {
        return Ok(None);
    };

    let Some(lockfile) = Lockfile::load(&lockfile_path)
        .map_err(|e| CliError::other(format!("Failed to load lockfile: {e}")))?
    else {
        return Ok(None);
    };

    let options = ToolActivationResolveOptions::new(&lockfile, &lockfile_path);
    let activation = resolve_tool_activation(&options).map_err(|e| {
        CliError::config_with_help(
            format!("Invalid tool activation configuration: {e}"),
            "Run 'cuenv sync lock' to refresh cuenv.lock",
        )
    })?;

    if activation.is_empty() {
        return Ok(None);
    }

    Ok(Some(activation))
}

/// Execute the `tools activate` command.
///
/// Outputs shell export statements inferred from lockfile tool metadata.
///
/// # Errors
///
/// Returns an error if the lockfile is not found.
#[allow(clippy::print_stdout)] // Shell export statements, no secrets
pub fn execute_tools_activate() -> Result<(), CliError> {
    let activation_steps = resolve_tool_activation_steps(None)?.ok_or_else(|| {
        CliError::config_with_help(
            "No cuenv.lock found or no tools configured",
            "Run 'cuenv sync lock' to create the lockfile",
        )
    })?;

    let mut env: BTreeMap<String, String> = std::env::vars().collect();
    let mut touched_vars: Vec<String> = Vec::new();
    let mut touched_set: HashSet<String> = HashSet::new();

    for step in activation_steps {
        let current = env.get(&step.var).map(String::as_str);
        if let Some(new_value) = apply_resolved_tool_activation(current, &step) {
            if touched_set.insert(step.var.clone()) {
                touched_vars.push(step.var.clone());
            }
            env.insert(step.var, new_value);
        }
    }

    for var in touched_vars {
        if let Some(value) = env.get(&var) {
            println!("export {var}={}", shell_quote(value));
        }
    }

    Ok(())
}

fn shell_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\"'\"'"))
}

/// Execute the `tools list` command.
///
/// Lists all tools configured in the lockfile.
///
/// # Errors
///
/// Returns an error if the lockfile is not found.
#[allow(clippy::print_stdout)] // Tool listing info, no secrets
pub fn execute_tools_list() -> Result<(), CliError> {
    // Find the lockfile
    let lockfile_path = find_lockfile(None).ok_or_else(|| {
        CliError::config_with_help(
            "No cuenv.lock found",
            "Run 'cuenv sync lock' to create the lockfile",
        )
    })?;

    // Load the lockfile
    let lockfile = Lockfile::load(&lockfile_path)
        .map_err(|e| CliError::other(format!("Failed to load lockfile: {e}")))?
        .ok_or_else(|| {
            CliError::config_with_help(
                "Lockfile is empty",
                "Run 'cuenv sync lock' to populate the lockfile",
            )
        })?;

    // Get current platform for highlighting
    let current_platform = cuenv_core::lockfile::current_platform();

    if lockfile.tools.is_empty() {
        println!("No tools configured.");
        println!();
        println!("To add tools, create a runtime in your env.cue:");
        println!();
        println!("  runtime: #ToolsRuntime & {{");
        println!("      platforms: [\"darwin-arm64\", \"linux-x86_64\"]");
        println!("      tools: {{");
        println!("          jq: \"1.7.1\"");
        println!("          yq: \"4.44.6\"");
        println!("          foundationdb: {{");
        println!("              version: \"7.3.63\"");
        println!(
            "              source: #GitHub & {{repo: \"apple/foundationdb\", asset: \"FoundationDB-{{version}}_arm64.pkg\", extract: [{{kind: \"lib\", path: \"libfdb_c.dylib\", env: \"FDB_CLIENT_LIB\"}}]}}"
        );
        println!("          }}");
        println!("      }}");
        println!("  }}");
        return Ok(());
    }

    println!("Configured tools:");
    println!();

    // Sort tools by name
    let mut tools: Vec<_> = lockfile.tools.iter().collect();
    tools.sort_by_key(|(name, _)| *name);

    for (name, tool) in tools {
        println!("  {} v{}", name, tool.version);

        // Show platforms
        for (platform, locked) in &tool.platforms {
            let marker = if platform == &current_platform {
                " (current)"
            } else {
                ""
            };
            println!(
                "    - {}: {} ({}){}",
                platform,
                locked.provider,
                &locked.digest[..20],
                marker
            );
        }
    }

    println!();
    for line in activation_section_lines(&lockfile, &lockfile_path) {
        println!("{line}");
    }
    println!();
    println!(
        "Total: {} tools, {} platforms",
        lockfile.tools.len(),
        lockfile
            .tools
            .values()
            .map(|t| t.platforms.len())
            .sum::<usize>()
    );

    Ok(())
}

fn activation_section_lines(lockfile: &Lockfile, lockfile_path: &Path) -> Vec<String> {
    activation_section_lines_with_cache_dir(lockfile, lockfile_path, None)
}

fn activation_section_lines_with_cache_dir(
    lockfile: &Lockfile,
    lockfile_path: &Path,
    cache_dir: Option<PathBuf>,
) -> Vec<String> {
    let platform = Platform::current();
    let mode = if lockfile.tools_activation.is_empty() {
        "inferred"
    } else {
        "explicit"
    };
    let mut lines = vec![format!("Activation ({platform}, {mode}):")];
    let mut options =
        ToolActivationResolveOptions::new(lockfile, lockfile_path).with_platform(platform);
    if let Some(cache_dir) = cache_dir {
        options = options.with_cache_dir(cache_dir);
    }

    match resolve_tool_activation(&options) {
        Ok(steps) => {
            let rendered = render_activation_steps(&steps);
            if rendered.is_empty() {
                lines.push(
                    "  - No activation paths are currently materialized for this platform."
                        .to_string(),
                );
            } else {
                lines.extend(rendered);
            }
        }
        Err(err) => lines.push(format!("  - error: {err}")),
    }

    lines
}

fn render_activation_steps(steps: &[ResolvedToolActivationStep]) -> Vec<String> {
    steps
        .iter()
        .filter(|step| !step.value.is_empty() || matches!(step.op, ToolActivationOperation::Set))
        .map(|step| {
            let value = if step.value.is_empty() {
                "<empty>"
            } else {
                step.value.as_str()
            };
            format!(
                "  - {} ({}): {}",
                step.var,
                activation_operation_label(&step.op),
                value
            )
        })
        .collect()
}

fn activation_operation_label(operation: &ToolActivationOperation) -> &'static str {
    match operation {
        ToolActivationOperation::Set => "set",
        ToolActivationOperation::Prepend => "prepend",
        ToolActivationOperation::Append => "append",
    }
}

/// Find the lockfile by walking up from the given directory (or current directory).
fn find_lockfile(start_path: Option<&Path>) -> Option<PathBuf> {
    let mut current = start_path
        .map(|p| p.to_path_buf())
        .or_else(|| std::env::current_dir().ok())?;
    loop {
        let lockfile_path = current.join(LOCKFILE_NAME);
        if lockfile_path.exists() {
            return Some(lockfile_path);
        }

        // Also check in cue.mod directory
        let cue_mod_lockfile = current.join("cue.mod").join(LOCKFILE_NAME);
        if cue_mod_lockfile.exists() {
            return Some(cue_mod_lockfile);
        }

        if !current.pop() {
            return None;
        }
    }
}

/// Find a lockfile scoped to the current project only.
///
/// Runtime commands like `task` and `exec` should not inherit an ancestor
/// workspace lockfile when the target project does not define one.
fn find_lockfile_in_project(project_path: &Path) -> Option<PathBuf> {
    let project_lockfile = project_path.join(LOCKFILE_NAME);
    if project_lockfile.exists() {
        return Some(project_lockfile);
    }

    let cue_mod_lockfile = project_path.join("cue.mod").join(LOCKFILE_NAME);
    if cue_mod_lockfile.exists() {
        return Some(cue_mod_lockfile);
    }

    None
}

fn find_runtime_lockfile(project_path: Option<&Path>) -> Option<PathBuf> {
    project_path.map_or_else(|| find_lockfile(None), find_lockfile_in_project)
}

#[cfg(test)]
mod tests {
    use super::*;
    use cuenv_core::lockfile::{LockedTool, LockedToolPlatform};
    use cuenv_core::tools::{ToolActivationSource, ToolActivationStep};
    use std::collections::BTreeMap;
    use std::fs;

    fn current_platform_key() -> String {
        Platform::current().to_string()
    }

    fn github_tool(version: &str) -> LockedTool {
        LockedTool {
            version: version.to_string(),
            platforms: BTreeMap::from([(
                current_platform_key(),
                LockedToolPlatform {
                    provider: "github".to_string(),
                    digest: "sha256:abc".to_string(),
                    source: serde_json::json!({
                        "type": "github",
                        "repo": "jqlang/jq",
                        "tag": "jq-1.7.1",
                        "asset": "jq",
                    }),
                    size: None,
                    dependencies: vec![],
                },
            )]),
        }
    }

    #[test]
    fn test_find_lockfile_not_found() {
        // Save and restore CWD to avoid breaking parallel tests
        let original_cwd = std::env::current_dir().unwrap();

        // Create temp dir without lockfile
        let temp = tempfile::tempdir().unwrap();
        std::env::set_current_dir(temp.path()).unwrap();

        // Should return None when searching from temp dir
        let result = find_lockfile(None);

        // Restore CWD before assertions (in case of panic)
        std::env::set_current_dir(&original_cwd).unwrap();

        assert!(result.is_none());
    }

    #[test]
    fn test_find_lockfile_in_project_checks_project_root() {
        let temp = tempfile::tempdir().unwrap();
        let lockfile_path = temp.path().join(LOCKFILE_NAME);
        fs::write(&lockfile_path, "").unwrap();

        let result = find_lockfile_in_project(temp.path());

        assert_eq!(result, Some(lockfile_path));
    }

    #[test]
    fn test_find_lockfile_in_project_does_not_walk_to_parent() {
        let temp = tempfile::tempdir().unwrap();
        fs::write(temp.path().join(LOCKFILE_NAME), "").unwrap();

        let project_dir = temp.path().join("nested-project");
        fs::create_dir_all(&project_dir).unwrap();

        let result = find_lockfile_in_project(&project_dir);

        assert!(result.is_none());
    }

    #[test]
    fn test_activation_section_lines_show_inferred_activation() {
        let temp = tempfile::tempdir().unwrap();
        let lockfile_path = temp.path().join("cuenv.lock");
        let cache_dir = temp.path().join("cache");
        let bin_dir = cache_dir
            .join("github")
            .join("jq")
            .join("1.7.1")
            .join("bin");
        fs::create_dir_all(&bin_dir).unwrap();

        let mut lockfile = Lockfile::new();
        lockfile
            .tools
            .insert("jq".to_string(), github_tool("1.7.1"));

        let lines =
            activation_section_lines_with_cache_dir(&lockfile, &lockfile_path, Some(cache_dir));

        assert!(
            lines
                .first()
                .is_some_and(|line| line.contains("Activation (") && line.contains("inferred"))
        );
        assert!(
            lines
                .iter()
                .any(|line| line == &format!("  - PATH (prepend): {}", bin_dir.display()))
        );
    }

    #[test]
    fn test_activation_section_lines_show_explicit_activation() {
        let temp = tempfile::tempdir().unwrap();
        let lockfile_path = temp.path().join("cuenv.lock");
        let cache_dir = temp.path().join("cache");
        let bin_dir = cache_dir
            .join("github")
            .join("jq")
            .join("1.7.1")
            .join("bin");
        fs::create_dir_all(&bin_dir).unwrap();

        let mut lockfile = Lockfile::new();
        lockfile
            .tools
            .insert("jq".to_string(), github_tool("1.7.1"));
        lockfile.tools_activation = vec![ToolActivationStep {
            var: "PATH".to_string(),
            op: ToolActivationOperation::Prepend,
            separator: ":".to_string(),
            from: ToolActivationSource::ToolBinDir {
                tool: "jq".to_string(),
            },
        }];

        let lines =
            activation_section_lines_with_cache_dir(&lockfile, &lockfile_path, Some(cache_dir));

        assert!(
            lines
                .first()
                .is_some_and(|line| line.contains("Activation (") && line.contains("explicit"))
        );
        assert_eq!(
            lines[1],
            format!("  - PATH (prepend): {}", bin_dir.display())
        );
        assert_eq!(lines.len(), 2);
    }

    #[test]
    fn test_activation_section_lines_show_invalid_activation_error() {
        let temp = tempfile::tempdir().unwrap();
        let lockfile_path = temp.path().join("cuenv.lock");
        let mut lockfile = Lockfile::new();
        lockfile
            .tools
            .insert("jq".to_string(), github_tool("1.7.1"));
        lockfile.tools_activation = vec![ToolActivationStep {
            var: "PATH".to_string(),
            op: ToolActivationOperation::Prepend,
            separator: ":".to_string(),
            from: ToolActivationSource::ToolBinDir {
                tool: "missing".to_string(),
            },
        }];

        let lines = activation_section_lines_with_cache_dir(&lockfile, &lockfile_path, None);

        assert!(
            lines
                .iter()
                .any(|line| line.contains("error:") && line.contains("unknown tool 'missing'"))
        );
    }

    #[test]
    fn test_activation_section_lines_note_when_no_paths_are_materialized() {
        let temp = tempfile::tempdir().unwrap();
        let lockfile_path = temp.path().join("cuenv.lock");
        let cache_dir = temp.path().join("cache");
        let mut lockfile = Lockfile::new();
        lockfile
            .tools
            .insert("jq".to_string(), github_tool("1.7.1"));

        let lines =
            activation_section_lines_with_cache_dir(&lockfile, &lockfile_path, Some(cache_dir));

        assert!(lines.iter().any(|line| {
            line == "  - No activation paths are currently materialized for this platform."
        }));
    }

    #[test]
    fn test_lockfile_entry_to_source_parses_url_source() {
        let locked = LockedToolPlatform {
            provider: "url".to_string(),
            digest: "sha256:abc".to_string(),
            source: serde_json::json!({
                "type": "url",
                "url": "https://example.com/tool.tar.gz",
                "extract": [{"kind": "bin", "path": "tool"}],
            }),
            size: None,
            dependencies: vec![],
        };

        let source = lockfile_entry_to_source("tool", "1.0.0", &locked).expect("parsed source");
        match source {
            ToolSource::Url { url, extract } => {
                assert_eq!(url, "https://example.com/tool.tar.gz");
                assert_eq!(
                    extract,
                    vec![ToolExtract::Bin {
                        path: "tool".to_string(),
                        as_name: None,
                    }]
                );
            }
            _ => panic!("expected URL source"),
        }
    }
}