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
198 changes: 198 additions & 0 deletions services/common/src/description_lint.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
//! The last check on a pull request description before it is written.
//!
//! A web pull request's description carried "History of the touched files"
//! three times, one section per fix round, and a list of deploy workflows
//! for services the change never touched. Whatever section writer produced
//! it, the description is held here at the one place it is written
//! (`GitHubClient::create_pull_request` and `update_pr_body`):
//!
//! - a section said twice keeps only its newest (last) copy;
//! - a line that lists several deploy workflows (a deploy map) goes: the
//! release section names only the deploy the change waits on;
//! - "who this affects" with no use found goes: a search that found nothing
//! tells a reviewer nothing.
//!
//! [`defects`] is the check; [`clean`] applies it.

/// A section heading: `## X`, `### X`, or a line that is only a bold label
/// (`**History of the touched files**`).
fn heading(l: &str) -> Option<String> {
let t = l.trim();
let name = if let Some(h) = t.strip_prefix("### ").or_else(|| t.strip_prefix("## ")) {
h
} else if t.starts_with("**")
&& t.ends_with("**")
&& t.len() > 4
&& !t[2..t.len() - 2].contains("**")
{
&t[2..t.len() - 2]
} else {
return None;
};
let level = t.chars().take_while(|c| *c == '#').count();
let n = name.trim().trim_end_matches(':').trim().to_lowercase();
(!n.is_empty()).then(|| {
if level == 0 {
n
} else {
format!("{} {n}", "#".repeat(level))
}
})
}

/// A line that ends a section without being one (a collapsed block's
/// edge, a hidden marker).
fn boundary(l: &str) -> bool {
let t = l.trim_start();
t.starts_with("<!--") || t.starts_with("<details") || t.starts_with("</details")
}

/// Each line with whether it is inside a collapsed `<details>` block.
fn with_depth(body: &str) -> Vec<(&str, bool)> {
let mut depth = 0usize;
body.lines()
.map(|l| {
let t = l.trim_start();
if t.starts_with("<details") {
depth += 1;
return (l, true);
}
if t.starts_with("</details") {
depth = depth.saturating_sub(1);
return (l, true);
}
(l, depth > 0)
})
.collect()
}

/// A line listing more than one deploy workflow.
fn deploy_map(l: &str) -> bool {
l.matches(".github/workflows/").count() > 1
|| (l.contains("How it deploys") && l.matches("deploys on").count() > 1)
}

/// "Who this affects" saying nothing was found.
fn empty_affects(l: &str) -> bool {
let t = l.replace("**", "").to_lowercase();
t.trim_start().starts_with("who this affects:") && t.contains("nothing outside")
}

/// What is wrong with a description; empty when it holds.
pub fn defects(body: &str) -> Vec<String> {
let mut out = Vec::new();
let mut seen: Vec<String> = Vec::new();
for (l, folded) in with_depth(body) {
if folded {
continue;
}
if let Some(h) = heading(l) {
if seen.contains(&h)
&& !out
.iter()
.any(|o: &String| o.ends_with(&format!("\"{h}\"")))
{
out.push(format!("section repeated: \"{h}\""));
}
seen.push(h);
}
if deploy_map(l) {
out.push("lists several deploy workflows".to_string());
}
if empty_affects(l) {
out.push("says who it affects with no use found".to_string());
}
}
out
}

/// The description with [`defects`] taken out: an earlier copy of a
/// repeated section, deploy maps, an empty "who this affects".
pub fn clean(body: &str) -> String {
let lines: Vec<&str> = body.lines().collect();
let folded: Vec<bool> = with_depth(body).into_iter().map(|(_, f)| f).collect();
// Where each section starts and ends (in sight only: a collapsed block
// keeps what it holds).
let mut sections: Vec<(String, usize, usize)> = Vec::new();
for (i, l) in lines.iter().enumerate() {
if folded[i] {
continue;
}
if let Some(h) = heading(l) {
let end = lines[i + 1..]
.iter()
.position(|n| heading(n).is_some() || boundary(n))
.map_or(lines.len(), |p| i + 1 + p);
sections.push((h, i, end));
}
}
let mut drop = vec![false; lines.len()];
for (k, (h, start, end)) in sections.iter().enumerate() {
if sections[k + 1..].iter().any(|(n, _, _)| n == h) {
for d in drop.iter_mut().take(*end).skip(*start) {
*d = true;
}
}
}
for (i, l) in lines.iter().enumerate() {
if !folded[i] && (deploy_map(l) || empty_affects(l)) {
drop[i] = true;
}
}
let mut out: Vec<&str> = Vec::new();
for (i, l) in lines.iter().enumerate() {
if drop[i] {
continue;
}
// No run of blank lines left behind.
if l.trim().is_empty() && out.last().is_some_and(|p| p.trim().is_empty()) {
continue;
}
out.push(l);
}
let mut s = out.join("\n");
if body.ends_with('\n') && !s.ends_with('\n') {
s.push('\n');
}
s
}

#[cfg(test)]
mod tests {
use super::*;

const BEFORE: &str = "### Summary\n\nAdds the sign-up page.\n\n**History of the touched files**\n- `app/page.tsx`: round one.\n\n**History of the touched files**\n- `app/page.tsx`: round two.\n\n**How it deploys:** Staging deploys on merge (`.github/workflows/deploy-a.yml`); Staging deploys on merge (`.github/workflows/deploy-b.yml`).\n\n**Who this affects:** nothing outside this repository (searched the team's repositories).\n\n**History of the touched files**\n- `app/page.tsx`: round three.\n\n### Verification\n\nTests pass.\n";

#[test]
fn a_repeated_section_keeps_its_newest_copy() {
let d = defects(BEFORE);
assert!(
d.iter().any(|x| x.contains("history of the touched files")),
"{d:?}"
);
assert!(d.iter().any(|x| x.contains("deploy workflows")), "{d:?}");
assert!(d.iter().any(|x| x.contains("no use found")), "{d:?}");
let after = clean(BEFORE);
assert_eq!(
after.matches("History of the touched files").count(),
1,
"{after}"
);
assert!(
after.contains("round three") && !after.contains("round one"),
"{after}"
);
assert!(!after.contains(".github/workflows/"), "{after}");
assert!(!after.contains("Who this affects"), "{after}");
assert!(after.contains("### Verification\n\nTests pass."), "{after}");
assert!(defects(&after).is_empty(), "{:?}", defects(&after));
assert!(!after.contains("\n\n\n"), "{after}");
}

#[test]
fn a_clean_description_is_left_alone() {
let body = "### Summary\n\nFixes the total.\n\n**Who this affects**\n- `billing` (uses `total()`): updated in this pull request\n\n<!-- coderhelm:x -->\n";
assert_eq!(clean(body), body);
assert!(defects(body).is_empty());
}
}
163 changes: 163 additions & 0 deletions services/common/src/git_conventions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,127 @@ pub fn subject_key(subject: &str) -> Option<String> {
.map(|l| l.key)
}

/// Commits a pull request may carry when it is marked ready; more is fix
/// round churn, squashed first (a dependency pull request once had 50).
pub const MAX_READY_COMMITS: usize = 5;

/// Whether `commits` on a pull request are churn to squash before ready.
pub fn churn(commits: usize) -> bool {
commits > MAX_READY_COMMITS
}

/// One commit of a branch, oldest first, as the final squash reads it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CommitInfo {
pub sha: String,
pub subject: String,
}

/// A commit the final squash writes: its message and the commit whose tree
/// it takes (the last one of its run of commits).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Group {
pub message: String,
pub last_sha: String,
pub count: usize,
}

/// Commits a squashed pull request keeps, at most.
pub const MAX_GROUPS: usize = 4;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Round {
Review,
Checks,
Other,
}

fn round_of(subject: &str) -> Round {
let l = subject.to_lowercase();
let has = |ws: &[&str]| {
l.split(|c: char| !c.is_ascii_alphanumeric())
.any(|w| ws.contains(&w))
};
if has(&[
"review",
"feedback",
"address",
"comment",
"comments",
"suggestion",
]) {
Round::Review
} else if has(&[
"test",
"tests",
"ci",
"lint",
"format",
"fmt",
"lockfile",
"build",
"types",
"typecheck",
"clippy",
"e2e",
]) {
Round::Checks
} else {
Round::Other
}
}

fn round_words(r: Round) -> &'static str {
match r {
Round::Review => "Address review feedback",
Round::Checks => "Fix failing checks",
Round::Other => "Follow-up changes",
}
}

/// The final squash's commits: the first commit (the implementation) under
/// `first` (its own subject, normalized to the run's key), then one commit
/// per run of fix-round commits of one kind (review feedback, failing
/// checks, other follow-ups), at most [`MAX_GROUPS`] in all. Runs stay in
/// order, so each commit takes the tree of its run's last commit and the
/// result is exactly the branch's code. Every message carries the run's
/// real `key` or none.
pub fn squash_groups(commits: &[CommitInfo], first: &str, key: Option<&str>) -> Vec<Group> {
let Some((head, rest)) = commits.split_first() else {
return Vec::new();
};
let mut runs: Vec<(Option<Round>, String, usize)> = vec![(None, head.sha.clone(), 1)];
for c in rest {
let r = round_of(&c.subject);
match runs.last_mut() {
Some((Some(k), last, n)) if *k == r => {
*last = c.sha.clone();
*n += 1;
}
_ => runs.push((Some(r), c.sha.clone(), 1)),
}
}
// Too many runs: the follow-ups after the first fold into one.
while runs.len() > MAX_GROUPS {
let tail = runs.split_off(MAX_GROUPS - 1);
let last = tail.last().map(|t| t.1.clone()).unwrap_or_default();
let n: usize = tail.iter().map(|t| t.2).sum();
let kind = tail[0].0.filter(|k| tail.iter().all(|t| t.0 == Some(*k)));
runs.push((kind.or(Some(Round::Other)), last, n));
}
let msg = |text: &str| normalize_message(&normalize_subject(text, key, key.is_some()), key);
runs.into_iter()
.map(|(kind, last_sha, count)| Group {
message: match kind {
None => normalize_message(first, key),
Some(k) => msg(round_words(k)),
},
last_sha,
count,
})
.collect()
}

/// A whole commit message with its subject normalized as in
/// [`normalize_subject`] (no key added), its body kept.
pub fn normalize_message(message: &str, key: Option<&str>) -> String {
Expand Down Expand Up @@ -691,6 +812,48 @@ pub fn validate(kind: Kind, template: &str) -> Result<(), String> {

#[cfg(test)]
mod tests {
fn c(sha: &str, subject: &str) -> super::CommitInfo {
super::CommitInfo {
sha: sha.into(),
subject: subject.into(),
}
}

#[test]
fn churn_squashes_into_a_few_logical_commits_with_the_runs_key() {
let commits = vec![
c("a1", "KEY-1: add the export retry"),
c("a2", "fix lint"),
c("a3", "fix failing test"),
c("a4", "address review feedback on naming"),
c("a5", "address review comment"),
c("a6", "fix ci"),
c("a7", "tidy the docs"),
];
let g = super::squash_groups(&commits, "OPS-41: Add the export retry", Some("OPS-41"));
assert!(g.len() <= super::MAX_GROUPS, "{g:?}");
assert_eq!(g[0].message, "OPS-41: Add the export retry");
assert_eq!(g[0].last_sha, "a1");
assert_eq!(g[1].message, "OPS-41: Fix failing checks");
assert_eq!(g[1].last_sha, "a3");
assert_eq!(g[2].message, "OPS-41: Address review feedback");
// The rest folds into one, ending at the branch's tip.
assert_eq!(g.last().unwrap().last_sha, "a7");
assert_eq!(g.iter().map(|x| x.count).sum::<usize>(), 7);
// No stand-in key reaches a message.
assert!(g.iter().all(|x| !x.message.contains("KEY-1")), "{g:?}");
// Without a key, none is added.
let g = super::squash_groups(&commits[..2], "Add the export retry", None);
assert_eq!(g[1].message, "Fix failing checks");
}

#[test]
fn fifty_commits_are_churn_to_squash_and_a_few_are_not() {
assert!(!super::churn(1));
assert!(!super::churn(super::MAX_READY_COMMITS));
assert!(super::churn(50));
}

use super::*;

fn tokens() -> Tokens {
Expand Down
3 changes: 3 additions & 0 deletions services/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,9 @@ pub mod knowledge;
pub mod repo_read;
// The test that every model call site is a metered helper
pub mod ci_cover;
/// The last check on a pull request description: no section twice, no
/// deploy maps, no empty "who this affects".
pub mod description_lint;
#[cfg(test)]
mod model_call_sites;
/// Which pull requests CoderHelm may push to, edit or close: its own.
Expand Down
Loading
Loading