mlua-pkg 0.4.1

Composable Lua module loader for mlua
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
//! `mlua-pkg` CLI — install / add / update / clean.
//!
//! Each subcommand delegates to a free function (`run_*`) that accepts
//! explicit path arguments, which makes them unit-testable without touching
//! the process working directory.

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

use anyhow::Context as _;
use clap::{Parser, Subcommand};

use mlua_pkg::{
    fetcher::{Fetcher, GitFetcher},
    lockfile::{LockedPkg, Lockfile},
    manifest::{Dep, Manifest, Package},
    resolve_entry, PkgError,
};

// ── CLI definition ─────────────────────────────────────────────────────────────

#[derive(Parser)]
#[command(
    name = "mlua-pkg",
    about = "Lua package manager for mlua",
    version,
    author
)]
struct Cli {
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Fetch all packages listed in mlua-pkg.toml and write mlua-pkg.lock.
    Install,

    /// Add a new dependency to mlua-pkg.toml (run `install` afterwards to fetch).
    Add {
        /// Local package alias used in `require()`.
        name: String,
        /// Remote git URL.
        git: String,
        /// Pin to a specific tag.
        #[arg(long)]
        tag: Option<String>,
        /// Pin to a specific commit revision.
        #[arg(long)]
        rev: Option<String>,
        /// Track a branch (non-reproducible).
        #[arg(long)]
        branch: Option<String>,
        /// Override the Lua `require()` entry subdir.
        #[arg(long)]
        entry: Option<PathBuf>,
    },

    /// Re-fetch packages from the manifest (MVP: re-installs all packages).
    Update {
        /// Package name to update (MVP: re-installs all regardless).
        name: Option<String>,
    },

    /// Remove stale cached packages not referenced by the lockfile.
    Clean {
        /// Remove the entire cache directory, not just stale entries.
        #[arg(long)]
        all: bool,
    },
}

// ── Entry point ───────────────────────────────────────────────────────────────

/// Strip the redundant `mlua-pkg` arg that Cargo injects when the binary is
/// invoked as `cargo mlua-pkg ...` (Cargo dispatches `cargo <name> <args...>`
/// to `cargo-<name>` with `<name>` re-added as `args[1]`).
fn strip_cargo_subcommand<I>(args: I) -> Vec<String>
where
    I: IntoIterator<Item = String>,
{
    let mut args: Vec<String> = args.into_iter().collect();
    if args.get(1).map(String::as_str) == Some("mlua-pkg") {
        args.remove(1);
    }
    args
}

fn main() -> anyhow::Result<()> {
    let cli = Cli::parse_from(strip_cargo_subcommand(std::env::args()));
    match cli.cmd {
        Cmd::Install => run_install(
            Path::new("mlua-pkg.toml"),
            Path::new(".mlua-pkgs/cache"),
            Path::new(".mlua-pkgs/vendored"),
            Path::new("mlua-pkg.lock"),
        ),
        Cmd::Add {
            name,
            git,
            tag,
            rev,
            branch,
            entry,
        } => run_add(
            Path::new("mlua-pkg.toml"),
            name,
            git,
            tag,
            rev,
            branch,
            entry,
        ),
        Cmd::Update { name } => run_update(
            name,
            Path::new("mlua-pkg.toml"),
            Path::new(".mlua-pkgs/cache"),
            Path::new(".mlua-pkgs/vendored"),
            Path::new("mlua-pkg.lock"),
        ),
        Cmd::Clean { all } => run_clean(
            all,
            Path::new(".mlua-pkgs/cache"),
            Path::new("mlua-pkg.lock"),
        ),
    }
}

// ── install ───────────────────────────────────────────────────────────────────

/// Core install logic — testable with explicit paths.
fn run_install(
    manifest_path: &Path,
    cache_dir: &Path,
    vendored_dir: &Path,
    lock_path: &Path,
) -> anyhow::Result<()> {
    let manifest = Manifest::from_path(manifest_path)
        .with_context(|| format!("reading {}", manifest_path.display()))?;

    let fetcher = GitFetcher::new(cache_dir.to_path_buf());
    std::fs::create_dir_all(vendored_dir)?;

    let mut locked_pkgs: Vec<LockedPkg> = Vec::with_capacity(manifest.deps.len());
    // Belt-and-suspenders same-name guard (HashMap keys are already unique for
    // direct deps; this guard becomes meaningful when transitive deps are added).
    let mut seen_names: HashSet<String> = HashSet::new();

    for (name, dep) in &manifest.deps {
        if !seen_names.insert(name.clone()) {
            return Err(PkgError::SameNameConflict { name: name.clone() }.into());
        }

        let fetched = fetcher
            .fetch(dep)
            .with_context(|| format!("fetching '{name}'"))?;

        // Author manifest version-assert: warn on tag mismatch, don't hard-error.
        if let Some(author) = &fetched.manifest {
            if let Some(req_tag) = &dep.tag {
                let av = &author.package.version;
                let normalized = req_tag.strip_prefix('v').unwrap_or(req_tag.as_str());
                if av != req_tag && av != normalized {
                    eprintln!(
                        "warning: {name}: requested tag '{req_tag}' vs \
                         author manifest version '{av}'"
                    );
                }
            }
        }

        // Entry resolution: dep.entry > author-manifest entry > fallback chain.
        let author_entry: Option<PathBuf> = fetched
            .manifest
            .as_ref()
            .and_then(|m| m.package.entry.clone());
        let override_entry: Option<&Path> = dep.entry.as_deref().or(author_entry.as_deref());

        let entry_abs = resolve_entry(&fetched.cache_path, override_entry)
            .with_context(|| format!("resolving entry for '{name}'"))?;

        // Create relative symlink: .mlua-pkgs/vendored/<name> → ../cache/git/…
        let symlink_path = vendored_dir.join(name);
        if symlink_path.symlink_metadata().is_ok() {
            remove_symlink(&symlink_path)?;
        }
        let rel_target = relative_path(vendored_dir, &entry_abs)?;
        create_symlink(&rel_target, &symlink_path)?;

        // Compute entry relative to the package cache root for the lockfile.
        let entry = entry_rel_to_pkg(&fetched.cache_path, &entry_abs);

        locked_pkgs.push(LockedPkg {
            name: name.clone(),
            source: format!("git+{}", dep.git),
            tag: dep.tag.clone(),
            rev: dep.rev.clone(),
            branch: dep.branch.clone(),
            sha: fetched.sha,
            entry,
        });
    }

    let lockfile = Lockfile {
        version: 1,
        pkg: locked_pkgs,
    };
    lockfile.write(lock_path)?;

    println!("installed {} package(s)", manifest.deps.len());
    Ok(())
}

/// Strip `cache_path` prefix from `entry_abs`; return `"."` for the repo root.
fn entry_rel_to_pkg(cache_path: &Path, entry_abs: &Path) -> PathBuf {
    match entry_abs.strip_prefix(cache_path) {
        Ok(rel) if rel.as_os_str().is_empty() => PathBuf::from("."),
        Ok(rel) => rel.to_path_buf(),
        Err(_) => PathBuf::from("."),
    }
}

// ── add ───────────────────────────────────────────────────────────────────────

fn run_add(
    manifest_path: &Path,
    name: String,
    git: String,
    tag: Option<String>,
    rev: Option<String>,
    branch: Option<String>,
    entry: Option<PathBuf>,
) -> anyhow::Result<()> {
    // Validate ref-field exclusivity up front.
    let ref_count = [tag.is_some(), rev.is_some(), branch.is_some()]
        .into_iter()
        .filter(|&b| b)
        .count();
    if ref_count > 1 {
        return Err(anyhow::anyhow!(
            "at most one of --tag, --rev, --branch may be specified"
        ));
    }

    // Load existing manifest or synthesise a minimal one.
    let mut manifest = if manifest_path.exists() {
        Manifest::from_path(manifest_path)
            .with_context(|| format!("reading {}", manifest_path.display()))?
    } else {
        let pkg_name = std::env::current_dir()
            .ok()
            .and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
            .unwrap_or_else(|| "my-project".to_string());
        Manifest {
            package: Package {
                name: pkg_name,
                version: "0.1.0".to_string(),
                entry: None,
            },
            deps: HashMap::new(),
        }
    };

    let dep = Dep {
        git,
        tag,
        rev,
        branch,
        entry,
    };
    let existed = manifest.deps.insert(name.clone(), dep).is_some();

    let toml_str = toml::to_string(&manifest)?;
    std::fs::write(manifest_path, toml_str)?;

    if existed {
        println!(
            "updated '{}' in {}; run 'mlua-pkg install' to fetch",
            name,
            manifest_path.display()
        );
    } else {
        println!(
            "added '{}' to {}; run 'mlua-pkg install' to fetch",
            name,
            manifest_path.display()
        );
    }
    Ok(())
}

// ── update ────────────────────────────────────────────────────────────────────

fn run_update(
    name: Option<String>,
    manifest_path: &Path,
    cache_dir: &Path,
    vendored_dir: &Path,
    lock_path: &Path,
) -> anyhow::Result<()> {
    // If a specific name was given, verify it exists in the manifest.
    if let Some(ref n) = name {
        let manifest = Manifest::from_path(manifest_path)
            .with_context(|| format!("reading {}", manifest_path.display()))?;
        if !manifest.deps.contains_key(n) {
            return Err(anyhow::anyhow!(
                "unknown package '{}' in {}",
                n,
                manifest_path.display()
            ));
        }
    }

    // MVP: re-run install for all packages.
    run_install(manifest_path, cache_dir, vendored_dir, lock_path)
}

// ── clean ─────────────────────────────────────────────────────────────────────

fn run_clean(all: bool, cache_dir: &Path, lock_path: &Path) -> anyhow::Result<()> {
    if all {
        if cache_dir.exists() {
            std::fs::remove_dir_all(cache_dir)?;
            println!("removed all cached packages");
        } else {
            println!("nothing to clean");
        }
        return Ok(());
    }

    // Read lockfile — absent means nothing was ever installed.
    let lockfile = match Lockfile::read(lock_path) {
        Ok(lf) => lf,
        Err(PkgError::MissingLockfile { .. }) => {
            println!("no lockfile found; nothing to clean");
            return Ok(());
        }
        Err(e) => return Err(e.into()),
    };

    let in_use: HashSet<String> = lockfile.pkg.iter().map(|p| p.sha.clone()).collect();

    let git_dir = cache_dir.join("git");
    if !git_dir.exists() {
        println!("nothing to clean");
        return Ok(());
    }

    let mut removed: usize = 0;
    remove_stale_sha_dirs(&git_dir, &in_use, &mut removed)?;
    println!(
        "removed {removed} stale cache entr{}",
        if removed == 1 { "y" } else { "ies" }
    );
    Ok(())
}

/// Recursively walk `dir` and delete subdirectories whose name is a 40-hex
/// SHA that is absent from `in_use`.
fn remove_stale_sha_dirs(
    dir: &Path,
    in_use: &HashSet<String>,
    removed: &mut usize,
) -> std::io::Result<()> {
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let file_name = entry.file_name();
        let name = file_name.to_string_lossy();
        if name.len() == 40 && name.chars().all(|c| c.is_ascii_hexdigit()) {
            if !in_use.contains(name.as_ref()) {
                std::fs::remove_dir_all(&path)?;
                *removed += 1;
            }
        } else {
            // Descend deeper (host / org / repo levels).
            remove_stale_sha_dirs(&path, in_use, removed)?;
        }
    }
    Ok(())
}

// ── symlink helpers ───────────────────────────────────────────────────────────

/// Create a directory symlink at `link` pointing to `target`.
#[cfg(unix)]
fn create_symlink(target: &Path, link: &Path) -> std::io::Result<()> {
    std::os::unix::fs::symlink(target, link)
}

#[cfg(windows)]
fn create_symlink(target: &Path, link: &Path) -> std::io::Result<()> {
    std::os::windows::fs::symlink_dir(target, link)
}

#[cfg(not(any(unix, windows)))]
fn create_symlink(_target: &Path, _link: &Path) -> std::io::Result<()> {
    Err(std::io::Error::new(
        std::io::ErrorKind::Unsupported,
        "symlinks not supported on this platform",
    ))
}

/// Remove a symlink at `path`.
#[cfg(unix)]
fn remove_symlink(path: &Path) -> std::io::Result<()> {
    std::fs::remove_file(path)
}

#[cfg(windows)]
fn remove_symlink(path: &Path) -> std::io::Result<()> {
    // On Windows a directory symlink is removed with remove_dir.
    if path.is_dir() {
        std::fs::remove_dir(path)
    } else {
        std::fs::remove_file(path)
    }
}

#[cfg(not(any(unix, windows)))]
fn remove_symlink(path: &Path) -> std::io::Result<()> {
    std::fs::remove_file(path)
}

/// Compute the path to `to` relative to `from_dir`.
///
/// Canonicalises both arguments so the result is correct even when the
/// process working directory is a symlinked path (e.g. macOS `/Users` →
/// `/private/Users`).  Both paths must already exist on the filesystem.
fn relative_path(from_dir: &Path, to: &Path) -> std::io::Result<PathBuf> {
    let from_abs = std::fs::canonicalize(from_dir)?;
    let to_abs = std::fs::canonicalize(to)?;

    let from_parts: Vec<_> = from_abs.components().collect();
    let to_parts: Vec<_> = to_abs.components().collect();

    let common = from_parts
        .iter()
        .zip(to_parts.iter())
        .take_while(|(a, b)| a == b)
        .count();

    let mut rel = PathBuf::new();
    for _ in &from_parts[common..] {
        rel.push("..");
    }
    for c in &to_parts[common..] {
        rel.push(c);
    }
    Ok(rel)
}

// ── tests ─────────────────────────────────────────────────────────────────────

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

    // ── helpers ───────────────────────────────────────────────────────────────

    /// Initialise a bare git repository at `dir`, write a single `main.lua`
    /// file, commit it, and return the 40-char commit SHA.
    fn init_repo_with_commit(dir: &Path) -> String {
        use git2::{Repository, Signature};

        let repo = Repository::init(dir).unwrap();
        {
            let mut cfg = repo.config().unwrap();
            cfg.set_str("user.name", "Test").unwrap();
            cfg.set_str("user.email", "test@example.com").unwrap();
        }

        std::fs::write(dir.join("main.lua"), "return {}\n").unwrap();

        let mut index = repo.index().unwrap();
        index.add_path(Path::new("main.lua")).unwrap();
        index.write().unwrap();
        let tree_id = index.write_tree().unwrap();
        let tree = repo.find_tree(tree_id).unwrap();
        let sig = Signature::now("Test", "test@example.com").unwrap();
        let oid = repo
            .commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
            .unwrap();
        oid.to_string()
    }

    /// Write `content` to `path` (creating parent dirs as needed).
    fn write_file(path: &Path, content: &str) {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(path, content).unwrap();
    }

    // ── install ───────────────────────────────────────────────────────────────

    #[test]
    fn install_creates_lockfile_and_symlink() {
        let remote = TempDir::new().unwrap();
        let sha = init_repo_with_commit(remote.path());

        let project = TempDir::new().unwrap();
        let manifest_path = project.path().join("mlua-pkg.toml");
        let cache_dir = project.path().join(".mlua-pkgs/cache");
        let vendored_dir = project.path().join(".mlua-pkgs/vendored");
        let lock_path = project.path().join("mlua-pkg.lock");

        let url = format!("file://{}", remote.path().display());
        write_file(
            &manifest_path,
            &format!(
                "[package]\nname = \"test\"\nversion = \"0.1.0\"\n\n\
                 [deps]\nmylib = {{ git = \"{url}\", rev = \"{sha}\" }}\n"
            ),
        );

        run_install(&manifest_path, &cache_dir, &vendored_dir, &lock_path).unwrap();

        // Lockfile exists and has one entry.
        assert!(lock_path.exists(), "lockfile must be written");
        let lf = Lockfile::read(&lock_path).unwrap();
        assert_eq!(lf.pkg.len(), 1, "one locked package");
        assert_eq!(lf.pkg[0].name, "mylib");
        assert_eq!(lf.pkg[0].sha, sha);
        assert_eq!(lf.pkg[0].source, format!("git+{url}"));

        // Vendored symlink exists.
        let symlink = vendored_dir.join("mylib");
        assert!(
            symlink.symlink_metadata().is_ok(),
            "symlink .mlua-pkgs/vendored/mylib must exist"
        );
        // Symlink target must be relative (not absolute).
        let target = std::fs::read_link(&symlink).unwrap();
        assert!(
            target.is_relative(),
            "symlink target must be a relative path, got: {}",
            target.display()
        );
    }

    #[test]
    fn install_missing_manifest_returns_error() {
        let project = TempDir::new().unwrap();
        let result = run_install(
            &project.path().join("mlua-pkg.toml"),
            &project.path().join(".mlua-pkgs/cache"),
            &project.path().join(".mlua-pkgs/vendored"),
            &project.path().join("mlua-pkg.lock"),
        );
        assert!(result.is_err(), "must fail when mlua-pkg.toml is absent");
    }

    #[test]
    fn install_is_idempotent() {
        // Running install twice must succeed (symlink replaced, lockfile overwritten).
        let remote = TempDir::new().unwrap();
        let sha = init_repo_with_commit(remote.path());

        let project = TempDir::new().unwrap();
        let manifest_path = project.path().join("mlua-pkg.toml");
        let cache_dir = project.path().join(".mlua-pkgs/cache");
        let vendored_dir = project.path().join(".mlua-pkgs/vendored");
        let lock_path = project.path().join("mlua-pkg.lock");

        let url = format!("file://{}", remote.path().display());
        write_file(
            &manifest_path,
            &format!(
                "[package]\nname = \"test\"\nversion = \"0.1.0\"\n\n\
                 [deps]\nlib = {{ git = \"{url}\", rev = \"{sha}\" }}\n"
            ),
        );

        run_install(&manifest_path, &cache_dir, &vendored_dir, &lock_path).unwrap();
        run_install(&manifest_path, &cache_dir, &vendored_dir, &lock_path).unwrap();

        let lf = Lockfile::read(&lock_path).unwrap();
        assert_eq!(lf.pkg.len(), 1);
    }

    // ── add ───────────────────────────────────────────────────────────────────

    #[test]
    fn add_creates_manifest_with_dep() {
        let project = TempDir::new().unwrap();
        let manifest_path = project.path().join("mlua-pkg.toml");

        run_add(
            &manifest_path,
            "mylib".to_string(),
            "https://github.com/x/mylib".to_string(),
            Some("v1.0.0".to_string()),
            None,
            None,
            None,
        )
        .unwrap();

        let manifest = Manifest::from_path(&manifest_path).unwrap();
        assert!(manifest.deps.contains_key("mylib"), "dep must be present");
        let dep = &manifest.deps["mylib"];
        assert_eq!(dep.git, "https://github.com/x/mylib");
        assert_eq!(dep.tag.as_deref(), Some("v1.0.0"));
        assert!(dep.rev.is_none());
        assert!(dep.branch.is_none());
    }

    #[test]
    fn add_to_existing_manifest_preserves_other_deps() {
        let project = TempDir::new().unwrap();
        let manifest_path = project.path().join("mlua-pkg.toml");

        write_file(
            &manifest_path,
            "[package]\nname = \"test\"\nversion = \"0.1.0\"\n\n\
             [deps]\nexisting = { git = \"https://github.com/a/b\", branch = \"main\" }\n",
        );

        run_add(
            &manifest_path,
            "newdep".to_string(),
            "https://github.com/x/newdep".to_string(),
            None,
            Some("abc1234567890123456789012345678901234567890".to_string()),
            None,
            None,
        )
        .unwrap();

        let manifest = Manifest::from_path(&manifest_path).unwrap();
        assert_eq!(manifest.deps.len(), 2, "both deps must be present");
        assert!(manifest.deps.contains_key("existing"));
        assert!(manifest.deps.contains_key("newdep"));
    }

    #[test]
    fn add_rejects_multiple_ref_fields() {
        let project = TempDir::new().unwrap();
        let manifest_path = project.path().join("mlua-pkg.toml");

        let result = run_add(
            &manifest_path,
            "lib".to_string(),
            "https://github.com/x/lib".to_string(),
            Some("v1.0.0".to_string()),
            Some("abc123".to_string()),
            None,
            None,
        );
        assert!(result.is_err(), "tag + rev together must be rejected");
    }

    // ── update ────────────────────────────────────────────────────────────────

    #[test]
    fn update_unknown_name_returns_error() {
        let project = TempDir::new().unwrap();
        let manifest_path = project.path().join("mlua-pkg.toml");

        write_file(
            &manifest_path,
            "[package]\nname = \"test\"\nversion = \"0.1.0\"\n",
        );

        let result = run_update(
            Some("nonexistent".to_string()),
            &manifest_path,
            &project.path().join("cache"),
            &project.path().join("vendored"),
            &project.path().join("mlua-pkg.lock"),
        );
        assert!(result.is_err(), "unknown dep name must return error");
    }

    // ── clean ─────────────────────────────────────────────────────────────────

    #[test]
    fn clean_all_removes_cache() {
        let project = TempDir::new().unwrap();
        let cache_dir = project.path().join(".mlua-pkgs/cache");
        let git_dir = cache_dir.join("git/example.com/org/repo");
        std::fs::create_dir_all(&git_dir).unwrap();
        std::fs::write(git_dir.join("sentinel"), "data").unwrap();

        run_clean(true, &cache_dir, &project.path().join("mlua-pkg.lock")).unwrap();

        assert!(!cache_dir.exists(), "cache directory must be removed");
    }

    #[test]
    fn clean_all_on_empty_dir_is_noop() {
        let project = TempDir::new().unwrap();
        let cache_dir = project.path().join(".mlua-pkgs/cache");

        // Does not exist — must succeed without error.
        run_clean(true, &cache_dir, &project.path().join("mlua-pkg.lock")).unwrap();
    }

    #[test]
    fn clean_without_lockfile_is_noop() {
        let project = TempDir::new().unwrap();

        run_clean(
            false,
            &project.path().join(".mlua-pkgs/cache"),
            &project.path().join("mlua-pkg.lock"),
        )
        .unwrap();
    }

    #[test]
    fn clean_removes_stale_sha_dirs_only() {
        let project = TempDir::new().unwrap();
        let cache_dir = project.path().join(".mlua-pkgs/cache");
        let git_base = cache_dir.join("git/gh.com/org/repo");

        let sha_in_use = "a".repeat(40);
        let sha_stale = "b".repeat(40);

        std::fs::create_dir_all(git_base.join(&sha_in_use)).unwrap();
        std::fs::create_dir_all(git_base.join(&sha_stale)).unwrap();

        // Write a lockfile that references only sha_in_use.
        let lock_path = project.path().join("mlua-pkg.lock");
        let lf = Lockfile {
            version: 1,
            pkg: vec![LockedPkg {
                name: "lib".to_string(),
                source: "git+https://gh.com/org/repo".to_string(),
                tag: None,
                rev: None,
                branch: None,
                sha: sha_in_use.clone(),
                entry: PathBuf::from("."),
            }],
        };
        lf.write(&lock_path).unwrap();

        run_clean(false, &cache_dir, &lock_path).unwrap();

        assert!(
            git_base.join(&sha_in_use).exists(),
            "in-use SHA dir must be retained"
        );
        assert!(
            !git_base.join(&sha_stale).exists(),
            "stale SHA dir must be removed"
        );
    }

    // ── relative_path ─────────────────────────────────────────────────────────

    #[test]
    fn relative_path_sibling_dirs() {
        let tmp = TempDir::new().unwrap();
        let from_dir = tmp.path().join("a/b");
        let to_dir = tmp.path().join("a/c/d");
        std::fs::create_dir_all(&from_dir).unwrap();
        std::fs::create_dir_all(&to_dir).unwrap();

        let rel = relative_path(&from_dir, &to_dir).unwrap();
        // Expect: "../c/d"
        assert_eq!(rel, PathBuf::from("../c/d"));
    }

    #[test]
    fn relative_path_vendored_to_cache() {
        let tmp = TempDir::new().unwrap();
        let vendored = tmp.path().join(".mlua-pkgs/vendored");
        let entry = tmp
            .path()
            .join(".mlua-pkgs/cache/git/gh.com/org/repo/aaaa1234/src");
        std::fs::create_dir_all(&vendored).unwrap();
        std::fs::create_dir_all(&entry).unwrap();

        let rel = relative_path(&vendored, &entry).unwrap();
        assert!(
            rel.starts_with(".."),
            "must navigate up from vendored first"
        );
        assert!(
            rel.to_string_lossy().contains("cache"),
            "must contain 'cache' segment"
        );
    }

    // ── entry_rel_to_pkg ──────────────────────────────────────────────────────

    #[test]
    fn entry_rel_to_pkg_subdir() {
        let cache = PathBuf::from("/tmp/repo");
        let entry = PathBuf::from("/tmp/repo/src");
        assert_eq!(entry_rel_to_pkg(&cache, &entry), PathBuf::from("src"));
    }

    #[test]
    fn entry_rel_to_pkg_root() {
        let cache = PathBuf::from("/tmp/repo");
        let entry = PathBuf::from("/tmp/repo");
        assert_eq!(entry_rel_to_pkg(&cache, &entry), PathBuf::from("."));
    }

    // ── CLI parse smoke ───────────────────────────────────────────────────────

    #[test]
    fn cli_debug_assert() {
        use clap::CommandFactory;
        Cli::command().debug_assert();
    }

    // ── cargo subcommand arg strip ────────────────────────────────────────────

    #[test]
    fn strip_cargo_subcommand_drops_redundant_arg() {
        let input = vec![
            "cargo-mlua-pkg".to_string(),
            "mlua-pkg".to_string(),
            "install".to_string(),
        ];
        let out = strip_cargo_subcommand(input);
        assert_eq!(
            out,
            vec!["cargo-mlua-pkg".to_string(), "install".to_string()]
        );
    }

    #[test]
    fn strip_cargo_subcommand_leaves_standalone_invocation_alone() {
        let input = vec!["mlua-pkg".to_string(), "install".to_string()];
        let out = strip_cargo_subcommand(input);
        assert_eq!(out, vec!["mlua-pkg".to_string(), "install".to_string()]);
    }

    #[test]
    fn strip_cargo_subcommand_handles_empty() {
        let out = strip_cargo_subcommand(Vec::<String>::new());
        assert!(out.is_empty());
    }
}