local-ci 0.6.2

Run the GitHub Actions jobs a branch would trigger, locally, in an isolated worktree, and print a short report
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
//! The git plumbing local-ci needs: what to test, what changed, and a
//! throwaway worktree to test it in.

use anyhow::{bail, Context, Result};
use regex::Regex;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;

pub fn git(dir: &Path, args: &[&str]) -> Result<String> {
    let out = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .output()
        .context("failed to run git")?;
    if !out.status.success() {
        bail!(
            "git {}: {}",
            args.join(" "),
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim_end().to_string())
}

fn git_ok(dir: &Path, args: &[&str]) -> Option<String> {
    git(dir, args).ok().filter(|s| !s.is_empty())
}

/// `git worktree add` / `prune` / `remove`, one at a time per repository, in
/// this process and across `local-ci` runs. Side by side, an add reads the
/// `.git/worktrees/<name>/commondir` another add is still writing ("failed to
/// read ... commondir"), and a prune can drop an entry that is half made.
fn worktree_admin<T>(repo: &Path, f: impl FnOnce() -> Result<T>) -> Result<T> {
    use fs2::FileExt;
    static LOCAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
    let _local = LOCAL.lock().unwrap_or_else(|e| e.into_inner());
    let common = git(
        repo,
        &["rev-parse", "--path-format=absolute", "--git-common-dir"],
    )?;
    let lock = std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .write(true)
        .open(Path::new(&common).join("local-ci-worktrees.lock"))
        .context("cannot open the worktree lock")?;
    lock.lock_exclusive()?;
    f()
}

pub fn toplevel(dir: &Path) -> Result<PathBuf> {
    Ok(PathBuf::from(
        git(dir, &["rev-parse", "--show-toplevel"]).context("not inside a git repository")?,
    ))
}

pub fn rev(dir: &Path, r: &str) -> Result<String> {
    git(dir, &["rev-parse", "--verify", &format!("{r}^{{commit}}")])
}

pub fn is_dirty(dir: &Path) -> bool {
    git(dir, &["status", "--porcelain", "--untracked-files=no"])
        .map(|s| !s.is_empty())
        .unwrap_or(false)
}

pub fn current_branch(dir: &Path) -> Option<String> {
    git_ok(dir, &["symbolic-ref", "--short", "-q", "HEAD"])
}

/// The branch name `branches:` filters see. A `--base` that is not a branch
/// (a SHA, `HEAD~3`) stands for origin's default branch.
pub fn base_branch_name(dir: &Path, base: &str) -> String {
    let is_branch = ["refs/heads/", "refs/remotes/", "refs/remotes/origin/"]
        .iter()
        .any(|p| {
            git(
                dir,
                &["show-ref", "--verify", "--quiet", &format!("{p}{base}")],
            )
            .is_ok()
        });
    if is_branch {
        return branch_name(base);
    }
    default_base(dir)
        .map(|b| branch_name(&b))
        .unwrap_or_else(|_| "main".into())
}

/// The ref to compare against: origin's default branch, else a local main/master.
pub fn default_base(dir: &Path) -> Result<String> {
    if let Some(r) = git_ok(
        dir,
        &["symbolic-ref", "--short", "-q", "refs/remotes/origin/HEAD"],
    ) {
        return Ok(r);
    }
    for b in ["origin/main", "origin/master", "main", "master"] {
        if rev(dir, b).is_ok() {
            return Ok(b.to_string());
        }
    }
    bail!("cannot find a base branch; pass --base <ref>")
}

/// `origin/main` → `main`
pub fn branch_name(r: &str) -> String {
    r.strip_prefix("origin/")
        .or_else(|| r.strip_prefix("refs/remotes/origin/"))
        .or_else(|| r.strip_prefix("refs/heads/"))
        .unwrap_or(r)
        .to_string()
}

pub fn changed_files(dir: &Path, base: &str, sha: &str) -> Result<Vec<String>> {
    let from = git_ok(dir, &["merge-base", base, sha]).unwrap_or_else(|| base.to_string());
    let out = git(dir, &["diff", "--name-only", "--no-renames", &from, sha])?;
    Ok(out
        .lines()
        .filter(|l| !l.is_empty())
        .map(String::from)
        .collect())
}

/// Where a workflow directory was named, for the error when it holds none.
#[derive(Clone, Copy, PartialEq)]
enum Named {
    /// `.github/workflows` with no `.local-ci.toml` to replace it: may be empty.
    Default,
    Config,
    Flag,
}

/// Workflow files at `sha`, as (path, text): each of `configured` (the
/// `workflows-dirs` of `.local-ci.toml`; `.github/workflows` when `None`) and
/// then each of `extra` (`--workflows-dir`). All are relative to the
/// repository root, and every one but the unconfigured `.github/workflows`
/// must hold some.
pub fn workflows_at(
    dir: &Path,
    sha: &str,
    configured: Option<&[String]>,
    extra: &[String],
) -> Result<Vec<(String, String)>> {
    let mut dirs: Vec<(String, Named)> = match configured {
        Some(c) => c.iter().map(|d| (d.clone(), Named::Config)).collect(),
        None => vec![(
            crate::config::DEFAULT_WORKFLOWS_DIR.to_string(),
            Named::Default,
        )],
    };
    for d in extra {
        if Path::new(d).is_absolute() {
            bail!("--workflows-dir {d}: give a path relative to the repository root");
        }
        let d = crate::plan::norm_dir(d);
        if !dirs.iter().any(|(x, _)| x == &d) {
            dirs.push((d, Named::Flag));
        }
    }
    let mut out = Vec::new();
    for (d, named) in &dirs {
        let list = git(dir, &["ls-tree", "--name-only", sha, &format!("{d}/")]).unwrap_or_default();
        let files: Vec<&str> = list
            .lines()
            .filter(|f| f.ends_with(".yml") || f.ends_with(".yaml"))
            .collect();
        if files.is_empty() && *named != Named::Default {
            let source = match named {
                Named::Config => format!("{}: workflows-dirs", crate::config::FILE),
                _ => "--workflows-dir".to_string(),
            };
            bail!(
                "{source} {d}: no .yml / .yaml files there at {} (workflows are read from the commit; commit them first)",
                &sha[..sha.len().min(7)]
            );
        }
        for f in files {
            out.push((f.to_string(), git(dir, &["show", &format!("{sha}:{f}")])?));
        }
    }
    Ok(out)
}

/// `owner/name` from origin's URL.
pub fn repo_slug(dir: &Path) -> Option<String> {
    let url = git_ok(dir, &["remote", "get-url", "origin"])?;
    let s = url.trim_end_matches(".git").trim_end_matches('/');
    let tail = s.rsplit_once(':').map(|(_, t)| t).unwrap_or(s);
    let parts: Vec<&str> = tail.rsplit('/').take(2).collect();
    if parts.len() == 2 {
        Some(format!("{}/{}", parts[1], parts[0]))
    } else {
        None
    }
}

pub fn add_worktree(repo: &Path, path: &Path, sha: &str) -> Result<()> {
    worktree_admin(repo, || {
        git(
            repo,
            &[
                "worktree",
                "add",
                "--detach",
                "--quiet",
                &path.to_string_lossy(),
                sha,
            ],
        )
    })
    .map(|_| ())
}

/// Another worktree of `sha` at `to`, holding a copy of everything in `from`
/// (setup output included). Files are cloned copy-on-write where the
/// filesystem allows it, so this is quick and a write in one copy is never
/// seen in the other. With `link_node_modules` (`link-node-modules` in
/// `.local-ci.toml`) each `node_modules` holds links to what is in `from`'s
/// instead. That is off by default: tools that follow a link to where it
/// really is and then refuse paths outside the project (TypeScript emitting
/// declarations, Turbopack's workspace root) fail with it.
pub fn clone_worktree(
    repo: &Path,
    from: &Path,
    to: &Path,
    sha: &str,
    link_node_modules: bool,
) -> Result<()> {
    worktree_admin(repo, || {
        git(
            repo,
            &[
                "worktree",
                "add",
                "--detach",
                "--no-checkout",
                "--quiet",
                &to.to_string_lossy(),
                sha,
            ],
        )
    })?;
    let index = |d: &Path| {
        git(
            d,
            &["rev-parse", "--path-format=absolute", "--git-path", "index"],
        )
        .map(PathBuf::from)
    };
    std::fs::copy(index(from)?, index(to)?).context("cannot copy the index")?;
    let mut holders = HashSet::new();
    if link_node_modules {
        for nm in node_modules_dirs(from) {
            holders.extend(nm.ancestors().skip(1).map(Path::to_path_buf));
        }
    }
    let mut rest = Vec::new();
    copy_entries(
        from,
        to,
        Path::new(""),
        link_node_modules,
        &holders,
        &mut rest,
    )?;
    for (into, srcs) in rest {
        cp(&srcs, &into)?;
    }
    Ok(())
}

/// The `node_modules` directories under `root` (relative to it), not looking
/// inside them or `.git`.
fn node_modules_dirs(root: &Path) -> Vec<PathBuf> {
    let mut found = Vec::new();
    let mut todo = vec![PathBuf::new()];
    while let Some(rel) = todo.pop() {
        let Ok(rd) = std::fs::read_dir(root.join(&rel)) else {
            continue;
        };
        for e in rd.flatten() {
            if !e.file_type().is_ok_and(|t| t.is_dir()) {
                continue;
            }
            let name = e.file_name();
            if name == "node_modules" {
                found.push(rel.join(&name));
            } else if name != ".git" {
                todo.push(rel.join(&name));
            }
        }
    }
    found
}

/// Copy what is in `from` (at `rel` in the worktree) into `to`. With `link`, a
/// `node_modules` directory is linked into, not copied: setup installed it and the
/// units read it, while a copy is tens of thousands of files per project to
/// make and then delete again, each one also an event for fseventsd. A unit
/// that writes into it first makes it its own ([`own_node_modules`]). A
/// directory with one further down (`holders`) is walked into; anything else
/// is cloned whole, or left in `rest` for `cp`.
fn copy_entries(
    from: &Path,
    to: &Path,
    rel: &Path,
    link: bool,
    holders: &HashSet<PathBuf>,
    rest: &mut Vec<(PathBuf, Vec<PathBuf>)>,
) -> Result<()> {
    let mut left = Vec::new();
    for e in std::fs::read_dir(from)? {
        let e = e?;
        let name = e.file_name();
        if rel.as_os_str().is_empty() && name == ".git" {
            continue;
        }
        let is_dir = e.file_type().is_ok_and(|t| t.is_dir());
        let (src, dst, r) = (e.path(), to.join(&name), rel.join(&name));
        // a matrix entry's copy is made from a unit's: link to setup's again
        let shared = std::fs::read_to_string(src.join(SHARED)).map(PathBuf::from);
        let real = shared.as_deref().unwrap_or(&src);
        if is_dir && name == "node_modules" && link && !links_out(real) && !emits_declarations(from)
        {
            link_node_modules(real, &dst)
                .with_context(|| format!("cannot link {}", dst.display()))?;
        } else if is_dir && name == "node_modules" && shared.is_ok() {
            copy_dir(real, &dst)?;
        } else if is_dir && holders.contains(&r) {
            std::fs::create_dir(&dst)?;
            copy_entries(&src, &dst, &r, link, holders, rest)?;
        } else if !clone_tree(&src, &dst) {
            left.push(src);
        }
    }
    if !left.is_empty() {
        rest.push((to.to_path_buf(), left));
    }
    Ok(())
}

/// Copy `srcs` into the directory `into`, cloning where the filesystem allows it.
fn cp(srcs: &[PathBuf], into: &Path) -> Result<()> {
    let flags: &[&str] = if cfg!(target_os = "macos") {
        &["-Rp"]
    } else {
        &["-a", "--reflink=auto"]
    };
    let out = Command::new("cp")
        .args(flags)
        .args(srcs)
        .arg(into)
        .output()
        .context("failed to run cp")?;
    if !out.status.success() {
        bail!(
            "cp into {}: {}",
            into.display(),
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(())
}

/// Make every `node_modules` in the copy `ws` that links into setup's a copy
/// of its own, before a step that may write into one (an install,
/// `prisma generate`): the other units read setup's. All of them, as a step
/// can `cd` anywhere.
pub fn own_node_modules(ws: &Path) -> Result<()> {
    for rel in node_modules_dirs(ws) {
        let nm = ws.join(rel);
        let Ok(target) = std::fs::read_to_string(nm.join(SHARED)) else {
            continue;
        };
        let tmp = nm.with_file_name(".node_modules.local-ci");
        let _ = std::fs::remove_dir_all(&tmp);
        copy_dir(Path::new(&target), &tmp)?;
        // removes the links, not what they point to
        std::fs::remove_dir_all(&nm)?;
        std::fs::rename(&tmp, &nm)?;
    }
    Ok(())
}

/// `from` copied to `to` (which must not exist), cloned where the filesystem allows it.
fn copy_dir(from: &Path, to: &Path) -> Result<()> {
    if clone_tree(from, to) {
        return Ok(());
    }
    std::fs::create_dir(to)?;
    let entries: Vec<PathBuf> = std::fs::read_dir(from)?
        .map(|e| e.map(|e| e.path()))
        .collect::<std::io::Result<_>>()?;
    if !entries.is_empty() {
        cp(&entries, to)?;
    }
    Ok(())
}

/// Whether a package in `nm` is a link that leaves it (a workspace or
/// `file:` dependency). Through a link to setup's it would resolve into
/// setup's tree rather than the unit's, so such a `node_modules` is copied.
fn links_out(nm: &Path) -> bool {
    let Ok(rd) = std::fs::read_dir(nm) else {
        return false;
    };
    let mut entries: Vec<PathBuf> = Vec::new();
    for e in rd.flatten() {
        let p = e.path();
        if e.file_name().to_string_lossy().starts_with('@') && p.is_dir() {
            entries.extend(
                std::fs::read_dir(&p)
                    .into_iter()
                    .flatten()
                    .flatten()
                    .map(|e| e.path()),
            );
        } else {
            entries.push(p);
        }
    }
    entries.iter().any(|p| {
        std::fs::read_link(p).is_ok_and(|t| {
            let to = p.parent().unwrap_or(nm).join(t);
            !normalize(&to).starts_with(normalize(nm))
        })
    })
}

/// Whether a `tsconfig*.json` in `dir` (or one it extends by a relative
/// path) emits declarations (`declaration` or `composite`). TypeScript
/// resolves a linked package to where it really is, and a declaration that
/// would have to name a path outside the project fails with TS2742, even
/// under `--noEmit`. Such a project's `node_modules` is copied, not linked.
fn emits_declarations(dir: &Path) -> bool {
    static ON: OnceLock<Regex> = OnceLock::new();
    static EXTENDS: OnceLock<Regex> = OnceLock::new();
    let on = ON.get_or_init(|| Regex::new(r#""(declaration|composite)"\s*:\s*true"#).unwrap());
    let extends =
        EXTENDS.get_or_init(|| Regex::new(r#""extends"\s*:\s*(\[[^\]]*\]|"[^"]*")"#).unwrap());
    let mut todo: Vec<PathBuf> = std::fs::read_dir(dir)
        .into_iter()
        .flatten()
        .flatten()
        .map(|e| e.path())
        .filter(|p| {
            let n = p.file_name().unwrap_or_default().to_string_lossy();
            n.starts_with("tsconfig") && n.ends_with(".json")
        })
        .collect();
    let mut seen = HashSet::new();
    while let Some(f) = todo.pop() {
        if seen.len() > 20 || !seen.insert(f.clone()) {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(&f) else {
            continue;
        };
        if on.is_match(&text) {
            return true;
        }
        let base = f.parent().unwrap_or(dir);
        for c in extends.captures_iter(&text) {
            for name in c[1].split('"').skip(1).step_by(2) {
                if name.starts_with('.') {
                    // as TypeScript does: the name as given, else with `.json` added
                    let p = base.join(name);
                    todo.push(if p.is_file() {
                        p
                    } else {
                        PathBuf::from(format!("{}.json", p.display()))
                    });
                }
            }
        }
    }
    false
}

/// `p` with `.` and `..` taken out, without touching the filesystem.
fn normalize(p: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for c in p.components() {
        match c {
            std::path::Component::ParentDir => {
                out.pop();
            }
            std::path::Component::CurDir => {}
            c => out.push(c),
        }
    }
    out
}

/// Names the `node_modules` a unit's one links into; the npm shim reads it too.
pub const SHARED: &str = ".local-ci-shared";

/// `dst` as a directory of links to what is in `src`. A directory rather than
/// one link: `node_modules/` in a `.gitignore` matches only a directory, and
/// a link to one shows up as untracked. Node resolves a package through its
/// link to setup's copy and its dependencies from there.
fn link_node_modules(src: &Path, dst: &Path) -> Result<()> {
    std::fs::create_dir(dst)?;
    for e in std::fs::read_dir(src)? {
        let e = e?;
        std::os::unix::fs::symlink(e.path(), dst.join(e.file_name()))?;
    }
    std::fs::write(dst.join(SHARED), src.as_os_str().as_encoded_bytes())?;
    Ok(())
}

/// Clone a whole directory tree in one call (APFS). About five times faster
/// than `cp -c`, which clones file by file.
#[cfg(target_os = "macos")]
fn clone_tree(from: &Path, to: &Path) -> bool {
    use std::ffi::CString;
    use std::os::unix::ffi::OsStrExt;
    const CLONE_NOFOLLOW: u32 = 0x0001;
    let (Ok(f), Ok(t)) = (
        CString::new(from.as_os_str().as_bytes()),
        CString::new(to.as_os_str().as_bytes()),
    ) else {
        return false;
    };
    unsafe { libc::clonefile(f.as_ptr(), t.as_ptr(), CLONE_NOFOLLOW) == 0 }
}

#[cfg(not(target_os = "macos"))]
fn clone_tree(_from: &Path, _to: &Path) -> bool {
    false
}

/// Move the worktree out of the way, unregister it, and delete the files in the background.
pub fn remove_worktree(repo: &Path, path: &Path, trash: &Path) {
    let _ = std::fs::create_dir_all(trash);
    let target = trash.join(path.file_name().unwrap_or_default());
    if std::fs::rename(path, &target).is_ok() {
        let _ = worktree_admin(repo, || git(repo, &["worktree", "prune"]));
        if spawn_quiet(delete_later(&target, &trash.join(".lock"))).is_err() {
            let mut rm = Command::new("rm");
            rm.arg("-rf").arg(&target);
            let _ = spawn_quiet(rm);
        }
    } else {
        let _ = worktree_admin(repo, || {
            git(
                repo,
                &["worktree", "remove", "--force", &path.to_string_lossy()],
            )
        });
    }
}

/// `rm -rf` at the lowest priority, one deletion at a time across runs. Many
/// units end together, and a dozen copies holding `node_modules` deleted side
/// by side took several cores, and as many again in fseventsd and the kernel,
/// from the jobs still running. On macOS `lockf` waits for the deletion before
/// it. Only the CPU priority is lowered: `taskpolicy -b` also throttled the
/// disk, and on a busy machine it deleted a thousand files in two minutes, so
/// the copies would pile up faster than they went.
fn delete_later(target: &Path, lock: &Path) -> Command {
    let mut cmd = Command::new("nice");
    cmd.args(["-n", "19"]);
    if cfg!(target_os = "macos") {
        cmd.args(["lockf", "-k"]).arg(lock);
    }
    cmd.args(["rm", "-rf"]).arg(target);
    cmd
}

fn spawn_quiet(mut cmd: Command) -> std::io::Result<std::process::Child> {
    cmd.stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
}

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

    #[test]
    fn names() {
        assert_eq!(branch_name("origin/main"), "main");
        assert_eq!(branch_name("refs/heads/dev"), "dev");
        assert_eq!(branch_name("develop"), "develop");
    }

    /// Many units make and drop their copies at the same moment.
    #[test]
    fn a_copy_links_node_modules_and_owns_it_before_a_write() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("repo");
        let w = |p: &str| {
            let f = repo.join(p);
            std::fs::create_dir_all(f.parent().unwrap()).unwrap();
            std::fs::write(f, p).unwrap();
        };
        w("a.txt");
        w("api/src/b.ts");
        let ok = Command::new("git")
            .args(["-c", "user.email=t@example.com", "-c", "user.name=t"])
            .args([
                "-c",
                "commit.gpgsign=false",
                "-c",
                "core.hooksPath=/dev/null",
            ])
            .args(["init", "-q"])
            .current_dir(&repo)
            .status()
            .unwrap()
            .success();
        assert!(ok);
        git(&repo, &["add", "."]).unwrap();
        git(
            &repo,
            &[
                "-c",
                "user.email=t@example.com",
                "-c",
                "user.name=t",
                "-c",
                "commit.gpgsign=false",
                "commit",
                "-qm",
                "a",
            ],
        )
        .unwrap();
        // setup output
        w("node_modules/top/index.js");
        w("api/node_modules/x/index.js");
        w("mobile/.dart_tool/package_config.json");
        let sha = rev(&repo, "HEAD").unwrap();
        // by default every node_modules is a copy, as before
        let plain = tmp.path().join("plain");
        clone_worktree(&repo, &repo, &plain, &sha, false).unwrap();
        for p in ["node_modules/top", "api/node_modules/x"] {
            assert!(!plain.join(p).is_symlink(), "{p}");
            assert!(plain.join(p).join("index.js").is_file(), "{p}");
        }
        assert!(!plain.join("api/node_modules").join(SHARED).exists());
        let to = tmp.path().join("copy");
        clone_worktree(&repo, &repo, &to, &sha, true).unwrap();
        let link = |p: &str| std::fs::read_link(to.join(p)).ok();
        // a directory of links, which `node_modules/` in a .gitignore matches
        assert!(to
            .join("api/node_modules")
            .symlink_metadata()
            .unwrap()
            .is_dir());
        assert_eq!(
            link("node_modules/top"),
            Some(repo.join("node_modules/top"))
        );
        assert_eq!(
            link("api/node_modules/x"),
            Some(repo.join("api/node_modules/x"))
        );
        assert_eq!(link("api/src"), None);
        assert_eq!(link("mobile/.dart_tool"), None);
        assert!(to.join("api/node_modules/x/index.js").is_file());
        assert!(to.join("mobile/.dart_tool/package_config.json").is_file());
        assert_eq!(
            std::fs::read_to_string(to.join("api/src/b.ts")).unwrap(),
            "api/src/b.ts"
        );
        // a matrix entry's copy, made from the unit's, links to setup's too
        let to2 = tmp.path().join("copy2");
        clone_worktree(&repo, &to, &to2, &sha, true).unwrap();
        assert_eq!(
            std::fs::read_link(to2.join("api/node_modules/x")).ok(),
            Some(repo.join("api/node_modules/x"))
        );
        own_node_modules(&to2).unwrap();
        assert!(!to2.join("api/node_modules/x").is_symlink());
        assert!(to2.join("api/node_modules/x/index.js").is_file());
        // owning every node_modules, wherever the step runs
        own_node_modules(&to).unwrap();
        assert_eq!(link("api/node_modules/x"), None);
        assert_eq!(link("node_modules/top"), None);
        assert!(!to.join("api/node_modules").join(SHARED).exists());
        assert!(repo.join("api/node_modules/x/index.js").is_file());
        std::fs::write(to.join("api/node_modules/x/index.js"), "changed").unwrap();
        assert_eq!(
            std::fs::read_to_string(repo.join("api/node_modules/x/index.js")).unwrap(),
            "api/node_modules/x/index.js"
        );
        assert!(!to.join("api/.node_modules.local-ci").exists());
    }

    #[test]
    fn a_project_emitting_declarations_does_not_share_node_modules() {
        let tmp = tempfile::tempdir().unwrap();
        let api = tmp.path().join("api");
        std::fs::create_dir_all(&api).unwrap();
        // comments and trailing commas, as tsconfig allows
        std::fs::write(
            api.join("tsconfig.json"),
            "{\n  // shared\n  \"extends\": \"../tsconfig.base\",\n  \"compilerOptions\": { \"strict\": true, },\n}\n",
        )
        .unwrap();
        std::fs::write(
            api.join("tsconfig.build.json"),
            "{ \"extends\": \"./tsconfig.json\" }",
        )
        .unwrap();
        std::fs::write(
            tmp.path().join("tsconfig.base.json"),
            "{ \"compilerOptions\": { \"declaration\": false } }",
        )
        .unwrap();
        assert!(!emits_declarations(&api));
        std::fs::write(
            tmp.path().join("tsconfig.base.json"),
            "{ \"compilerOptions\": { \"declaration\": true } }",
        )
        .unwrap();
        assert!(emits_declarations(&api));
        std::fs::write(
            api.join("tsconfig.json"),
            "{ \"extends\": [\"@tsconfig/node20\"], \"compilerOptions\": { \"composite\": true } }",
        )
        .unwrap();
        assert!(emits_declarations(&api));
        assert!(!emits_declarations(tmp.path().join("web").as_path()));
    }

    #[test]
    fn a_node_modules_linking_into_the_repository_is_not_shared() {
        let tmp = tempfile::tempdir().unwrap();
        let nm = tmp.path().join("web/node_modules");
        std::fs::create_dir_all(nm.join("@s")).unwrap();
        std::fs::create_dir_all(nm.join("plain")).unwrap();
        std::os::unix::fs::symlink("plain", nm.join("alias")).unwrap();
        assert!(!links_out(&nm));
        std::os::unix::fs::symlink("../../../shared", nm.join("@s/w")).unwrap();
        assert!(links_out(&nm));
    }

    #[test]
    fn copies_made_and_removed_side_by_side() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        let run = |args: &[&str]| {
            let ok = Command::new("git")
                .args(["-c", "user.email=t@example.com", "-c", "user.name=t"])
                .args([
                    "-c",
                    "commit.gpgsign=false",
                    "-c",
                    "core.hooksPath=/dev/null",
                ])
                .args(args)
                .current_dir(&repo)
                .output()
                .unwrap()
                .status
                .success();
            assert!(ok, "git {args:?}");
        };
        run(&["init", "-q"]);
        std::fs::write(repo.join("a.txt"), "a").unwrap();
        run(&["add", "a.txt"]);
        run(&["commit", "-qm", "a"]);
        let sha = rev(&repo, "HEAD").unwrap();
        let trash = tmp.path().join("trash");
        std::thread::scope(|s| {
            for i in 0..24 {
                let (repo, sha, trash) = (&repo, &sha, &trash);
                let to = tmp.path().join(format!("c{i}"));
                s.spawn(move || {
                    clone_worktree(repo, repo, &to, sha, false).unwrap();
                    assert!(to.join("a.txt").is_file());
                    remove_worktree(repo, &to, trash);
                });
            }
        });
        assert_eq!(
            git(&repo, &["worktree", "list"]).unwrap().lines().count(),
            1
        );
        // The deletions queue behind one another and still all finish.
        let left = || {
            std::fs::read_dir(&trash)
                .unwrap()
                .filter(|e| e.as_ref().unwrap().file_name() != ".lock")
                .count()
        };
        let until = std::time::Instant::now() + std::time::Duration::from_secs(60);
        while left() > 0 && std::time::Instant::now() < until {
            std::thread::sleep(std::time::Duration::from_millis(100));
        }
        assert_eq!(left(), 0);
    }
}