use crate::context::ExecContext;
use crate::frozen::{
DisabledRecord, DisabledSource, DisabledWorkflow, Filters, FrozenConfig, FrozenPlan, PlanParts,
SourceRef,
};
use crate::source::{self, SourceInfo, SourceKind, SourceManifest};
use crate::{cache, config, exec, filter, git, plan, reclaim, report, setup, workflow};
use anyhow::{bail, Context, Result};
use std::path::{Path, PathBuf};
pub trait Observer {
fn notice(&mut self, _msg: &str) {}
fn executing(&mut self) {}
}
pub struct Quiet;
impl Observer for Quiet {}
#[derive(Clone, Debug)]
pub struct Target {
pub base: Option<String>,
pub sha: String,
pub all: bool,
pub include_disabled: bool,
pub workflows_dirs: Vec<String>,
pub workflows: Vec<String>,
pub jobs: Vec<String>,
pub dir: PathBuf,
}
#[derive(Clone, Debug)]
pub struct RunOptions {
pub target: Target,
pub parallel: Option<usize>,
pub no_traffic_controller: bool,
pub no_portool: bool,
pub containers: usize,
pub keep: bool,
pub job_timeout: f64,
pub no_cache: bool,
pub no_build_cache: bool,
pub all_os_legs: bool,
pub cache_dir: PathBuf,
pub source: Option<SourceManifest>,
}
pub struct RunReport {
pub result: report::RunResult,
pub repo_root: PathBuf,
pub cancelled: bool,
pub style: report::Style,
pub source: Option<SourceInfo>,
}
pub struct Repo {
pub root: PathBuf,
pub sha: String,
pub base: String,
pub head: Option<String>,
pub changed: Vec<String>,
pub dirty: bool,
pub all: bool,
pub workflow_dirs: Vec<String>,
pub no_cache: Vec<String>,
pub link_node_modules: bool,
pub ignore_env: Vec<String>,
pub default_workflows_dir: String,
pub disabled: DisabledRecord,
}
pub fn resolve(
ctx: &ExecContext,
t: &Target,
obs: &mut dyn Observer,
) -> Result<(Repo, plan::Plan)> {
resolve_with(ctx, t, None, obs)
}
pub fn resolve_with(
ctx: &ExecContext,
t: &Target,
disabled_list: Option<Vec<DisabledWorkflow>>,
obs: &mut dyn Observer,
) -> Result<(Repo, plan::Plan)> {
let root = git::toplevel(ctx, &t.dir)?;
let sha = git::rev(ctx, &root, &t.sha)?;
let base = match &t.base {
Some(b) => b.clone(),
None => git::default_base(ctx, &root)?,
};
let changed = git::changed_files(ctx, &root, &base, &sha)?;
let head = if t.sha == "HEAD" {
git::current_branch(ctx, &root)
} else {
None
};
let config = config::at(ctx, &root, &sha)?;
let mut wfs = Vec::new();
for (file, text) in git::workflows_at(
ctx,
&root,
&sha,
config.workflows_dirs.as_deref(),
&t.workflows_dirs,
)? {
match workflow::parse(&file, &text) {
Ok(w) => wfs.push(w),
Err(e) => obs.notice(&format!("skipping {file}: {e:#}")),
}
}
let ev = filter::Event {
base: git::base_branch_name(ctx, &root, &base),
head: head.clone(),
changed: changed.clone(),
all: t.all,
};
let mut disabled_skips = Vec::new();
let mut record = DisabledRecord::not_checked();
if !t.all && !t.include_disabled {
let (source, mut list) = match disabled_list {
Some(l) => (DisabledSource::Provided, l),
None => match disabled_workflows(ctx, &root) {
Some(l) => (DisabledSource::Github, l),
None => (DisabledSource::Unavailable, vec![]),
},
};
list.sort();
list.dedup();
let disabled = list.clone();
record = DisabledRecord {
source,
workflows: list,
};
wfs.retain(|w| match disabled.iter().find(|d| d.path == w.file) {
Some(DisabledWorkflow { state, .. }) => {
if t.workflows.is_empty()
|| t.workflows
.iter()
.any(|o| w.file.ends_with(o.as_str()) || &w.name == o)
{
disabled_skips.push((
w.file.clone(),
format!("{} on GitHub", state.replace('_', " ")),
));
}
false
}
None => true,
});
}
let mut p = plan::build(wfs, &ev, &t.workflows);
p.skipped.extend(disabled_skips);
if !t.jobs.is_empty() {
keep_jobs(&mut p, &t.jobs);
}
let dirty = git::is_dirty(ctx, &root);
let mut workflow_dirs = config
.workflows_dirs
.clone()
.unwrap_or_else(|| vec![config::DEFAULT_WORKFLOWS_DIR.to_string()]);
workflow_dirs.extend(t.workflows_dirs.iter().map(|d| plan::norm_dir(d)));
Ok((
Repo {
root,
sha,
base,
head,
changed,
dirty,
all: t.all,
workflow_dirs,
default_workflows_dir: config.default_workflows_dir().to_string(),
disabled: record,
no_cache: config.no_cache,
link_node_modules: config.link_node_modules,
ignore_env: config.ignore_env,
},
p,
))
}
fn disabled_workflows(ctx: &ExecContext, root: &std::path::Path) -> Option<Vec<DisabledWorkflow>> {
let slug = git::repo_slug(ctx, root)?;
let gh = ctx.find_tool("gh")?;
let child = ctx
.command(gh)
.args([
"api",
&format!("repos/{slug}/actions/workflows?per_page=100"),
"-q",
r#".workflows[] | select(.state != "active") | "\(.path)\t\(.state)""#,
])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn();
let Ok(mut child) = child else { return None };
let t0 = std::time::Instant::now();
loop {
match child.try_wait() {
Ok(Some(_)) => break,
Ok(None) if t0.elapsed() < std::time::Duration::from_secs(10) => {
std::thread::sleep(std::time::Duration::from_millis(100))
}
_ => {
let _ = child.kill();
return None;
}
}
}
let Ok(out) = child.wait_with_output() else {
return None;
};
if !out.status.success() {
return None;
}
Some(
String::from_utf8_lossy(&out.stdout)
.lines()
.filter_map(|l| {
l.split_once('\t').map(|(p, s)| DisabledWorkflow {
path: p.to_string(),
state: s.to_string(),
})
})
.collect(),
)
}
pub(crate) fn keep_jobs(p: &mut plan::Plan, wanted: &[String]) {
for u in &mut p.units {
let w = &p.selected[u.wf].wf;
let mut keep: Vec<String> = u
.jobs
.iter()
.filter(|j| wanted.contains(j))
.cloned()
.collect();
let mut i = 0;
while i < keep.len() {
if let Some(j) = w.jobs.iter().find(|j| j.id == keep[i]) {
for n in &j.needs {
if !keep.contains(n) {
keep.push(n.clone());
}
}
}
i += 1;
}
u.jobs.retain(|j| keep.contains(j));
}
p.units.retain(|u| !u.jobs.is_empty());
}
fn repo_key(ctx: &ExecContext, root: &std::path::Path) -> String {
use std::hash::{Hash, Hasher};
let common = git::git(
ctx,
root,
&["rev-parse", "--path-format=absolute", "--git-common-dir"],
)
.unwrap_or_else(|_| root.to_string_lossy().into_owned());
let mut h = std::collections::hash_map::DefaultHasher::new();
common.hash(&mut h);
let name = root
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let name: String = name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' {
c
} else {
'_'
}
})
.collect();
format!("{name}-{:08x}", h.finish() as u32)
}
fn status_target(origin_url: Option<&str>, gh_host: Option<&str>) -> Result<String, String> {
let Some(url) = origin_url else {
return Err("no origin remote".into());
};
let Some((host, slug)) = git::remote_host_and_slug(url) else {
return Err("origin is not a remote with a host (a local path?); not posting".into());
};
let allowed = match gh_host.map(str::trim).filter(|h| !h.is_empty()) {
Some(h) => h.to_ascii_lowercase(),
None => "github.com".to_string(),
};
if host == allowed {
Ok(slug)
} else {
Err(format!(
"origin host {host} is not {allowed}; not posting a commit status (set GH_HOST to post to a GitHub Enterprise host)"
))
}
}
fn status_failure(sha: &str, output: &str) -> String {
if output.contains("No commit found") {
format!(
"{} is not on GitHub yet; run `local-ci status` after pushing",
&sha[..7.min(sha.len())]
)
} else {
format!(
"gh api failed: {}",
output.lines().next().unwrap_or("").trim()
)
}
}
pub fn post_status(
ctx: &ExecContext,
root: &std::path::Path,
sha: &str,
state: &str,
description: &str,
) -> Result<()> {
let slug = status_target(
git::origin_url(ctx, root).as_deref(),
ctx.env().get("GH_HOST").map(String::as_str),
)
.map_err(|e| anyhow::anyhow!(e))?;
let gh = ctx.find_tool("gh").context("gh is not installed")?;
let out = ctx
.command(gh)
.args([
"api",
&format!("repos/{slug}/statuses/{sha}"),
"-f",
&format!("state={}", report::github_state(state)),
"-f",
"context=local-ci",
"-f",
&format!("description={description}"),
])
.output()?;
if out.status.success() {
return Ok(());
}
let err =
String::from_utf8_lossy(&out.stderr).to_string() + &String::from_utf8_lossy(&out.stdout);
bail!("{}", status_failure(sha, &err))
}
pub fn claim_run_dir(runs: &std::path::Path, stamp: u64, sha7: &str) -> Result<PathBuf> {
std::fs::create_dir_all(runs)?;
for n in 0u32.. {
let name = if n == 0 {
format!("{stamp}-{sha7}")
} else {
format!("{stamp}-{sha7}-{n}")
};
let dir = runs.join(name);
match std::fs::create_dir(&dir) {
Ok(()) => return Ok(dir),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(e.into()),
}
}
unreachable!("a counter that does not end")
}
const UNFINISHED_SECS: u64 = 24 * 3600;
const UNRECORDED_SECS: u64 = 7 * 24 * 3600;
fn prune_runs(all: &Path, mine: &Path, root: &Path, now: std::time::SystemTime) {
use std::os::unix::ffi::{OsStrExt, OsStringExt};
let _ = std::fs::write(mine.join("root"), root.as_os_str().as_bytes());
let age = |p: &Path| {
std::fs::symlink_metadata(p)
.and_then(|m| m.modified())
.ok()
.and_then(|t| now.duration_since(t).ok())
.map_or(0, |d| d.as_secs())
};
for e in std::fs::read_dir(all).into_iter().flatten().flatten() {
if !e.file_type().is_ok_and(|t| t.is_dir()) {
continue;
}
let dir = e.path();
let gone = match std::fs::read(dir.join("root")) {
Ok(r) => {
std::fs::symlink_metadata(PathBuf::from(std::ffi::OsString::from_vec(r))).is_err()
}
Err(_) => dir != mine && age(&dir.join("last")).max(age(&dir)) > UNRECORDED_SECS,
};
if gone {
let _ = std::fs::remove_dir_all(&dir);
continue;
}
keep_last_run(&dir, |p| age(p) > UNFINISHED_SECS);
}
}
fn keep_last_run(dir: &Path, stale: impl Fn(&Path) -> bool) {
let runs: Vec<PathBuf> = std::fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
.map(|e| e.path())
.collect();
let finished = |p: &Path| p.join("result.json").is_file();
let keep = std::fs::read_to_string(dir.join("last"))
.ok()
.and_then(|l| Path::new(l.trim()).file_name().map(|n| n.to_owned()))
.or_else(|| {
runs.iter()
.filter(|p| finished(p))
.max()
.and_then(|p| p.file_name().map(|n| n.to_owned()))
});
for p in &runs {
if p.file_name() == keep.as_deref() {
continue;
}
if finished(p) || stale(p) {
let _ = std::fs::remove_dir_all(p);
}
}
}
pub fn build_frozen_plan(
ctx: &ExecContext,
t: &Target,
obs: &mut dyn Observer,
) -> Result<FrozenPlan> {
build_frozen_plan_with(ctx, t, None, obs)
}
pub fn build_frozen_plan_with(
ctx: &ExecContext,
t: &Target,
disabled: Option<Vec<DisabledWorkflow>>,
obs: &mut dyn Observer,
) -> Result<FrozenPlan> {
let (repo, p) = resolve_with(ctx, t, disabled, obs)?;
freeze(ctx, &repo, p, t)
}
pub fn freeze(ctx: &ExecContext, repo: &Repo, p: plan::Plan, t: &Target) -> Result<FrozenPlan> {
FrozenPlan::new(PlanParts {
repository: git::repo_slug(ctx, &repo.root),
source: SourceRef {
source_id: format!("commit:{}", repo.sha),
execution_commit: Some(repo.sha.clone()),
base: Some(repo.base.clone()),
pinned: None,
},
branch: repo.head.clone(),
changed_files: repo.changed.clone(),
config: FrozenConfig {
workflow_dirs: repo.workflow_dirs.clone(),
default_workflows_dir: repo.default_workflows_dir.clone(),
no_cache: repo.no_cache.clone(),
link_node_modules: repo.link_node_modules,
ignore_env: repo.ignore_env.clone(),
},
filters: Filters {
all: t.all,
include_disabled: t.include_disabled,
workflows_dirs: t.workflows_dirs.iter().map(|d| plan::norm_dir(d)).collect(),
workflows: t.workflows.clone(),
jobs: t.jobs.clone(),
},
disabled: repo.disabled.clone(),
plan: p,
})
}
pub fn execute_plan(
ctx: &ExecContext,
fp: &FrozenPlan,
ws: &exec::Workspace,
opts: exec::Opts,
) -> Result<report::RunResult> {
fp.require_git_source()?;
let area = ws.run_dir.join("artifacts");
if std::fs::read_dir(&area).is_ok_and(|mut d| d.next().is_some()) {
bail!(
"{} already has artifacts: a run needs a directory of its own",
ws.run_dir.display()
);
}
run_plan(ctx, fp, ws, opts, None, None)
}
fn run_plan(
ctx: &ExecContext,
fp: &FrozenPlan,
ws: &exec::Workspace,
opts: exec::Opts,
cpu: Option<crate::cpu::Share>,
build_cache: Option<crate::build_cache::Settings>,
) -> Result<report::RunResult> {
let t0 = std::time::Instant::now();
let nothing = fp.units.is_empty();
if nothing {
return report::assemble(
fp,
ws.run_dir.clone(),
vec![],
vec![],
t0.elapsed().as_secs_f64(),
);
}
let keep = opts.keep;
let mut runner = exec::Runner::new(ctx, fp, ws, opts)?;
runner.job_threads = cpu.map(|c| c.threads_per_job);
runner.build_cache = build_cache;
let result = (|| -> Result<_> {
runner.prepare_tools()?;
let recipes = runner.task_recipes()?;
let run_id = ws
.run_dir
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let tctx = setup::TemplateContext::local(fp, &run_id);
let all = setup::SetupRecipe::union(&recipes.iter().map(|(_, r)| r).collect::<Vec<_>>());
let done = runner.run_recipe(&all, all.template_key(&tctx).digest())?;
let ok = done.ok();
let mut by_key: std::collections::HashMap<String, setup::PreparedReceipt> =
Default::default();
let mut receipts = std::collections::HashMap::new();
for (task, recipe) in &recipes {
let key = recipe.template_key(&tctx);
let r = by_key
.entry(key.digest().to_string())
.or_insert_with(|| done.receipt.restricted_to(recipe, &key));
receipts.insert(task.clone(), r.clone());
}
runner.set_receipts(receipts, tctx);
let setup = done.steps;
let units = if ok && !ctx.cancel.is_cancelled() {
runner.run_units()?
} else {
vec![]
};
Ok((setup, units))
})();
ctx.cancel.remove_containers(ctx);
if !keep {
runner.release_ports(&ws.root)?;
}
let (setup, units) = result?;
let mut r = report::assemble(
fp,
ws.run_dir.clone(),
setup,
units,
t0.elapsed().as_secs_f64(),
)?;
r.cpu = cpu;
Ok(r)
}
pub fn run(ctx: &ExecContext, a: RunOptions, obs: &mut dyn Observer) -> Result<RunReport> {
let t_start = std::time::Instant::now();
let mut full = build_frozen_plan(ctx, &a.target, obs)?;
if let Some(m) = &a.source {
if m.execution_commit.as_deref() != full.source.execution_commit.as_deref() {
bail!(
"the target is {}, not the execution commit of source {}",
&full
.source
.execution_commit
.as_deref()
.expect("resolved Git commit")[..7],
m.source_id
);
}
full = full.with_source_id(&m.source_id)?;
}
let root = git::toplevel(ctx, &a.target.dir)?;
let cache = a.cache_dir.clone();
if !cache.is_absolute() {
bail!(
"the cache directory `{}` is not an absolute path",
cache.display()
);
}
let all_os_legs = a.all_os_legs
|| ctx
.var("LOCAL_CI_ALL_OS_LEGS")
.is_some_and(crate::build_cache::truthy);
let key = repo_key(ctx, &root);
let runs = cache.join("runs").join(&key);
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)?
.as_secs();
let mut full_plan = full.to_plan();
let store = cache::Store::new(cache.join("results").join(&key));
cache::prune_all(&cache.join("results"), stamp);
let sha = full
.source
.execution_commit
.as_deref()
.expect("resolved Git commit");
let fingerprints: Vec<Option<String>> = if full.units.is_empty() {
vec![]
} else {
match cache::Inputs::read(
ctx,
&root,
sha,
full.source.base.as_deref().expect("resolved Git base"),
full.branch.as_deref(),
&full.config.workflow_dirs,
&full.config.no_cache,
)
.map(|i| i.with_all_os_legs(all_os_legs))
{
Ok(inputs) => full_plan
.units
.iter()
.map(|u| {
let s = &full_plan.selected[u.wf];
inputs.fingerprint(&s.wf, &s.event, u)
})
.collect(),
Err(e) => {
obs.notice(&format!("not reusing results: {e:#}"));
vec![None; full.units.len()]
}
}
};
let run_dir = claim_run_dir(&runs, stamp, &sha[..7])?;
let mut hits: Vec<Option<cache::Hit>> = std::mem::take(&mut full_plan.units)
.iter()
.zip(&fingerprints)
.map(|(u, fp)| {
fp.as_deref()
.filter(|_| !a.no_cache)
.and_then(|f| store.get(f, &full_plan.selected[u.wf].wf.file, stamp))
})
.collect();
let all_units = full.to_plan().units;
let (fp, taken) = loop {
let taken = cache::settle(&hits);
let mut p = full.to_plan();
p.units = all_units
.iter()
.zip(&taken)
.filter(|(_, t)| !**t)
.map(|(u, _)| u.clone())
.collect();
let fp = full.with_plan(p)?;
let _ = std::fs::remove_dir_all(run_dir.join("artifacts"));
if !taken.iter().any(|t| *t) {
break (fp, taken);
}
let mut failed = false;
for (i, t) in taken.iter().enumerate() {
let (Some(h), Some(f)) = (hits[i].as_ref(), fingerprints[i].as_deref()) else {
continue;
};
if *t && store.restore(f, h, &run_dir, &fp.digest).is_err() {
hits[i] = None;
failed = true;
}
}
if !failed {
break (fp, taken);
}
};
let mut reused = Vec::new();
let mut run_idx = Vec::new();
let mut run_fps = Vec::new();
for (i, (fp_, t)) in fingerprints.into_iter().zip(taken).enumerate() {
if t {
if let Some(h) = hits[i].take() {
reused.push(exec::UnitResult {
unit: Some(i),
..h.result
});
}
} else {
run_idx.push(i);
run_fps.push(fp_);
}
}
std::fs::create_dir_all(&run_dir)?;
let source_info = a.source.as_ref().map(SourceInfo::of);
if let Some(info) = &source_info {
exec::write_json(&run_dir.join("source.json"), info)?;
}
std::fs::create_dir_all(cache.join("locks"))?;
if git::is_dirty(ctx, &root) {
obs.notice(&format!(
"uncommitted changes are not tested; testing commit {}",
&sha[..7]
));
}
let owner = reclaim::enter(ctx, &cache)?;
if owner.legacy() > 0 {
obs.notice(&format!(
"{} leftover worktree(s) from an older version; run `local-ci cache prune --legacy` to remove them",
owner.legacy()
));
}
let mut cpu = None;
let (setup, units) = if fp.units.is_empty() {
(vec![], vec![])
} else {
let name = format!("{}-{}", &sha[..7], std::process::id());
let wt = cache.join("wt").join(&name);
let tools = cache.join("wt").join(format!("{name}.tools"));
obs.executing();
match &a.source {
Some(m) => source::add_worktree(
ctx,
&source::ObjectStore::open(cache.join("sources"))?,
&root,
&wt,
m,
)?,
None => git::add_worktree(ctx, &root, &wt, sha)?,
}
let traffic_controller = if a.no_traffic_controller {
None
} else {
ctx.find_tool("task-traffic-controller")
};
let gated = traffic_controller.is_some();
let parallel = a.parallel.unwrap_or(if gated {
fp.units.len().clamp(1, 16)
} else {
crate::cpu::UNGATED_PARALLEL
});
let portool = if a.no_portool {
None
} else {
ctx.find_tool("portool")
};
let isolated = portool.is_some() && wt.join(".portool.toml").is_file();
let peak = crate::cpu::peak(&fp, gated, isolated, parallel, all_os_legs);
if peak > 1 {
let budget = match traffic_controller.as_deref() {
Some(c) => match crate::cpu::controller_budget(ctx, c) {
Ok(b) => Some(b),
Err(why) => {
obs.notice(&format!(
"the CPU share of the jobs is off: task-traffic-controller {why}, so its budget is not known"
));
None
}
},
None => Some(crate::cpu::cores()),
};
cpu = budget.and_then(|b| crate::cpu::share(b, a.parallel, gated, peak));
}
let opts = exec::Opts {
parallel,
traffic_controller,
executor: None,
portool,
containers: a.containers,
job_timeout_min: a.job_timeout,
keep: a.keep,
trash: cache.join("trash"),
all_os_legs,
};
let ws = exec::Workspace {
root: wt.clone(),
repo_root: root.clone(),
run_dir: run_dir.clone(),
tools: tools.clone(),
lock_file: cache.join("locks").join(format!("{key}.lock")),
};
let build_cache = crate::build_cache::Settings::from_ctx(ctx, &cache, a.no_build_cache);
let result = run_plan(ctx, &fp, &ws, opts, cpu, build_cache);
if a.keep {
owner.keep();
obs.notice(&format!("kept worktree {}", report::tilde(&wt, ctx.home())));
if fp.units.len() > 1 {
obs.notice(
"and the copies of units and matrix entries beside it (`-u<n>-`, `-c<n>-`)",
);
}
} else {
git::remove_worktree(ctx, &root, &wt, &cache.join("trash"));
git::remove_dir_later(ctx, &tools, &cache.join("trash"));
}
let r = result?;
(r.setup, r.units)
};
drop(owner);
if !ctx.cancel.is_cancelled() {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)?
.as_secs();
for (u, fp_) in units.iter().zip(&run_fps) {
if let Some(f) = fp_ {
let mut downloads: Vec<String> = u
.unit
.into_iter()
.flat_map(|ui| fp.tasks.iter().filter(move |t| t.unit == ui))
.flat_map(|t| t.artifacts.iter().cloned())
.collect();
downloads.sort();
downloads.dedup();
store.put(f, sha, u, now, &run_dir, &downloads);
}
}
}
let units: Vec<exec::UnitResult> = reused
.into_iter()
.chain(units.into_iter().map(|u| exec::UnitResult {
unit: u.unit.and_then(|i| run_idx.get(i).copied()),
..u
}))
.collect();
let result = report::assemble(
&full,
run_dir.clone(),
setup,
units,
t_start.elapsed().as_secs_f64(),
)?;
let result = report::RunResult { cpu, ..result };
exec::write_json(&run_dir.join("result.json"), &result)?;
std::fs::write(runs.join("last"), run_dir.to_string_lossy().as_bytes())?;
prune_runs(
&cache.join("runs"),
&runs,
&root,
std::time::SystemTime::now(),
);
let cancelled = ctx.cancel.is_cancelled();
Ok(RunReport {
result,
repo_root: root,
cancelled,
style: report::Style {
workflows_dir: full.config.default_workflows_dir.clone(),
home: ctx.home().map(String::from),
},
source: source_info,
})
}
pub fn publish_target(
ctx: &ExecContext,
root: &std::path::Path,
tested_sha: &str,
info: Option<&SourceInfo>,
) -> std::result::Result<String, String> {
let Some(info) = info else {
return Ok(tested_sha.to_string());
};
let target = match info.source_kind {
SourceKind::Worktree => info.original_head.clone(),
SourceKind::Commit => info.execution_commit.clone(),
SourceKind::Directory => None,
};
let Some(target) = target else {
return Err("the run tested a directory snapshot, not a commit".into());
};
source::publishable(ctx, root, info, &target)?;
Ok(target)
}
pub fn status(
ctx: &ExecContext,
dir: &std::path::Path,
sha: &str,
cache_dir: &std::path::Path,
) -> Result<(String, String)> {
let root = git::toplevel(ctx, dir)?;
let want = git::rev(ctx, &root, sha)?;
let last = cache_dir
.join("runs")
.join(repo_key(ctx, &root))
.join("last");
let run_dir =
std::fs::read_to_string(&last).context("no local-ci run recorded for this repository")?;
let saved: report::Saved = serde_json::from_str(&std::fs::read_to_string(
PathBuf::from(run_dir.trim()).join("result.json"),
)?)?;
let run_dir = PathBuf::from(run_dir.trim());
let info: Option<SourceInfo> = match std::fs::read_to_string(run_dir.join("source.json")) {
Ok(t) => Some(serde_json::from_str(&t).context("source.json is not readable")?),
Err(_) => None,
};
match &info {
None if saved.sha != want => bail!(
"the last run tested {}, not {}; run `local-ci run` again",
&saved.sha[..7],
&want[..7]
),
None => {}
Some(i) => {
if let Err(why) = source::publishable(ctx, &root, i, &want) {
bail!("not posting: {why}");
}
}
}
post_status(ctx, &root, &want, &saved.state, &saved.description)?;
Ok((
report::github_state(&saved.state).to_string(),
want[..7].to_string(),
))
}
#[cfg(test)]
mod tests {
#[test]
fn status_target_host_rules() {
let t = |u: &str, h: Option<&str>| status_target(Some(u), h);
assert_eq!(t("git@github.com:o/n.git", None), Ok("o/n".to_string()));
assert_eq!(t("https://GitHub.com/o/n", Some("")), Ok("o/n".to_string()));
assert!(t("git@gitlab.com:o/n.git", None)
.unwrap_err()
.contains("gitlab.com"));
assert!(t("https://ghe.example.com/o/n", None).is_err());
assert_eq!(
t("https://ghe.example.com/o/n", Some("ghe.example.com")),
Ok("o/n".to_string())
);
assert_eq!(
t("git@GHE.example.com:o/n", Some("ghe.example.com")),
Ok("o/n".to_string())
);
assert!(t("git@github.com:o/n", Some("ghe.example.com")).is_err());
assert!(t("/srv/git/o/n.git", None)
.unwrap_err()
.contains("local path"));
assert!(t("/srv/git/o/n.git", Some("github.com")).is_err());
assert_eq!(status_target(None, None), Err("no origin remote".into()));
}
#[test]
fn status_failure_only_no_commit_found_is_not_on_github() {
let sha = "0123456789abcdef";
let m = status_failure(sha, "gh: No commit found for SHA: 0123456 (HTTP 422)\n");
assert_eq!(
m,
"0123456 is not on GitHub yet; run `local-ci status` after pushing"
);
assert_eq!(
status_failure(sha, "{\"message\":\"No commit found for SHA\"}"),
m
);
let other = status_failure(sha, "gh: Validation Failed (HTTP 422)\nmore");
assert_eq!(other, "gh api failed: gh: Validation Failed (HTTP 422)");
assert_eq!(
status_failure(sha, "HTTP 500 body mentions 422 in passing"),
"gh api failed: HTTP 500 body mentions 422 in passing"
);
}
use super::*;
fn finished_run(dir: &Path, name: &str) -> PathBuf {
let p = dir.join(name);
std::fs::create_dir_all(p.join("job")).unwrap();
std::fs::write(p.join("result.json"), "{}").unwrap();
p
}
fn set_age(p: &Path, secs: u64) {
std::fs::File::open(p)
.unwrap()
.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(secs))
.unwrap();
}
#[test]
fn only_the_last_run_of_each_worktree_is_kept() {
let t = tempfile::tempdir().unwrap();
let all = t.path().join("runs");
let wt = t.path().join("wt-a");
std::fs::create_dir_all(&wt).unwrap();
let mine = all.join("wt-a-0000aaaa");
let old = finished_run(&mine, "100-abcdef0");
let later = finished_run(&mine, "200-abcdef0");
let last = finished_run(&mine, "150-abcdef0");
std::fs::write(mine.join("last"), last.to_string_lossy().as_bytes()).unwrap();
let going = mine.join("300-abcdef0");
std::fs::create_dir_all(&going).unwrap();
let killed = mine.join("50-abcdef0");
std::fs::create_dir_all(&killed).unwrap();
set_age(&killed, UNFINISHED_SECS + 60);
prune_runs(&all, &mine, &wt, std::time::SystemTime::now());
assert!(last.exists() && going.exists());
assert!(!old.exists() && !later.exists() && !killed.exists());
assert_eq!(
std::fs::read_to_string(mine.join("root")).unwrap(),
wt.to_string_lossy()
);
}
#[test]
fn the_runs_of_a_worktree_that_is_gone_are_dropped() {
let t = tempfile::tempdir().unwrap();
let all = t.path().join("runs");
let wt = t.path().join("here");
std::fs::create_dir_all(&wt).unwrap();
let mine = all.join("here-0000aaaa");
finished_run(&mine, "100-abcdef0");
let gone = all.join("gone-0000bbbb");
finished_run(&gone, "100-abcdef0");
std::fs::write(
gone.join("root"),
t.path().join("gone").to_string_lossy().as_bytes(),
)
.unwrap();
let other_wt = t.path().join("other");
std::fs::create_dir_all(&other_wt).unwrap();
let other = all.join("other-0000cccc");
let o1 = finished_run(&other, "100-abcdef0");
let o2 = finished_run(&other, "200-abcdef0");
std::fs::write(other.join("root"), other_wt.to_string_lossy().as_bytes()).unwrap();
let stale = all.join("stale-0000dddd");
finished_run(&stale, "100-abcdef0");
std::fs::write(stale.join("last"), "x").unwrap();
set_age(&stale.join("last"), UNRECORDED_SECS + 60);
set_age(&stale, UNRECORDED_SECS + 60);
let fresh = all.join("fresh-0000eeee");
finished_run(&fresh, "100-abcdef0");
std::fs::write(all.join("notes.txt"), "x").unwrap();
prune_runs(&all, &mine, &wt, std::time::SystemTime::now());
assert!(mine.exists() && !gone.exists() && !stale.exists());
assert!(!o1.exists() && o2.exists());
assert!(fresh.join("100-abcdef0").exists());
assert!(all.join("notes.txt").exists());
}
#[test]
fn two_runs_of_one_commit_in_one_second_get_directories_of_their_own() {
let t = tempfile::tempdir().unwrap();
let runs = t.path().join("runs");
let a = claim_run_dir(&runs, 100, "abcdef0").unwrap();
let b = claim_run_dir(&runs, 100, "abcdef0").unwrap();
let c = claim_run_dir(&runs, 100, "abcdef0").unwrap();
let d = claim_run_dir(&runs, 101, "abcdef0").unwrap();
assert_eq!(a, runs.join("100-abcdef0"));
assert_eq!(b, runs.join("100-abcdef0-1"));
assert_eq!(c, runs.join("100-abcdef0-2"));
assert_eq!(d, runs.join("101-abcdef0"));
let mut sorted = vec![c.clone(), b.clone(), a.clone()];
sorted.sort();
assert_eq!(sorted, [a, b, c]);
}
}