Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
256 changes: 256 additions & 0 deletions crates/squabble-cli/src/drift.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,256 @@
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) <j.d.a.jewell@open.ac.uk>
//! `squabble drift` — compare a repository's workflow callers with the layer-3
//! templates (CI programme W49, S9).
//!
//! Read-only by construction: it lists and reads files under `--repo` and
//! `--templates` and writes nothing, anywhere. The comparison itself is
//! [`squabble_core::drift`]; this module only gathers the inputs.
//!
//! Exit codes: `0` no drift found; `4` drift found (a reportable finding, like
//! `squabble chains`); `2` bad usage or an unreadable input. A clean `0` still
//! carries `not_checked`: read it before treating `0` as "all good".

use serde::Serialize;
use squabble_core::drift::{analyse, File, Inputs, Report};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

pub const USAGE: &str = "usage: squabble drift [--json] [--repo DIR] [--templates DIR] [--latest-suite-sha SHA] [--latest-proven-sha SHA]";

/// Where the vendored templates live, relative to a repository root.
const DEFAULT_TEMPLATES: &str = "docs/upstream/proven-cicd-w49/templates";
const LOCK: &str = ".github/workflows/actions.lock";

#[derive(Serialize)]
struct Out<'a> {
schema: &'static str,
repo: String,
templates: TemplatesInfo,
latest: Latest<'a>,
drift: bool,
#[serde(flatten)]
report: &'a Report,
}

#[derive(Serialize)]
struct TemplatesInfo {
dir: String,
/// The SHA the templates were taken at, when the vendor README says.
source_sha: Option<String>,
}

#[derive(Serialize)]
struct Latest<'a> {
suite_sha: Option<&'a str>,
/// Where `suite_sha` came from: `flag`, `templates-readme` (the SHA the vendored
/// templates were taken at, i.e. a branch tip, not a release) or `none`.
suite_sha_source: &'static str,
/// What `StalePin` means for this run. Until release tags exist the default is
/// the vendor-time branch tip, so a stale pin is only "behind vendor-time main".
stale_pin_means: &'static str,
proven_sha: Option<&'a str>,
}

struct Args {
json: bool,
repo: PathBuf,
templates: Option<PathBuf>,
suite_sha: Option<String>,
proven_sha: Option<String>,
}

fn parse(args: &[String]) -> Result<Args, String> {
let mut a = Args {
json: false,
repo: PathBuf::from("."),
templates: None,
suite_sha: None,
proven_sha: None,
};
let mut it = args.iter();
while let Some(flag) = it.next() {
let mut val = |name: &str| {
it.next()
.cloned()
.ok_or_else(|| format!("{name} needs a value"))
};
match flag.as_str() {
"--json" => a.json = true,
"--repo" => a.repo = PathBuf::from(val("--repo")?),
"--templates" => a.templates = Some(PathBuf::from(val("--templates")?)),
"--latest-suite-sha" => a.suite_sha = Some(val("--latest-suite-sha")?),
"--latest-proven-sha" => a.proven_sha = Some(val("--latest-proven-sha")?),
other => return Err(format!("unknown argument {other}")),
}
}
Ok(a)
}

fn read(p: &Path) -> Result<String, String> {
std::fs::read_to_string(p).map_err(|e| format!("cannot read {}: {e}", p.display()))
}

/// Files directly in `dir` with a `.yml`/`.yaml` extension, sorted by name.
fn yaml_files(dir: &Path) -> Result<Vec<PathBuf>, String> {
let mut v: Vec<PathBuf> = std::fs::read_dir(dir)
.map_err(|e| format!("cannot list {}: {e}", dir.display()))?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| {
p.is_file()
&& matches!(
p.extension().and_then(std::ffi::OsStr::to_str),
Some("yml" | "yaml")
)
})
.collect();
v.sort();
Ok(v)
}

/// The SHA after `templates/ and profiles/ from main = ` in the vendor README.
fn vendor_source_sha(templates: &Path) -> Option<String> {
let readme = std::fs::read_to_string(templates.parent()?.join("README.adoc")).ok()?;
let line = readme
.lines()
.find(|l| l.contains("templates/ and profiles/ from main"))?;
let (_, rest) = line.split_once('=')?;
let sha: String = rest
.trim()
.chars()
.take_while(char::is_ascii_hexdigit)
.collect();
(sha.len() == 40).then_some(sha)
}

pub fn run(args: &[String]) -> ExitCode {
let a = match parse(args) {
Ok(a) => a,
Err(e) => {
eprintln!("squabble drift: {e}\n{USAGE}");
return ExitCode::from(2);
}
};
match gather_and_report(&a) {
Ok(code) => code,
Err(e) => {
eprintln!("squabble drift: {e}");
ExitCode::from(2)
}
}
}

fn gather_and_report(a: &Args) -> Result<ExitCode, String> {
let tdir = a
.templates
.clone()
.unwrap_or_else(|| a.repo.join(DEFAULT_TEMPLATES));
if !tdir.is_dir() {
return Err(format!(
"templates directory {} does not exist (pass --templates DIR)",
tdir.display()
));
}

// Workflow templates only: a template with no top-level `on:` (dependabot.yml) is config, not a workflow.
let mut templates = Vec::new();
for p in yaml_files(&tdir)? {
let text = read(&p)?;
if text.lines().any(|l| l.starts_with("on:")) {
let name = p
.file_name()
.and_then(std::ffi::OsStr::to_str)
.unwrap_or_default()
.to_string();
templates.push(File { path: name, text });
}
}
if templates.is_empty() {
return Err(format!("no workflow templates found in {}", tdir.display()));
}

let wf_dir = a.repo.join(".github/workflows");
let mut workflows = Vec::new();
if wf_dir.is_dir() {
for p in yaml_files(&wf_dir)? {
let name = p
.file_name()
.and_then(std::ffi::OsStr::to_str)
.unwrap_or_default();
workflows.push(File {
path: format!(".github/workflows/{name}"),
text: read(&p)?,
});
}
}
let lock = std::fs::read_to_string(a.repo.join(LOCK)).ok();

let source_sha = vendor_source_sha(&tdir);
let suite = a.suite_sha.clone().or_else(|| source_sha.clone());
let suite_source = match (&a.suite_sha, &source_sha) {
(Some(_), _) => "flag",
(None, Some(_)) => "templates-readme",
_ => "none",
};
let stale_means = match suite_source {
"templates-readme" => {
"behind vendor-time main (a branch tip, not a release; no release tags exist yet)"
}
"flag" => "behind the pin given with --latest-suite-sha",
_ => "not checked: no latest suite pin",
};
let report = analyse(&Inputs {
workflows: &workflows,
templates: &templates,
lock: lock.as_deref(),
latest_suite_sha: suite.as_deref(),
latest_proven_sha: a.proven_sha.as_deref(),
});

let drift = report.drifted();
if a.json {
let out = Out {
schema: "squabble/drift/v1",
repo: a.repo.display().to_string(),
templates: TemplatesInfo {
dir: tdir.display().to_string(),
source_sha,
},
latest: Latest {
suite_sha: suite.as_deref(),
suite_sha_source: suite_source,
stale_pin_means: stale_means,
proven_sha: a.proven_sha.as_deref(),
},
drift,
report: &report,
};
println!(
"{}",
serde_json::to_string_pretty(&out).map_err(|e| format!("serialise: {e}"))?
);
} else {
for c in &report.callers {
println!(
"{}\t{}\t{}",
c.file,
c.template,
if c.clean { "clean" } else { "DRIFT" }
);
}
for f in &report.findings {
println!(
"finding\t{}",
serde_json::to_string(f).map_err(|e| format!("serialise: {e}"))?
);
}
for n in &report.not_checked {
println!("not-checked\t{n}");
}
}
Ok(if drift {
ExitCode::from(4)
} else {
ExitCode::SUCCESS
})
}
4 changes: 4 additions & 0 deletions crates/squabble-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ mod board;
#[cfg(feature = "boj")]
mod boj;
mod chains;
mod drift;
mod fetch;
mod fight;
mod inbox;
Expand Down Expand Up @@ -80,6 +81,7 @@ fn main() -> ExitCode {
},
Some("fight") => fight::run(&args[2..]),
Some("chains") => chains::run(&args[2..]),
Some("drift") => drift::run(&args[2..]),
Some("zero-job") => zero_job::run(&args[2..]),
Some("phase") => phase::run(&args[2..]),
Some("verify-satisfied") => verify::run(&args[2..]),
Expand Down Expand Up @@ -108,6 +110,7 @@ fn main() -> ExitCode {
squabble {}\n \
squabble {}\n \
squabble {}\n \
squabble {}\n \
squabble --version\n\n\
EXIT CODES:\n \
0 ok · 2 failure · 3 no `required_status_checks` rule on the base branch · 4 chains/zero-job: blocking finding · 5 verify-satisfied: agent items remain · 6 board or inbox-sweep: incomplete\n",
Expand All @@ -120,6 +123,7 @@ fn main() -> ExitCode {
inbox::USAGE.trim_start_matches("usage: squabble "),
verify::USAGE.trim_start_matches("usage: squabble "),
triage::USAGE.trim_start_matches("usage: squabble "),
drift::USAGE.trim_start_matches("usage: squabble "),
relock::USAGE.trim_start_matches("usage: squabble ")
);
ExitCode::from(2)
Expand Down
Loading
Loading