use std::path::Path;
use std::process::Command;
mod llvm_json;
pub(crate) mod swift;
pub(crate) mod swift_fn;
pub use swift::{
Toolchain, excluded_files, llvm_cov_lines, llvm_cov_lines_except,
swift_bin, swift_coverage, toolchain_of,
};
pub use swift_fn::{
Exclusion, SwiftMeasure, excluded_cap, excluded_verdict, exclusions,
measure_export, record_excluded, swift_measure,
};
pub const GATE_ARGS: [&str; 5] = [
"clippy",
"--workspace",
"--all-targets",
"--all-features",
"--message-format=short",
];
pub const MEASURED: [&str; 2] = ["src", "dev"];
pub const CEILING_FILE: u64 = 4_000;
pub const CEILING_TEST: u64 = 2_000;
#[must_use]
pub fn gate_counts(line: &str) -> bool {
MEASURED.iter().any(|d| line.starts_with(&format!("{d}/")))
&& line.contains(": warning")
}
#[must_use]
pub fn build_failed(line: &str) -> bool {
line.starts_with("error[") || line.starts_with("error:")
}
#[must_use]
pub fn per_kloc(tenths: usize) -> String {
format!("{}.{}", tenths / 10, tenths % 10)
}
#[must_use]
pub fn measured_lines(root: &Path) -> usize {
MEASURED
.iter()
.flat_map(|d| crate::fed::rust_files(&root.join(d)))
.filter_map(|p| std::fs::read_to_string(p).ok())
.map(|t| t.lines().count())
.sum()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Measured {
pub count: usize,
pub excess: usize,
pub loc: usize,
}
impl Measured {
#[must_use]
pub const fn density(self) -> usize {
match self.count.saturating_mul(10_000).checked_div(self.loc) {
Some(d) => d,
None => 0,
}
}
#[must_use]
pub const fn shape(self) -> usize {
match self.excess.saturating_mul(1_000).checked_div(self.loc) {
Some(s) => s,
None => 0,
}
}
}
#[must_use]
pub fn excess_lines(line: &str) -> Option<usize> {
let (_, tail) = line.split_once("too many lines (")?;
let (nums, _) = tail.split_once(')')?;
let (had, limit) = nums.split_once('/')?;
Some(
had.parse::<usize>()
.ok()?
.saturating_sub(limit.parse().ok()?),
)
}
#[must_use]
pub fn measure(root: &Path, cargo: &str) -> Option<Measured> {
let o = match Command::new(cargo)
.args(GATE_ARGS)
.current_dir(root)
.output()
{
Ok(o) => o,
Err(e) => {
eprintln!("sherd/debt: could not launch `{cargo}`: {e}");
return None;
}
};
let out = String::from_utf8_lossy(&o.stderr);
if !o.status.success() || out.lines().any(build_failed) {
eprintln!("sherd/debt: `{cargo} clippy` exited {}:", o.status);
out.lines()
.filter(|l| build_failed(l))
.chain(out.lines().rev().take(5))
.for_each(|l| eprintln!(" {l}"));
return None;
}
let loc = measured_lines(root);
if loc == 0 {
eprintln!("sherd/debt: no Rust found under {}", root.display());
return None;
}
let hits: Vec<&str> = out.lines().filter(|l| gate_counts(l)).collect();
Some(Measured {
count: hits.len(),
excess: hits.iter().filter_map(|l| excess_lines(l)).sum(),
loc,
})
}
#[must_use]
pub fn recorded_ceilings(root: &Path) -> Option<(usize, usize)> {
let text = std::fs::read_to_string(root.join(".lint-debt")).ok()?;
let read = |k: &str| text.lines().find_map(|l| tenths(l.strip_prefix(k)?));
Some((read("density ")?, read("shape ")?))
}
fn breach_density(now: usize, was: usize) -> Option<String> {
(now > was).then(|| {
format!(
"sherd/debt:V2: lint DENSITY rose, {} -> {} per KLoC. Fix the \
new sites, or record WHY in .lint-debt with the raise.",
per_kloc(was),
per_kloc(now)
)
})
}
fn breach_shape(now: usize, was: usize) -> Option<String> {
(now > was).then(|| {
format!(
"sherd/debt:V1: SHAPE rose, {}% -> {}% of lines inside an \
over-long function. Counting functions punishes splitting one, \
so this counts lines OVER the limit.",
per_kloc(was),
per_kloc(now)
)
})
}
#[must_use]
pub fn verdict(now: Measured, was: (usize, usize)) -> (bool, String) {
let (dw, sw) = was;
let (d, s) = (now.density(), now.shape());
let mut lines: Vec<String> = [breach_density(d, dw), breach_shape(s, sw)]
.into_iter()
.flatten()
.collect();
let ok = lines.is_empty();
lines.push(format!(
" lint {} per KLoC (ceiling {}) · shape {}% (ceiling {}%) · {} \
warnings and {} excess lines over {} lines of Rust",
per_kloc(d),
per_kloc(dw),
per_kloc(s),
per_kloc(sw),
now.count,
now.excess,
now.loc
));
(ok, lines.join("\n"))
}
fn restate(line: &str, now: Measured) -> String {
match line.split_once(' ').map(|(k, _)| k) {
Some("density") => format!("density {}", per_kloc(now.density())),
Some("shape") => format!("shape {}", per_kloc(now.shape())),
Some("count") => format!("count {}", now.count),
Some("excess") => format!("excess {}", now.excess),
Some("loc") => format!("loc {}", now.loc),
_ => line.to_string(),
}
}
pub fn record(root: &Path, now: Measured) -> Result<String, String> {
let path = root.join(".lint-debt");
let text = std::fs::read_to_string(&path).map_err(|e| format!("{e}"))?;
let was = recorded_ceilings(root).ok_or_else(|| {
"no `density`/`shape` rows to record into".to_string()
})?;
if !verdict(now, was).0 {
return Err(
"refusing to RECORD a raise. A ratchet that writes down whatever \
it measures is not a ratchet."
.into(),
);
}
let out: String = text.lines().fold(String::new(), |mut acc, l| {
acc.push_str(&restate(l, now));
acc.push('\n');
acc
});
std::fs::write(&path, &out).map_err(|e| format!("{e}"))?;
Ok(format!(
"recorded density {} · shape {}%",
per_kloc(now.density()),
per_kloc(now.shape())
))
}
#[must_use]
pub fn recorded(root: &Path) -> Option<usize> {
let text = std::fs::read_to_string(root.join(".lint-debt")).ok()?;
text.lines()
.find_map(|l| tenths(l.strip_prefix("density ")?))
}
fn tenths(v: &str) -> Option<usize> {
let v = v.trim();
let (whole, frac) = v.split_once('.').unwrap_or((v, "0"));
let tenth = frac.chars().next()?.to_digit(10)? as usize;
whole
.parse::<usize>()
.ok()?
.checked_mul(10)?
.checked_add(tenth)
}
pub const COVERAGE_SCALE: usize = 100;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Build {
All,
Default,
}
impl Build {
pub const BOTH: [Self; 2] = [Self::All, Self::Default];
#[must_use]
pub const fn row(self) -> &'static str {
match self {
Self::All => "lines",
Self::Default => "lines-default",
}
}
const fn flags(self) -> &'static [&'static str] {
match self {
Self::All => &["--all-features"],
Self::Default => &[],
}
}
}
#[must_use]
pub fn coverage(root: &Path, cargo: &str) -> Option<usize> {
coverage_of(root, cargo, Build::All)
}
#[must_use]
pub fn coverage_of(root: &Path, cargo: &str, build: Build) -> Option<usize> {
let o = Command::new(cargo)
.args(["llvm-cov", "--workspace"])
.args(build.flags())
.arg("--summary-only")
.current_dir(root)
.output()
.ok()?;
if !o.status.success() {
return None;
}
let text = String::from_utf8_lossy(&o.stdout);
let total = text.lines().find(|l| l.starts_with("TOTAL"))?;
hundredths(total.split_whitespace().nth(9)?.trim_end_matches('%'))
}
#[must_use]
pub fn recorded_floor(root: &Path) -> Option<usize> {
recorded_floor_of(root, Build::All)
}
#[must_use]
pub fn recorded_floor_of(root: &Path, build: Build) -> Option<usize> {
let text = std::fs::read_to_string(root.join(".coverage")).ok()?;
text.lines().find_map(|l| {
hundredths(l.strip_prefix(build.row())?.strip_prefix(' ')?)
})
}
fn hundredths(v: &str) -> Option<usize> {
let v = v.trim();
let (whole, frac) = v.split_once('.').unwrap_or((v, "0"));
let mut d = frac.chars().filter(char::is_ascii_digit);
let tens = d.next()?.to_digit(10)? as usize;
let ones = d.next().and_then(|c| c.to_digit(10)).unwrap_or(0) as usize;
whole
.parse::<usize>()
.ok()?
.checked_mul(COVERAGE_SCALE)?
.checked_add(tens.saturating_mul(10).saturating_add(ones))
}
#[must_use]
pub fn percent(h: usize) -> String {
format!("{}.{:02}", h / COVERAGE_SCALE, h % COVERAGE_SCALE)
}
#[must_use]
pub fn coverage_verdict(now: usize, was: usize) -> (bool, String) {
if now < was {
return (
false,
format!(
"sherd/debt:V9: coverage FELL, {}% -> {}%. A line that \
stopped being covered is a test that stopped asserting. \
Cover it, or say why in .coverage with the drop.",
percent(was),
percent(now)
),
);
}
(
true,
format!(" coverage {}% (floor {}%)", percent(now), percent(was)),
)
}
pub fn record_coverage(root: &Path, now: usize) -> Result<String, String> {
record_coverage_of(root, Build::All, now)
}
pub fn record_coverage_of(
root: &Path,
build: Build,
now: usize,
) -> Result<String, String> {
let path = root.join(".coverage");
let text = std::fs::read_to_string(&path).map_err(|e| format!("{e}"))?;
let row = build.row();
let was = recorded_floor_of(root, build)
.ok_or_else(|| format!("no `{row}` row to record into"))?;
if !coverage_verdict(now, was).0 {
return Err(format!(
"refusing to RECORD a drop in `{row}`, {}% -> {}%. Cover the \
gap, or edit .coverage by hand with the reason.",
percent(was),
percent(now)
));
}
let prefix = format!("{row} ");
let out: String = text.lines().fold(String::new(), |mut acc, l| {
if l.starts_with(&prefix) {
acc.push_str(&format!("{row} {}", percent(now)));
} else {
acc.push_str(l);
}
acc.push('\n');
acc
});
std::fs::write(&path, &out).map_err(|e| format!("{e}"))?;
Ok(format!("recorded `{row}` coverage {}%", percent(now)))
}
#[cfg(test)]
#[path = "tests/debt.rs"]
mod tests;
#[cfg(test)]
#[path = "tests/coverage.rs"]
pub(crate) mod coverage_tests;