local-ci 0.5.1

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
//! 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 std::path::{Path, PathBuf};
use std::process::Command;

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 such as `node_modules` 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.
pub fn clone_worktree(repo: &Path, from: &Path, to: &Path, sha: &str) -> 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 rest = Vec::new();
    for e in std::fs::read_dir(from)? {
        let e = e?;
        if e.file_name() != ".git" && !clone_tree(&e.path(), &to.join(e.file_name())) {
            rest.push(e.path());
        }
    }
    if rest.is_empty() {
        return Ok(());
    }
    let flags: &[&str] = if cfg!(target_os = "macos") {
        &["-Rp"]
    } else {
        &["-a", "--reflink=auto"]
    };
    let out = Command::new("cp")
        .args(flags)
        .args(&rest)
        .arg(to)
        .output()
        .context("failed to run cp")?;
    if !out.status.success() {
        bail!(
            "cp {}: {}",
            from.display(),
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    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 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).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);
    }
}