1use 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 #[serde(default)]
39 pub draft: bool,
40 #[serde(default)]
41 pub assets: Vec<Asset>,
42}
43
44const PER_PAGE: usize = 100;
46const 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
56fn curl(url: &str, output: Option<&Path>, auth: bool) -> Result<Vec<u8>> {
66 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 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 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
119pub 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
167fn host_is_recognised() -> bool {
173 matches!(std::env::consts::OS, "linux" | "macos" | "windows")
174 && matches!(std::env::consts::ARCH, "x86_64" | "aarch64")
175}
176
177fn host_libc() -> Option<String> {
188 cfg!(target_env = "musl").then(|| "musl".to_string())
189}
190
191fn is_usable_subject(name: &str) -> bool {
199 let n = name.to_lowercase();
200
201 if n.ends_with(".vsix") {
205 return false;
206 }
207
208 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 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 match Format::from_file_name(&n) {
241 Format::Raw => {
248 let base = n.rsplit('/').next().unwrap_or(&n);
249 base.ends_with(".exe") || !has_file_extension(base)
250 }
251 Format::Tar => !TAR_NEEDS_RARE_CODEC.iter().any(|e| n.ends_with(e)),
256 Format::Zip => true,
257 _ => false,
258 }
259}
260
261fn 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
280const TAR_NEEDS_RARE_CODEC: [&str; 4] = [".tar.br", ".tbr", ".tar.lz4", ".tlz4"];
282
283pub fn pick_asset(assets: &[Asset]) -> Option<&Asset> {
284 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 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 .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
343pub fn fetch_binary(asset: &Asset, bin_name: &str, dir: &Path) -> Result<PathBuf> {
350 std::fs::remove_dir_all(dir).ok();
354 std::fs::create_dir_all(dir)?;
355 let archive = dir.join(safe_component(&asset.name)?);
358
359 curl(&asset.url, Some(&archive), true)?;
360
361 match Format::from_file_name(&asset.name) {
365 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 Format::Raw => {
386 make_executable(&archive)?;
387 return Ok(archive);
388 }
389 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
402fn 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
415pub fn release_dir_name(index: usize, tag: &str) -> String {
421 format!("{index:04}-{}", safe_dir_name(tag))
422}
423
424fn 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
460fn 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
473fn 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
499pub 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
513pub 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
526pub fn version_of(tag: &str) -> &str {
529 tag.strip_prefix('v').unwrap_or(tag)
530}
531
532const BUILD_TAIL: usize = 20;
535
536const BUILD_TAIL_BYTES: u64 = 64 * 1024;
540
541pub 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
588fn 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 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 if std::env::consts::OS == "linux" && std::env::consts::ARCH == "x86_64" {
628 let got = pick_asset(&assets).expect("something should match");
629 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 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 assert_eq!(binary_candidates("mycli.exe").len(), 1);
660 }
661
662 #[test]
663 fn source_archives_are_not_benchmark_subjects() {
664 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 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 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 #[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 #[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 assert!(is_usable_subject("tool-linux-x86_64"));
710 assert!(is_usable_subject("tool.exe"));
711 }
712
713 #[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 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 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 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 #[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 #[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 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 if std::env::consts::OS == "macos" {
814 assert!(pick_asset(&assets).is_none());
815 }
816 }
817
818 #[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 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 assert!(!release_dir_name(0, "release/1.0").contains('/'));
849 assert!(!release_dir_name(0, "...").is_empty());
851 }
852
853 #[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}