Skip to main content

tak_cli/
backfill.rs

1//! Backfill history from published release binaries.
2//!
3//! A new adopter's first chart is empty, and an empty chart persuades nobody.
4//! Rather than rebuilding a project at a hundred historical commits — hours of
5//! compute, and impossible for anyone without a reproducible build — this
6//! downloads the binaries the project already published and measures those.
7//! Minutes, not hours, and it works for projects whose old commits no longer
8//! build at all.
9//!
10//! Network and archive handling shell out to `curl` and `tar`/`unzip` for the
11//! same reason [`crate::notes`] shells out to `git`: proxies, CA bundles and
12//! credential helpers are already solved there, and the dependency tree stays
13//! small.
14
15use anyhow::{Context, Result, bail};
16use asset_picker::{AssetPicker, Format, detect_platform_from_url};
17use serde::Deserialize;
18use std::io::Write;
19use std::path::{Path, PathBuf};
20use std::process::{Command, Stdio};
21
22#[derive(Debug, Clone, Deserialize)]
23pub struct Asset {
24    pub name: String,
25    #[serde(rename = "browser_download_url")]
26    pub url: String,
27}
28
29#[derive(Debug, Clone, Deserialize)]
30pub struct Release {
31    #[serde(rename = "tag_name")]
32    pub tag: String,
33    pub published_at: Option<String>,
34    #[serde(default)]
35    pub prerelease: bool,
36    /// Drafts are visible to authenticated requests and are not published
37    /// artefacts, so benchmarking one would record a version nobody can install.
38    #[serde(default)]
39    pub draft: bool,
40    #[serde(default)]
41    pub assets: Vec<Asset>,
42}
43
44/// GitHub's maximum, and the fewest round trips per page of history.
45const PER_PAGE: usize = 100;
46/// Bound the walk so a `--limit` larger than a project's history cannot spin.
47const MAX_PAGES: usize = 10;
48
49fn github_token() -> Option<String> {
50    std::env::var("GITHUB_TOKEN")
51        .or_else(|_| std::env::var("GH_TOKEN"))
52        .ok()
53        .filter(|t| !t.is_empty())
54}
55
56/// Run curl, keeping the bearer token off the command line.
57///
58/// The split matters. A token passed as `-H` lands in argv, where any local
59/// process reading `/proc` recovers it, so it goes over stdin via `--config -`.
60/// The URL and output path are *not* secret and go as ordinary arguments —
61/// which also sidesteps curl's config quoting, where a value containing `"` or
62/// a newline would otherwise close the quoted field and inject further
63/// directives. A crafted `browser_download_url` could then add its own `url =`
64/// line and receive the Authorization header meant for GitHub.
65fn curl(url: &str, output: Option<&Path>, auth: bool) -> Result<Vec<u8>> {
66    // `proto`/`proto-redir` are the load-bearing part: `location` follows
67    // redirects, and without pinning the redirect protocol a downgrade to
68    // http:// on the same host would carry the Authorization header in clear.
69    // Checking only the initial URL is not enough.
70    let mut cfg = String::from(
71        "silent\nshow-error\nlocation\nfail\nproto = \"=https\"\nproto-redir = \"=https\"\n",
72    );
73    cfg.push_str("header = \"User-Agent: tak\"\n");
74    if auth && let Some(token) = github_token() {
75        // curl's config format has no escape for `"` inside a quoted value, and
76        // GitHub tokens are ASCII-alphanumeric with `_`, so a token containing
77        // a quote is malformed rather than something to escape.
78        if token.contains(['"', '\n', '\r']) {
79            bail!("refusing to use a token containing quotes or newlines");
80        }
81        cfg.push_str(&format!("header = \"Authorization: Bearer {token}\"\n"));
82    }
83
84    // Only ever talk to https endpoints: a `http://` or `file://` redirect
85    // target would send the header in clear or read local files.
86    if !url.starts_with("https://") {
87        bail!("refusing a non-https URL: {url}");
88    }
89
90    let mut cmd = Command::new("curl");
91    cmd.arg("--config").arg("-");
92    if let Some(p) = output {
93        cmd.arg("-o").arg(p);
94    }
95    cmd.arg("--").arg(url);
96
97    let mut child = cmd
98        .stdin(Stdio::piped())
99        .stdout(Stdio::piped())
100        .stderr(Stdio::piped())
101        .spawn()
102        .context("failed to run curl — is it installed?")?;
103    child
104        .stdin
105        .take()
106        .context("curl stdin unavailable")?
107        .write_all(cfg.as_bytes())?;
108
109    let out = child.wait_with_output()?;
110    if !out.status.success() {
111        bail!(
112            "curl failed: {}",
113            String::from_utf8_lossy(&out.stderr).trim()
114        );
115    }
116    Ok(out.stdout)
117}
118
119/// Releases for `repo` ("owner/name"), newest first, pre-releases excluded.
120///
121/// Pages until `limit` qualifying releases are found or the history runs out —
122/// a first page consisting mostly of pre-releases would otherwise silently
123/// return far fewer than asked for.
124///
125/// Uses the GitHub API directly rather than mise-versions: that index only
126/// covers mise's curated registry, and backfill has to work for any project.
127pub fn list_releases(repo: &str, limit: usize) -> Result<Vec<Release>> {
128    let mut out: Vec<Release> = Vec::new();
129
130    for page in 1..=MAX_PAGES {
131        let url =
132            format!("https://api.github.com/repos/{repo}/releases?per_page={PER_PAGE}&page={page}");
133        let body = curl(&url, None, true)?;
134        let batch: Vec<Release> =
135            serde_json::from_slice(&body).context("could not parse the GitHub releases API")?;
136        let exhausted = batch.len() < PER_PAGE;
137
138        out.extend(
139            batch
140                .into_iter()
141                .filter(|r| !r.prerelease && !r.draft && !r.assets.is_empty()),
142        );
143
144        if out.len() >= limit {
145            break;
146        }
147        if exhausted {
148            return Ok(finish(out, limit));
149        }
150        if page == MAX_PAGES {
151            eprintln!(
152                "warning: stopped after {MAX_PAGES} pages with {} of {limit} releases; \
153                 older releases exist but were not fetched",
154                out.len()
155            );
156        }
157    }
158
159    Ok(finish(out, limit))
160}
161
162fn finish(mut v: Vec<Release>, limit: usize) -> Vec<Release> {
163    v.truncate(limit);
164    v
165}
166
167/// Whether the picker's tables actually cover this host.
168///
169/// Kept in step with `asset_picker`'s own OS and arch tables; anything outside
170/// them leaves its token list empty, which disables the corresponding filter
171/// rather than rejecting.
172fn host_is_recognised() -> bool {
173    matches!(std::env::consts::OS, "linux" | "macos" | "windows")
174        && matches!(std::env::consts::ARCH, "x86_64" | "aarch64")
175}
176
177/// The libc to select assets for.
178///
179/// Passing `None` makes the picker assume gnu on Linux, which is right for the
180/// common case and wrong on Alpine, where a gnu binary simply will not start.
181/// A musl-built `tak` is a good proxy for a musl host, and it is the only
182/// signal available without shelling out.
183///
184/// This matters beyond whether the binary runs: musl and glibc builds have
185/// different allocators and different startup costs, so picking the wrong one
186/// measures something the project's users never execute.
187fn host_libc() -> Option<String> {
188    cfg!(target_env = "musl").then(|| "musl".to_string())
189}
190
191/// Can this asset actually serve as a benchmark subject?
192///
193/// The picker answers "which asset fits this platform", which is not the same
194/// question. It will happily choose a source tarball when that is the only
195/// candidate, or a `.7z` this code cannot unpack — and an unusable pick means a
196/// skipped release rather than a fallback to the next-best asset. Filtering
197/// first lets the picker choose the best of what remains.
198fn is_usable_subject(name: &str) -> bool {
199    let n = name.to_lowercase();
200
201    // A .vsix is a zip, so `Format` classifies it as openable, but it is a VS
202    // Code extension package — never a CLI binary. Admitting it wastes a
203    // download and then skips the release with a confusing "no `tool` inside".
204    if n.ends_with(".vsix") {
205        return false;
206    }
207
208    // Checksums and signatures describe a release rather than being one. The
209    // picker scores them positively — verified: given only
210    // `tool-x86_64-unknown-linux-gnu.tar.gz.sha256` it returns exactly that —
211    // because mise consumes sidecars deliberately elsewhere. Here they are
212    // never a subject.
213    const SIDECAR: [&str; 9] = [
214        ".sha256",
215        ".sha512",
216        ".sha1",
217        ".md5",
218        ".asc",
219        ".sig",
220        ".pem",
221        ".sbom",
222        ".intoto.jsonl",
223    ];
224    if SIDECAR.iter().any(|e| n.ends_with(e)) {
225        return false;
226    }
227
228    // Source drops contain no executable. Whole-word so `resource-cli` survives.
229    let stem = n.rsplit('/').next().unwrap_or(&n);
230    if ["source", "sources", "src"].iter().any(|t| {
231        stem.split(|c: char| !c.is_ascii_alphanumeric())
232            .any(|w| w == *t)
233    }) {
234        return false;
235    }
236
237    // Only formats `fetch_binary` can actually open. Both sides ask `Format`
238    // rather than matching suffixes independently, so a name like `.vsix` —
239    // which is a zip — cannot pass the filter and then be rejected at unpack.
240    match Format::from_file_name(&n) {
241        // `Format::Raw` is a catch-all for "no recognised archive suffix",
242        // which also covers `tool-linux-x86_64.json`, `.yaml`, `.run` and
243        // anything else a project ships alongside its binaries. Those score on
244        // their platform tokens, and marking one executable and running it
245        // benchmarks the wrong program. A real bare binary has no extension at
246        // all, or `.exe`.
247        Format::Raw => {
248            let base = n.rsplit('/').next().unwrap_or(&n);
249            base.ends_with(".exe") || !has_file_extension(base)
250        }
251        // `tar` handles gz/xz/bz2/zst everywhere, but brotli and lz4 depend on
252        // the host build. Admitting one only to fail at extraction turns a
253        // usable release into a skipped one; excluding them lets the picker
254        // choose a different asset instead.
255        Format::Tar => !TAR_NEEDS_RARE_CODEC.iter().any(|e| n.ends_with(e)),
256        Format::Zip => true,
257        _ => false,
258    }
259}
260
261/// Does this filename end in something that looks like a file extension?
262///
263/// "Contains a dot" is not the same question. A raw unix binary is routinely
264/// published as `tool-v1.2.3-linux-x86_64`, and treating the version's dots as
265/// an extension rejects a perfectly good subject. An extension is short, purely
266/// alphanumeric, and not just digits — `json` and `yaml` qualify, the `3` at
267/// the end of a version does not.
268fn has_file_extension(base: &str) -> bool {
269    match base.rsplit_once('.') {
270        None => false,
271        Some((_, ext)) => {
272            !ext.is_empty()
273                && ext.len() <= 6
274                && ext.chars().all(|c| c.is_ascii_alphanumeric())
275                && !ext.chars().all(|c| c.is_ascii_digit())
276        }
277    }
278}
279
280/// Tar compressions that `tar` frequently cannot decompress unaided.
281const TAR_NEEDS_RARE_CODEC: [&str; 4] = [".tar.br", ".tbr", ".tar.lz4", ".tlz4"];
282
283pub fn pick_asset(assets: &[Asset]) -> Option<&Asset> {
284    // The picker's platform tables cover the mainstream targets and skip the
285    // OS or arch filter entirely when it does not recognise one — which on
286    // FreeBSD or riscv64 would let a linux-x86_64 tarball match a machine that
287    // cannot run it. Refusing to guess is the right answer for a tool whose
288    // whole purpose is trustworthy numbers.
289    if !host_is_recognised() {
290        return None;
291    }
292
293    let usable: Vec<String> = assets
294        .iter()
295        .map(|a| a.name.clone())
296        .filter(|n| is_usable_subject(n))
297        .collect();
298
299    // If any candidate states a platform, the ones that do not are not
300    // trustworthy. Verified against the picker: a release shipping
301    // `tool-x86_64-unknown-linux-gnu.tar.gz` alongside `tool.tar.gz` hands the
302    // latter to a macOS host, because the linux asset is filtered out and the
303    // unlabelled one has nothing to filter on. In a release that publishes
304    // per-platform builds, an unlabelled archive is some other artefact — not a
305    // universal binary — so measuring it is measuring the wrong thing.
306    //
307    // A genuinely universal release, where nothing declares a platform, is
308    // untouched by this.
309    let declares_platform = |n: &String| detect_platform_from_url(n).is_some();
310    let names: Vec<String> = if usable.iter().any(declares_platform) {
311        usable
312            .into_iter()
313            .filter(|n| declares_platform(n))
314            .collect()
315    } else {
316        usable
317    };
318    let picked = AssetPicker::with_libc(
319        std::env::consts::OS.to_string(),
320        std::env::consts::ARCH.to_string(),
321        host_libc(),
322    )
323    // A macOS `.app` bundle is not something we can invoke as a subject.
324    .with_no_app(true)
325    .pick_best_asset(&names)?;
326
327    assets.iter().find(|a| a.name == picked)
328}
329
330fn run(cmd: &mut Command, what: &str) -> Result<()> {
331    let out = cmd
332        .output()
333        .with_context(|| format!("failed to run {what}"))?;
334    if !out.status.success() {
335        bail!(
336            "{what} failed: {}",
337            String::from_utf8_lossy(&out.stderr).trim()
338        );
339    }
340    Ok(())
341}
342
343/// Download `asset` into `dir`, unpack it, and return the path to `bin_name`.
344///
345/// Handles tarballs, zips and bare executables — the three shapes essentially
346/// every CLI ships. The download is authenticated for the same reason the
347/// listing is: a private repository's assets are not publicly readable, and
348/// failing here after listing succeeded would skip every release.
349pub fn fetch_binary(asset: &Asset, bin_name: &str, dir: &Path) -> Result<PathBuf> {
350    // Start clean. Reusing a populated directory risks `find_binary` picking up
351    // an executable left by an earlier release and attributing its measurement
352    // to the wrong tag.
353    std::fs::remove_dir_all(dir).ok();
354    std::fs::create_dir_all(dir)?;
355    // Asset names come from the API and are not trusted: `../../x` would escape
356    // the per-release directory and write wherever it liked.
357    let archive = dir.join(safe_component(&asset.name)?);
358
359    curl(&asset.url, Some(&archive), true)?;
360
361    // Same classifier the candidate filter used, so the two can never disagree.
362    // Matching suffixes independently in each place is what let `.vsix` pass the
363    // filter as a zip and then be rejected here as unknown.
364    match Format::from_file_name(&asset.name) {
365        // `tar -xf` sniffs the compression, so gz/xz/bz2/zst all work here.
366        Format::Tar => run(
367            Command::new("tar").args([
368                "-xf",
369                &archive.to_string_lossy(),
370                "-C",
371                &dir.to_string_lossy(),
372            ]),
373            "tar",
374        )?,
375        Format::Zip => run(
376            Command::new("unzip").args([
377                "-oq",
378                &archive.to_string_lossy(),
379                "-d",
380                &dir.to_string_lossy(),
381            ]),
382            "unzip",
383        )?,
384        // The download is the artefact.
385        Format::Raw => {
386            make_executable(&archive)?;
387            return Ok(archive);
388        }
389        // Unreachable via `pick_asset`, which filters these out, but a caller
390        // could hand one over directly. Skipping loudly beats executing a
391        // tarball as if it were a program, which is what the old suffix chain
392        // did for anything it did not recognise.
393        other => bail!("cannot unpack {} ({other:?})", asset.name),
394    }
395
396    let found = find_binary(dir, bin_name)
397        .with_context(|| format!("no `{bin_name}` inside {}", asset.name))?;
398    make_executable(&found)?;
399    Ok(found)
400}
401
402/// Reduce an untrusted name to a single safe path component.
403///
404/// `Path::join` with a value containing `..` or separators escapes the intended
405/// directory, and both asset names and tags come from the GitHub API.
406fn safe_component(name: &str) -> Result<String> {
407    let base = Path::new(name)
408        .file_name()
409        .and_then(|s| s.to_str())
410        .filter(|s| !s.is_empty() && *s != "." && *s != "..")
411        .with_context(|| format!("unusable name from the API: {name:?}"))?;
412    Ok(base.to_string())
413}
414
415/// A filesystem-safe, collision-free directory name for a release.
416///
417/// Sanitising alone is not enough: tags may contain `/` (`release/1.0`), and
418/// mapping both `v1/0` and `v1_0` to `v1_0` would let two releases share a
419/// directory. The index keeps them distinct.
420pub fn release_dir_name(index: usize, tag: &str) -> String {
421    format!("{index:04}-{}", safe_dir_name(tag))
422}
423
424/// A filesystem-safe directory name for a release tag.
425///
426/// Tags may contain `/` (`release/1.0`) and are otherwise arbitrary, so anything
427/// outside a conservative set becomes `_`.
428fn safe_dir_name(tag: &str) -> String {
429    let s: String = tag
430        .chars()
431        .map(|c| {
432            if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') {
433                c
434            } else {
435                '_'
436            }
437        })
438        .collect();
439    let trimmed = s.trim_matches('.');
440    if trimmed.is_empty() {
441        "release".to_string()
442    } else {
443        trimmed.to_string()
444    }
445}
446
447fn make_executable(p: &Path) -> Result<()> {
448    #[cfg(unix)]
449    {
450        use std::os::unix::fs::PermissionsExt;
451        let mut perms = std::fs::metadata(p)?.permissions();
452        perms.set_mode(0o755);
453        std::fs::set_permissions(p, perms)?;
454    }
455    #[cfg(not(unix))]
456    let _ = p;
457    Ok(())
458}
459
460/// Names to accept for the executable.
461///
462/// Windows archives ship `tool.exe`, while `--bin` defaults to the repository
463/// name without a suffix, so an exact-match-only search skips every Windows
464/// release.
465fn binary_candidates(name: &str) -> Vec<String> {
466    let mut v = vec![name.to_string()];
467    if cfg!(windows) && !name.ends_with(".exe") {
468        v.push(format!("{name}.exe"));
469    }
470    v
471}
472
473/// Depth-limited search for the executable. Release archives nest one or two
474/// levels at most; a full walk risks wandering into a vendored tree.
475fn find_binary(dir: &Path, name: &str) -> Option<PathBuf> {
476    fn walk(dir: &Path, names: &[String], depth: u32) -> Option<PathBuf> {
477        if depth > 3 {
478            return None;
479        }
480        let entries = std::fs::read_dir(dir).ok()?;
481        let mut dirs = Vec::new();
482        for e in entries.flatten() {
483            let p = e.path();
484            if p.is_dir() {
485                dirs.push(p);
486            } else if p
487                .file_name()
488                .and_then(|s| s.to_str())
489                .is_some_and(|f| names.iter().any(|n| n == f))
490            {
491                return Some(p);
492            }
493        }
494        dirs.into_iter().find_map(|d| walk(&d, names, depth + 1))
495    }
496    walk(dir, &binary_candidates(name), 0)
497}
498
499/// Whether the current directory is inside a git work tree.
500///
501/// Distinguishes "not in a repository" from "tag not fetched", which otherwise
502/// both surface as a missing tag and send people looking in the wrong place.
503pub fn in_git_repo() -> bool {
504    Command::new("git")
505        .args(["rev-parse", "--is-inside-work-tree"])
506        .stdout(Stdio::null())
507        .stderr(Stdio::null())
508        .status()
509        .map(|s| s.success())
510        .unwrap_or(false)
511}
512
513/// Resolve a release tag to the commit it points at, if the tag is available
514/// locally. Returns `None` rather than failing — a shallow clone legitimately
515/// has no tags, and the caller can still report that precisely.
516pub fn tag_commit(tag: &str) -> Option<String> {
517    let out = Command::new("git")
518        .args(["rev-parse", &format!("{tag}^{{commit}}")])
519        .output()
520        .ok()?;
521    out.status
522        .success()
523        .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
524}
525
526/// Strip a leading `v` for display. Deliberately does no other normalisation —
527/// tool version strings are frequently not semver and must stay opaque.
528pub fn version_of(tag: &str) -> &str {
529    tag.strip_prefix('v').unwrap_or(tag)
530}
531
532/// Lines of a failed build's output to show. Enough for a compiler's error
533/// and the command that failed; the rest is progress noise.
534const BUILD_TAIL: usize = 20;
535
536/// Bytes read back from the end of a failed build's log to find its last
537/// lines. A bound, so a build that printed gigabytes costs no more to report
538/// than one that printed a page.
539const BUILD_TAIL_BYTES: u64 = 64 * 1024;
540
541/// Run `[build]`, anchored in a commit's checkout, and say how long it took.
542///
543/// Output goes to `log` rather than the terminal: twenty builds' worth of
544/// compiler progress buries the lines saying what was recorded, and when a
545/// build fails the error is at the end, which is what the failure shows. A
546/// file rather than a pipe held in memory, because a verbose build across a
547/// long backfill can print far more than tak should hold.
548///
549/// On Unix the build leads its own process group, registered with
550/// [`crate::worktree::build_started`] so an interrupt can stop all of it.
551///
552/// The environment is tak's own plus `[build].env`, without `env_deny`
553/// applied. That setting keeps a token from changing what a *measured*
554/// command does; the build is not measured, and one fetching a private
555/// dependency may need exactly the variable it removes.
556pub fn run_build(build: &crate::config::Build, log: &Path) -> Result<std::time::Duration> {
557    let started = std::time::Instant::now();
558    let (program, args) = build.cmd.split_first().context("empty build command")?;
559    let out = std::fs::File::create(log)
560        .with_context(|| format!("could not create {}", log.display()))?;
561    let mut cmd = Command::new(program);
562    cmd.args(args)
563        .envs(&build.env)
564        .stdin(Stdio::null())
565        .stdout(out.try_clone()?)
566        .stderr(out);
567    if let Some(dir) = &build.dir {
568        cmd.current_dir(dir);
569    }
570    #[cfg(unix)]
571    std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
572    let mut child = cmd.spawn().with_context(|| match &build.dir {
573        Some(d) if !d.is_dir() => format!("{} does not exist at this commit", d.display()),
574        _ => format!("could not run {program}"),
575    })?;
576    #[cfg(unix)]
577    crate::worktree::build_started(child.id());
578    let status = child.wait();
579    #[cfg(unix)]
580    crate::worktree::build_finished();
581    let status = status.context("could not wait for the build")?;
582    if !status.success() {
583        bail!("build failed ({status})\n{}", tail(log)?);
584    }
585    Ok(started.elapsed())
586}
587
588/// The last [`BUILD_TAIL`] lines of `log`, reading at most
589/// [`BUILD_TAIL_BYTES`] from its end.
590fn tail(log: &Path) -> Result<String> {
591    use std::io::{Read, Seek, SeekFrom};
592    let mut f = std::fs::File::open(log)?;
593    let len = f.metadata()?.len();
594    let start = len.saturating_sub(BUILD_TAIL_BYTES);
595    f.seek(SeekFrom::Start(start))?;
596    let mut buf = Vec::new();
597    f.read_to_end(&mut buf)?;
598    let text = String::from_utf8_lossy(&buf);
599    let mut lines: Vec<&str> = text.lines().collect();
600    // Starting mid-file almost always lands mid-line.
601    if start > 0 && !lines.is_empty() {
602        lines.remove(0);
603    }
604    Ok(lines[lines.len().saturating_sub(BUILD_TAIL)..].join("\n"))
605}
606
607#[cfg(test)]
608mod tests {
609    use super::*;
610
611    #[test]
612    fn pick_asset_chooses_the_best_candidate() {
613        let assets: Vec<Asset> = [
614            "tool-x86_64-apple-darwin.tar.gz",
615            "tool-x86_64-unknown-linux-gnu.tar.gz",
616            "tool-x86_64-unknown-linux-musl.tar.gz",
617            "tool-x86_64-unknown-linux-musl.tar.gz.sha256",
618        ]
619        .iter()
620        .map(|n| Asset {
621            name: n.to_string(),
622            url: format!("https://example.invalid/{n}"),
623        })
624        .collect();
625
626        // Only meaningful on the platform this asserts against.
627        if std::env::consts::OS == "linux" && std::env::consts::ARCH == "x86_64" {
628            let got = pick_asset(&assets).expect("something should match");
629            // gnu, not musl, on a glibc host. The two builds differ in
630            // allocator and startup cost, so the one users actually run is the
631            // one worth measuring — and it is never the darwin asset or the
632            // checksum file.
633            let want = if cfg!(target_env = "musl") {
634                "tool-x86_64-unknown-linux-musl.tar.gz"
635            } else {
636                "tool-x86_64-unknown-linux-gnu.tar.gz"
637            };
638            assert_eq!(got.name, want);
639        }
640    }
641
642    #[test]
643    fn version_strips_only_the_v_prefix() {
644        assert_eq!(version_of("v1.2.3"), "1.2.3");
645        assert_eq!(version_of("2024.01.15"), "2024.01.15");
646        // Non-semver tags must survive untouched.
647        assert_eq!(version_of("nightly"), "nightly");
648        assert_eq!(version_of("lts-iron"), "lts-iron");
649    }
650
651    #[test]
652    fn windows_archives_may_carry_an_exe_suffix() {
653        let c = binary_candidates("mycli");
654        assert!(c.contains(&"mycli".to_string()));
655        if cfg!(windows) {
656            assert!(c.contains(&"mycli.exe".to_string()));
657        }
658        // An explicit .exe must not become mycli.exe.exe.
659        assert_eq!(binary_candidates("mycli.exe").len(), 1);
660    }
661
662    #[test]
663    fn source_archives_are_not_benchmark_subjects() {
664        // The picker selects these when they are the only candidate; they
665        // contain no executable.
666        assert!(!is_usable_subject("tool-1.0-source.tar.gz"));
667        assert!(!is_usable_subject("tool-src.tar.gz"));
668        assert!(!is_usable_subject("sources.zip"));
669        // Whole-word, so a tool whose name merely contains "src" survives.
670        assert!(is_usable_subject("resource-cli-linux-x86_64.tar.gz"));
671        assert!(is_usable_subject("srcery-linux-amd64.tar.gz"));
672    }
673
674    #[test]
675    fn sidecars_are_never_subjects() {
676        // Verified against the real picker: given only the .sha256 it returns
677        // exactly that, so the filter has to catch them.
678        for n in [
679            "tool-x86_64-unknown-linux-gnu.tar.gz.sha256",
680            "tool-x86_64-unknown-linux-gnu.tar.gz.asc",
681            "tool.sig",
682            "tool.intoto.jsonl",
683        ] {
684            assert!(!is_usable_subject(n), "{n} should be rejected");
685        }
686    }
687
688    /// A .vsix unpacks fine — it is a zip — but never contains a CLI binary,
689    /// so admitting it costs a download and a confusing skip.
690    #[test]
691    fn vsix_is_openable_but_never_a_subject() {
692        assert_eq!(Format::from_file_name("tool.vsix"), Format::Zip);
693        assert!(!is_usable_subject("tool-linux-x86_64.vsix"));
694    }
695
696    /// `Format::Raw` means "no recognised archive suffix", which is not the
697    /// same as "an executable".
698    #[test]
699    fn platform_tagged_metadata_is_not_a_subject() {
700        for n in [
701            "tool-linux-x86_64.json",
702            "tool-linux-x86_64.yaml",
703            "tool-linux-x86_64.run",
704            "tool-linux-x86_64.txt",
705        ] {
706            assert!(!is_usable_subject(n), "{n} should be rejected");
707        }
708        // A genuine bare binary still qualifies.
709        assert!(is_usable_subject("tool-linux-x86_64"));
710        assert!(is_usable_subject("tool.exe"));
711    }
712
713    /// A version's dots are not a file extension, and rejecting on "contains a
714    /// dot" threw away raw binaries that projects really do publish.
715    #[test]
716    fn a_versioned_bare_binary_is_still_a_subject() {
717        assert!(is_usable_subject("tool-v1.2.3-linux-x86_64"));
718        assert!(is_usable_subject("tool-1.2.3"));
719        assert!(is_usable_subject("tool-linux-amd64-2024.01.15"));
720    }
721
722    #[test]
723    fn extension_detection_distinguishes_versions_from_suffixes() {
724        assert!(has_file_extension("tool.json"));
725        assert!(has_file_extension("tool.yaml"));
726        assert!(has_file_extension("tool.exe"));
727        // Trailing version components, not extensions.
728        assert!(!has_file_extension("tool-1.2.3"));
729        assert!(!has_file_extension("tool-v1.2.3-linux-x86_64"));
730        assert!(!has_file_extension("tool"));
731    }
732
733    #[test]
734    fn tar_codecs_the_host_may_lack_are_skipped() {
735        assert!(is_usable_subject("tool-linux-x86_64.tar.gz"));
736        assert!(is_usable_subject("tool-linux-x86_64.tar.zst"));
737        // Better to let the picker choose another asset than to fail at
738        // extraction and skip the release entirely.
739        assert!(!is_usable_subject("tool-linux-x86_64.tar.br"));
740        assert!(!is_usable_subject("tool-linux-x86_64.tar.lz4"));
741    }
742
743    #[test]
744    fn only_openable_formats_are_subjects() {
745        assert!(is_usable_subject("tool-linux-x86_64.tar.gz"));
746        assert!(is_usable_subject("tool-linux-x86_64.zip"));
747        assert!(is_usable_subject("tool"));
748        assert!(is_usable_subject("tool.exe"));
749        // fetch_binary cannot open these, and picking one skips the release.
750        assert!(!is_usable_subject("tool-linux-x86_64.7z"));
751        assert!(!is_usable_subject("tool-linux-x86_64.gz"));
752        assert!(!is_usable_subject("tool.rar"));
753    }
754
755    #[test]
756    fn a_platform_asset_beats_a_source_drop() {
757        let assets: Vec<Asset> = [
758            "tool-1.0-source.tar.gz",
759            "tool-x86_64-unknown-linux-gnu.tar.gz",
760        ]
761        .iter()
762        .map(|n| Asset {
763            name: n.to_string(),
764            url: format!("https://example.invalid/{n}"),
765        })
766        .collect();
767        if std::env::consts::OS == "linux" && std::env::consts::ARCH == "x86_64" {
768            assert_eq!(
769                pick_asset(&assets).map(|a| a.name.as_str()),
770                Some("tool-x86_64-unknown-linux-gnu.tar.gz")
771            );
772        }
773    }
774
775    /// The picker disables a filter it cannot populate, so an unrecognised host
776    /// must be refused before it ever gets there.
777    #[test]
778    fn unrecognised_hosts_are_refused() {
779        let recognised = matches!(std::env::consts::OS, "linux" | "macos" | "windows")
780            && matches!(std::env::consts::ARCH, "x86_64" | "aarch64");
781        assert_eq!(host_is_recognised(), recognised);
782
783        if !host_is_recognised() {
784            let assets = vec![Asset {
785                name: "tool-x86_64-unknown-linux-gnu.tar.gz".to_string(),
786                url: "https://example.invalid/x".to_string(),
787            }];
788            assert!(pick_asset(&assets).is_none());
789        }
790    }
791
792    /// The case that motivated the platform-evidence rule: a release with
793    /// per-platform builds, none of them ours, plus an unlabelled archive.
794    #[test]
795    fn an_unlabelled_archive_never_substitutes_for_a_platform_build() {
796        let assets: Vec<Asset> = ["tool-x86_64-unknown-linux-gnu.tar.gz", "tool.tar.gz"]
797            .iter()
798            .map(|n| Asset {
799                name: n.to_string(),
800                url: format!("https://example.invalid/{n}"),
801            })
802            .collect();
803
804        // On linux/x86_64 the labelled asset is the right answer.
805        if std::env::consts::OS == "linux" && std::env::consts::ARCH == "x86_64" {
806            assert_eq!(
807                pick_asset(&assets).map(|a| a.name.as_str()),
808                Some("tool-x86_64-unknown-linux-gnu.tar.gz")
809            );
810        }
811        // On macOS the linux asset does not apply, and falling back to
812        // `tool.tar.gz` would benchmark whatever that happens to be.
813        if std::env::consts::OS == "macos" {
814            assert!(pick_asset(&assets).is_none());
815        }
816    }
817
818    /// A release where nothing declares a platform is still usable — that is a
819    /// real and common shape, and rejecting it would exclude those projects.
820    #[test]
821    fn a_wholly_unlabelled_release_is_still_usable() {
822        let assets = vec![Asset {
823            name: "tool.tar.gz".to_string(),
824            url: "https://example.invalid/tool.tar.gz".to_string(),
825        }];
826        assert!(pick_asset(&assets).is_some());
827    }
828
829    #[test]
830    fn a_release_of_only_source_yields_nothing() {
831        let assets = vec![Asset {
832            name: "tool-1.0-source.tar.gz".to_string(),
833            url: "https://example.invalid/x".to_string(),
834        }];
835        assert!(pick_asset(&assets).is_none());
836    }
837
838    #[test]
839    fn release_dirs_never_collide() {
840        // Sanitising alone maps both of these to `v1_0`.
841        assert_ne!(
842            release_dir_name(0, "v1/0"),
843            release_dir_name(1, "v1_0"),
844            "distinct releases must not share a work directory"
845        );
846        assert_eq!(release_dir_name(7, "v1.2.3"), "0007-v1.2.3");
847        // Path separators must not survive into the name.
848        assert!(!release_dir_name(0, "release/1.0").contains('/'));
849        // A tag of only punctuation still yields something usable.
850        assert!(!release_dir_name(0, "...").is_empty());
851    }
852
853    /// A failed build shows its last lines, read from the end of the log,
854    /// however much it printed before them.
855    #[test]
856    fn a_long_build_log_is_read_from_its_end() {
857        let dir = tempfile::tempdir().unwrap();
858        let log = dir.path().join("build.log");
859        let mut text: String = (0..100_000).map(|i| format!("progress {i}\n")).collect();
860        text.push_str("error: it broke\n");
861        std::fs::write(&log, &text).unwrap();
862        let got = tail(&log).unwrap();
863        let lines: Vec<&str> = got.lines().collect();
864        assert_eq!(lines.len(), BUILD_TAIL);
865        assert_eq!(lines.last(), Some(&"error: it broke"));
866        assert_eq!(lines[0], "progress 99981", "whole lines only");
867
868        std::fs::write(&log, "one\ntwo\n").unwrap();
869        assert_eq!(tail(&log).unwrap(), "one\ntwo");
870    }
871
872    #[test]
873    fn finds_a_nested_binary() {
874        let dir = std::env::temp_dir().join(format!("tak-find-{}", std::process::id()));
875        let nested = dir.join("tool-1.0").join("bin");
876        std::fs::create_dir_all(&nested).unwrap();
877        std::fs::write(nested.join("mycli"), b"#!/bin/sh\n").unwrap();
878
879        assert_eq!(find_binary(&dir, "mycli"), Some(nested.join("mycli")));
880        assert_eq!(find_binary(&dir, "absent"), None);
881
882        std::fs::remove_dir_all(&dir).ok();
883    }
884}