use crate::{fed, spec};
use std::path::Path;
use std::process::Command;
pub const LAND_MIN: f64 = 0.85;
#[must_use]
pub fn stamp(secs: u64) -> String {
let (days, rem) = ((secs / 86_400) as i64, secs % 86_400);
let z = days + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = (z - era * 146_097) as u64;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe as i64 + era * 400 + i64::from(m <= 2);
format!(
"{y:04}-{m:02}-{d:02}--{:02}-{:02}",
rem / 3600,
(rem % 3600) / 60
)
}
#[must_use]
pub fn run_branch(current: &str, secs: u64) -> String {
if current.starts_with("sherd/apply-") {
current.to_string()
} else {
format!("sherd/apply-{}", stamp(secs))
}
}
#[derive(Debug, Clone)]
pub struct Evidence {
pub commits: usize,
pub gate_ok: bool,
pub findings: usize,
pub nodes: usize,
pub believability: f64,
}
pub fn landable(e: &Evidence) -> Result<(), String> {
if e.commits == 0 {
return Err("nothing to land -- no commits on this branch".into());
}
if !e.gate_ok {
return Err("gate is red on the branch head".into());
}
if e.findings > 0 {
return Err(format!(
"{} review finding(s) -- the gate and review disagree, and review wins here",
e.findings
));
}
if e.nodes == 0 {
return Err("cannot attribute this branch to a node -- believability \
unknown, so it does not land unattended"
.into());
}
if e.believability < LAND_MIN {
return Err(format!(
"believability {:.2} < {LAND_MIN:.2} -- this node has not earned an \
unattended merge. `sherd outcome <node> kept` after review is what \
raises it; five consecutive keeps clears the bar",
e.believability
));
}
Ok(())
}
fn git(root: &Path, args: &[&str]) -> Result<String, String> {
let o = crate::git::at(root, args)
.output()
.map_err(|e| e.to_string())?;
if o.status.success() {
Ok(String::from_utf8_lossy(&o.stdout).trim().to_string())
} else {
Err(String::from_utf8_lossy(&o.stderr).trim().to_string())
}
}
#[must_use]
pub fn remote(root: &Path) -> Option<String> {
let names = git(root, &["remote"]).ok()?;
let has = |w: &str| names.lines().any(|r| r == w);
if has("gitlab") {
return Some("gitlab".to_string());
}
has("origin").then(|| "origin".to_string())
}
pub fn push_branch(root: &Path, branch: &str) {
let Some(r) = remote(root) else {
eprintln!(" no `gitlab` or `origin` remote -- {branch} stays LOCAL");
return;
};
match git(root, &["push", "-q", "--set-upstream", &r, branch]) {
Ok(_) => eprintln!(" pushed {branch} to {r} -- CI runs on it there"),
Err(e) => eprintln!(" push to {r} FAILED (commit is local only): {e}"),
}
}
pub fn current_branch(root: &Path) -> Result<String, String> {
git(root, &["rev-parse", "--abbrev-ref", "HEAD"])
}
pub fn evidence(
root: &Path,
branch: &str,
gate_ok: bool,
) -> Result<Evidence, String> {
let shas = git(root, &["rev-list", &format!("main..{branch}")])?;
let shas: Vec<&str> = shas.lines().filter(|l| !l.is_empty()).collect();
let mut findings = 0;
let mut lowest = 1.0_f64;
let mut nodes = std::collections::BTreeSet::new();
for sha in &shas {
findings += crate::review::commit(root, sha)
.map_err(|e| e.to_string())?
.len();
let added = crate::review::added_in_commit(root, sha)
.map_err(|e| e.to_string())?;
for (node, _) in added {
if let Some(dir) = node.parent() {
lowest = lowest.min(crate::plan::believability(dir));
nodes.insert(dir.to_path_buf());
}
}
}
Ok(Evidence {
commits: shas.len(),
gate_ok,
findings,
nodes: nodes.len(),
believability: lowest,
})
}
pub fn land_with(
root: &Path,
push: bool,
cargo: &str,
) -> Result<String, String> {
let branch = current_branch(root)?;
refuse_unlandable_state(root, &branch)?;
let gate_ok = gate_with(root, cargo)?.0;
let e = evidence(root, &branch, gate_ok)?;
eprintln!(
"land: {} commit(s) on {branch} · gate {} · {} finding(s) · {} node(s) · believability {:.2}",
e.commits,
if e.gate_ok { "green" } else { "RED" },
e.findings,
e.nodes,
e.believability
);
landable(&e)?;
merge_ff(root, &branch, push)
}
fn refuse_unlandable_state(root: &Path, branch: &str) -> Result<(), String> {
if branch == "main" || branch == "master" {
return Err(format!("already on {branch} -- nothing to land"));
}
if !git(root, &["status", "--porcelain"])?.is_empty() {
return Err(
"working tree dirty -- land moves committed work only".into()
);
}
Ok(())
}
fn merge_ff(root: &Path, branch: &str, push: bool) -> Result<String, String> {
git(root, &["checkout", "main"])?;
if let Err(err) = git(root, &["merge", "--ff-only", branch]) {
git(root, &["checkout", branch])?;
return Err(format!("not a fast-forward -- main moved. {err}"));
}
if push && let Some(r) = remote(root) {
git(root, &["push", "-q", &r, "main"])?;
return Ok(format!("{branch} landed on main and pushed to {r}"));
}
Ok(format!(
"{branch} landed on main{}",
if push { " (no remote)" } else { "" }
))
}
pub fn land(root: &Path, push: bool) -> Result<String, String> {
land_with(root, push, &cargo_bin())
}
#[cfg(test)]
#[path = "tests/land.rs"]
mod tests;
#[cfg(test)]
#[path = "tests/git.rs"]
mod git_tests;
#[cfg(test)]
#[path = "tests/gate.rs"]
mod gate_tests;
pub fn gate(root: &Path) -> Result<(bool, String), String> {
gate_with(root, &cargo_bin())
}
pub fn gate_with(root: &Path, cargo: &str) -> Result<(bool, String), String> {
let out = Command::new(cargo)
.args(["test", "--offline"])
.current_dir(root)
.output();
let (tests_ok, mut report) = match out {
Ok(o) => {
let s = format!(
"{}{}",
String::from_utf8_lossy(&o.stdout),
String::from_utf8_lossy(&o.stderr)
);
(
o.status.success(),
format!(
"=== cargo test: {} ===\n{}",
if o.status.success() { "PASS" } else { "FAIL" },
tail(&s, 2500)
),
)
}
Err(e) => {
return Err(format!(
"the gate could not RUN: `{cargo}` -- {e}. set SHERD_CARGO or enter the \
dev shell. a gate that did not execute is not a gate that passed \
or failed"
));
}
};
let mut viol = 0;
let nodes = fed::discover(root);
for n in &nodes {
viol += std::fs::read_to_string(n.join("SPEC.md"))
.map_or(1, |t| spec::check(&t).len());
}
report.push_str(&format!(
"\n=== sherd check: {} === {} nodes examined, {viol} violations\n",
if viol == 0 { "PASS" } else { "FAIL" },
nodes.len()
));
let drift = if root.join(".sherd-slices").is_file() {
let drift = crate::slice::drifted(root)?;
report.push_str(&format!(
"=== slice: {} === {} drifted\n",
if drift.is_empty() { "PASS" } else { "FAIL" },
drift.len()
));
drift
} else {
report.push_str("=== slice: none required === no registry\n");
Vec::new()
};
let (fmt, fmt_r) = fmt_ok(root, cargo);
let (debt, debt_r) = lint_debt_ok(root, cargo);
report.push_str(&fmt_r);
report.push_str(&debt_r);
Ok((
tests_ok && viol == 0 && drift.is_empty() && fmt && debt,
report,
))
}
#[must_use]
pub fn cargo_bin() -> String {
std::env::var("SHERD_CARGO").unwrap_or_else(|_| "cargo".into())
}
pub(crate) fn fmt_ok(root: &Path, cargo: &str) -> (bool, String) {
let out = Command::new(cargo)
.args(["fmt", "--check"])
.current_dir(root)
.output();
let ok = out.is_ok_and(|o| o.status.success());
(
ok,
format!("=== fmt: {} ===\n", if ok { "PASS" } else { "FAIL" }),
)
}
pub(crate) fn lint_debt_ok(root: &Path, cargo: &str) -> (bool, String) {
let Some(was) = crate::debt::recorded(root) else {
return (true, String::new());
};
let Some(now) = crate::debt::measure(root, cargo).map(|m| m.density())
else {
return (true, String::new());
};
let ok = now <= was;
let word = if ok { "PASS" } else { "ROSE" };
(
ok,
format!(
"=== lint density: {word} === {} per KLoC (ceiling {})\n",
crate::debt::per_kloc(now),
crate::debt::per_kloc(was)
),
)
}
pub(crate) fn tail(s: &str, n: usize) -> &str {
if s.len() <= n { s } else { &s[s.len() - n..] }
}