From ad17f1eab6f813a91d9366b3eba205c2dc834eee Mon Sep 17 00:00:00 2001 From: Guy <115384744+jirathip-k@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:30:29 +0700 Subject: [PATCH] Port the history rewrite tool out of drover as a standalone binary (#2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The history fresh-start tool (one root before a cut, one commit per landed PR, private archive, undo) now lives here as its own program, no longer inside drover. - It does the same thing it did in drover: the same plan, the same two separate owner run cards for the line and for main, and the same refusals. - Drover hands over its folders, fleets and saved ids as arguments. The tool uses drover's own commands to post cards and to check that the run is the approved one. Closes #1 · 1 review round · src +1498 · PASS fafb193 --- .github/workflows/ci.yml | 20 ++ .gitignore | 1 + Cargo.lock | 256 ++++++++++++++ Cargo.toml | 17 + README.md | 78 +++++ rustfmt.toml | 1 + src/main.rs | 741 +++++++++++++++++++++++++++++++++++++++ src/plan.rs | 241 +++++++++++++ src/push.rs | 245 +++++++++++++ src/sh.rs | 110 ++++++ src/write.rs | 161 +++++++++ tests/compact.rs | 453 ++++++++++++++++++++++++ 12 files changed, 2324 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 rustfmt.toml create mode 100644 src/main.rs create mode 100644 src/plan.rs create mode 100644 src/push.rs create mode 100644 src/sh.rs create mode 100644 src/write.rs create mode 100644 tests/compact.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..bebd35a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,20 @@ +name: ci +on: + push: + branches: [main, staging] + pull_request: + +jobs: + rust: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - name: fmt + run: cargo fmt --check + - name: clippy + run: cargo clippy --locked --all-targets -- -D warnings + - name: test + run: cargo test --locked diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9b4669d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target*/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..c101248 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,256 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "clap" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "compact" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "serde", + "serde_json", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..4922ada --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "compact" +version = "0.1.0" +edition = "2021" +rust-version = "1.99" +description = "A repo's fresh history start: one root before a cut, one commit per landed PR after it, archive, undo" +license = "MIT" +repository = "https://github.com/jirathip-dev/compact" + +[dependencies] +anyhow = "1" +clap = { version = "4", features = ["derive"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +[lints.rust] +unsafe_code = "forbid" diff --git a/README.md b/README.md index b700e69..3953583 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,80 @@ # compact + Repo history fresh start: one root before a cut, one commit per landed PR after it, archive, undo (moved out of drover) + +`compact` replaces a repo's integration line with one root commit (the cut's exact tree, message +`: initial (history before in /-history)`) and one commit per landed PR after it, each +with the old commit's tree, message, author and date. Every other branch and notes ref is carried with its files +unchanged: an open PR's commits are copied onto their true base; a branch that last met the line before the cut +is carried detached; a fully merged branch is deleted (the archive keeps it). Nothing is rebased or replayed, and +every new tip's tree is checked equal to its old one (`COMPACT_TREE`). + +## Install + +Needs `git`, an authenticated `gh` and, for run cards, `drover` on `PATH`. + +```sh +cargo install --locked --git https://github.com/jirathip-dev/compact +``` + +## Use + +Every call names the repo and its folders: + +```sh +compact --repo owner/name --line staging --clone ~/src/name \ + [--lane [host:]path]... [--fleet ]... [--saved ids.tsv] [--dir ] +``` + +- `--clone`: the fleet's clone. Its `origin` is the repo pushed to; it is reset after every push. +- `--lane`: a lane folder (`host:path` runs over `ssh`). It must be clean and pushed, and it is reset after a push. +- `--fleet`: a drover fleet on the repo. No issue may sit in `review` or `verify` (`drover status --json`). +- `--saved`: drover's stored commit ids, one `fleetissuesha` per line. The dry run lists the ones to + remap, and the push writes them as `moved.json`. +- `--dir`: the scratch folder for the bare copy `old.git`, `plan.json`, `compact-map.tsv`, `moved.json` and + `undone` (default `~/.local/state/compact//`). + +Acts: + +| act | what it does | +| --- | --- | +| `--cut --dry-run` | Mirror origin, write the plan and map, print old → new commits, the root, each PR commit, the open PRs to carry, the records to remap and the readiness checks. Pushes nothing. | +| `--cut --thread ` | The same, then post the owner's run cards in that drover thread (`COMPACT_NOT_READY` when a check fails). | +| `--undo [--dry-run \| --thread ]` | Check every ref is still where compact put it; with `--thread`, post the undo cards. | +| `--push [--main] [--undo]` | The approved card's run. Refused `COMPACT_UNAPPROVED` outside its card. | +| `--reset` | Reset the clone and lane folders onto origin's branches (files stay). | + +A date cut is the last first-parent line commit before that midnight. Refusals print `REFUSED : why` and +exit 3. + +## Run cards and drover + +`compact` does not depend on drover. It uses drover's CLI only: + +- **Posting.** `--thread ` runs `drover card post --cmd … --why … --blast … --dir --timeout 3600 ` + once for the line (`compact --thread --push `: every ref but `main`). When `main` + moves, it posts a second card (`… --main --push `), whose blast warns that the push may fire the + repo's main-merge workflows. Undo posts `… --undo --push ` and `… --undo --main --push `. +- **Approval.** `--push` reads `drover thread show --json`. It runs only while a card with exactly its + command is approved and has not finished, so the line's card never pushes `main`. The main card runs only after + the line is compacted (`COMPACT_NOT_READY` before). +- **Archive.** The approved line run first pushes every old branch, tag, note and PR head (as `pull/`) to the + private `/-history`. It reads that back, then adds the plan and map on its `drover-compact` branch + (`COMPACT_ARCHIVE` if the archive is public or misses a ref). Then one atomic push moves every ref but `main`, + each with a lease on its old value (`COMPACT_MOVED` if one moved since the plan). Open PR bodies get their new + head ids. +- **Records.** Drover keeps its own log. After the push, `/moved.json` lists per fleet and issue the saved + ids now in the new history (`from`, `to`, `held`); drover logs them as its `compacted` records. An undo writes + `/undone` (the run's new tip) for drover's `compact-undone`. Which stored fields drover exports through + `--saved` (its saved-SHA list and the CI guard over it) stays in drover. + +Pause the fleet (`drover pause `) before posting the cards. + +## Develop + +```sh +cargo fmt --check && cargo clippy --all-targets -- -D warnings && cargo test +``` + +`tests/compact.rs` builds a repo with merges, why notes, an open PR, a lane and `main`. It compacts the repo +through faked `gh` and `drover`, then undoes the compact, with the real binary and real git. diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..7530651 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1 @@ +max_width = 120 diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..027b10b --- /dev/null +++ b/src/main.rs @@ -0,0 +1,741 @@ +mod plan; +mod push; +mod sh; +mod write; + +use anyhow::{Context, Result}; +use clap::Parser; +use plan::{Class, Kind}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use sh::{json, ok, refused, On, Refused}; +use std::collections::BTreeMap; +use std::io::Write; +use std::path::{Path, PathBuf}; + +/// A repo's fresh start: one root before a cut, one commit per landed PR after it; archive, undo. +#[derive(Parser, Debug)] +#[command(name = "compact", version)] +struct Opts { + #[arg(long, help = "The GitHub repo: owner/name")] + repo: String, + #[arg(long, help = "The line to compact: the repo's integration branch")] + line: String, + #[arg(long, help = "The fleet's clone: its origin is the repo; it is reset after a push")] + clone: PathBuf, + #[arg( + long = "lane", + help = "A lane folder, `[host:]path` (repeatable): checked clean, reset after a push" + )] + lanes: Vec, + #[arg( + long = "fleet", + help = "A drover fleet on the repo (repeatable): no check lane may be working" + )] + fleets: Vec, + #[arg( + long, + help = "Drover's saved commit ids, `fleetissuesha` per line: the records to remap" + )] + saved: Option, + #[arg( + long, + help = "The scratch folder: the bare copy, the plan and the map (default ~/.local/state/compact/)" + )] + dir: Option, + #[arg(long, help = "The cut: a date (the last line commit before that midnight) or a sha")] + cut: Option, + #[arg(long, help = "Print the plan; push nothing")] + dry_run: bool, + #[arg(long, help = "Post the owner's run card in this drover thread")] + thread: Option, + #[arg(long, help = "Put the old history back (with --dry-run, --thread or --push)")] + undo: bool, + #[arg( + long, + help = "The approved card's run: the plan's new tip (with --undo, its old tip)" + )] + push: Option, + #[arg(long, help = "With --push: the approved main card's run, main alone")] + main: bool, + #[arg(long, help = "Reset the fleet's clone and lane folders onto origin's new branches")] + reset: bool, +} + +enum Act { + Cut(String), + Undo, + Push { tip: String, undo: bool, main: bool }, + Reset, +} + +/// The repo and the folders compact works on, as the arguments name them. +pub struct Repo { + pub repo: String, + pub line: String, + pub clone: PathBuf, + pub lanes: Vec<(Option, PathBuf)>, + pub fleets: Vec, + pub saved: Option, + pub dir: PathBuf, + pub thread: Option, + base: Vec, +} + +impl Repo { + /// The clone's origin url. + pub fn origin(&self) -> Result { + let c = self.clone.to_string_lossy(); + Ok(ok("git", &["-C", &c, "remote", "get-url", "origin"])? + .trim() + .to_string()) + } + fn name(&self) -> &str { + self.repo.rsplit('/').next().unwrap_or(&self.repo) + } + /// The saved commit ids: (fleet, issue, sha) in the file's order. + pub fn saved(&self) -> Result> { + let Some(f) = &self.saved else { return Ok(vec![]) }; + let text = std::fs::read_to_string(f).with_context(|| format!("--saved {}", f.display()))?; + let row = |l: &str| { + let mut w = l.split('\t'); + Some(( + w.next()?.to_string(), + w.next()?.parse().ok()?, + w.next()?.trim().to_string(), + )) + }; + Ok(text.lines().filter_map(row).collect()) + } + fn cmd(&self, words: &[&str]) -> String { + let mut c = self.base.clone(); + c.extend(words.iter().map(ToString::to_string)); + sh::line(&c) + } +} + +/// A ref's move as the plan file keeps it. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RefMove { + pub name: String, + pub old: String, + pub new: Option, + pub class: String, + pub pr: Option, +} + +/// One commit of the new line after the root: old and new id, subject and how many old commits it holds. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Step { + pub old: String, + pub new: String, + pub subject: String, + pub held: usize, +} + +/// The planned compact of a repo: what the dry run prints, the card pins and the push sends. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Plan { + pub repo: String, + pub line: String, + pub cut: String, + pub root: String, + pub old_tip: String, + pub new_tip: String, + pub archive: String, + pub commits: [usize; 2], + pub refs: Vec, + pub chain: Vec, + pub forks: Vec, +} + +const MAIN: &str = "refs/heads/main"; + +impl Plan { + /// `m` is `main`, pushed only by its own card (never when main is the line itself). + pub fn is_main(&self, m: &RefMove) -> bool { + m.name == MAIN && self.line != "main" + } + /// `main`'s move, if the plan moves it. + pub fn main(&self) -> Option<&RefMove> { + (self.refs.iter()).find(|m| self.is_main(m) && m.new.as_deref() != Some(m.old.as_str())) + } +} + +fn is_sha(s: &str) -> bool { + s.len() >= 7 && s.len() <= 40 && s.bytes().all(|b| b.is_ascii_hexdigit()) +} + +/// The map file as rows: old id → (new id, kind). +pub fn map(d: &Path) -> Result> { + let text = std::fs::read_to_string(d.join("compact-map.tsv")).context("no compact-map.tsv: run --cut first")?; + let row = |l: &str| { + let mut w = l.split('\t').map(String::from); + Some((w.next()?, (w.next()?, w.next()?))) + }; + Ok(text.lines().filter_map(row).collect()) +} + +fn load(d: &Path) -> Result { + let text = std::fs::read_to_string(d.join("plan.json")).context("no plan.json: run --cut first")?; + Ok(serde_json::from_str(&text)?) +} + +fn build(t: &Repo, cut: &str) -> Result { + let d = &t.dir; + std::fs::create_dir_all(d)?; + let copy = d.join("old.git"); + write::mirror(&t.origin()?, ©)?; + let words = "pr list --state open --limit 500 --json number,headRefName,isCrossRepository -R"; + let prs = json( + "gh", + &[&words.split(' ').collect::>()[..], &[t.repo.as_str()]].concat(), + )?; + let prs = prs.as_array().cloned().unwrap_or_default(); + let open = (prs.iter()) + .filter_map(|p| Some((p["number"].as_u64()?, p["headRefName"].as_str()?.to_string()))) + .collect(); + let old = write::read(©, open)?; + let g = |a: &[&str]| ok("git", &[&["-C", ©.to_string_lossy()][..], a].concat()); + let line = format!("refs/heads/{}", t.line); + let (sha, label) = if is_sha(cut) { + let s = g(&["rev-parse", &format!("{cut}^{{commit}}")])?; + let day = g(&["log", "-1", "--format=%cs", s.trim()])?; + (s, day) + } else { + let before = format!("--before={cut} 00:00"); + ( + g(&["rev-list", "-1", "--first-parent", &before, &line])?, + cut.to_string(), + ) + }; + let (sha, label) = (sha.trim().to_string(), label.trim().to_string()); + if sha.is_empty() { + return refused("BAD_VALUE", format!("no commit on {} before {cut}", t.line)); + } + let archive = format!("{}-history", t.repo); + let msg = format!("{}: initial (history before {label} in {archive})\n", t.name()); + let shape = plan::plan(&old, &t.line, &sha, &msg).or_else(|e| refused("BAD_VALUE", e))?; + let (ids, notes) = write::write(©, &shape)?; + let id = |n: usize| ids.get(n).cloned().unwrap_or_default(); + let pr_of = |name: &str| { + let b = name.strip_prefix("refs/heads/")?; + old.open.iter().find(|o| o.1 == b).map(|o| o.0) + }; + let refs: Vec = (shape.refs.iter()) + .map(|m| RefMove { + name: m.name.clone(), + old: m.old.clone(), + new: match m.class { + Class::Notes => notes.iter().find(|n| n.0 == m.name).map(|n| n.1.clone()), + _ => m.to.map(id), + }, + class: format!("{:?}", m.class), + pr: pr_of(&m.name), + }) + .collect(); + if let Some(m) = refs + .iter() + .find(|m| m.name == MAIN && m.new.is_none() && t.line != "main") + { + return refused( + "COMPACT_TREE", + format!("main ({:.12}) would be deleted; nothing was sent", m.old), + ); + } + let checked: Vec<&RefMove> = refs.iter().filter(|m| m.class != "Notes" && m.new.is_some()).collect(); + let ends: Vec<&str> = (checked.iter()) + .flat_map(|m| [m.old.as_str(), m.new.as_deref().unwrap_or_default()]) + .collect(); + let trees = write::trees(©, &ends)?; + let bad: Vec<&str> = (checked.iter().zip(trees.chunks(2))) + .filter(|(_, t)| t.first() != t.get(1)) + .map(|(m, _)| m.name.as_str()) + .collect(); + if !bad.is_empty() { + return refused( + "COMPACT_TREE", + format!("a new tip's tree differs: {}; nothing was sent", bad.join(", ")), + ); + } + let mut held = vec![0usize; shape.nodes.len()]; + for (n, _) in shape.place.values().filter(|p| p.1 == Kind::Held) { + if let Some(h) = held.get_mut(*n) { + *h += 1; + } + } + let chain = (shape.line.iter().enumerate()) + .map(|(i, o)| Step { + old: o.clone(), + new: id(i + 1), + subject: old + .commits + .get(o) + .map_or("", |c| c.message.lines().next().unwrap_or_default()) + .to_string(), + held: held.get(i + 1).copied().unwrap_or_default(), + }) + .collect(); + let old_tip = (old.refs.iter().find(|x| x.0 == line)).map_or(String::new(), |x| x.1.clone()); + let count = g(&["rev-list", "--count", &old_tip])? + .trim() + .parse() + .unwrap_or_default(); + let p = Plan { + repo: t.repo.clone(), + line: t.line.clone(), + cut: sha, + root: id(0), + new_tip: id(shape.line.len()), + old_tip, + archive, + commits: [count, shape.line.len() + 1], + refs, + chain, + forks: (prs.iter()) + .filter(|p| p["isCrossRepository"] == true) + .filter_map(|p| p["number"].as_u64()) + .collect(), + }; + let mut rows: Vec = (shape.place.iter()) + .map(|(o, (n, k))| format!("{o}\t{}\t{}\n", id(*n), k.word())) + .collect(); + rows.sort(); + std::fs::write(d.join("compact-map.tsv"), rows.concat())?; + std::fs::write(d.join("plan.json"), serde_json::to_string_pretty(&p)?)?; + Ok(p) +} + +fn dirty(on: On, wt: &str) -> Option { + let st = match on.ok("git", &["-C", wt, "status", "--porcelain", "--untracked-files=no"]) { + Ok(s) => s, + Err(e) => return Some(format!("unreadable git status ({e:#})")), + }; + let changed = st.lines().count(); + if changed > 0 { + return Some(format!("{changed} uncommitted change(s)")); + } + match on.ok("git", &["-C", wt, "rev-list", "--count", "HEAD", "--not", "--remotes"]) { + Ok(n) if n.trim() == "0" => None, + Ok(n) => Some(format!("{} unpushed commit(s)", n.trim())), + Err(e) => Some(format!("unreadable unpushed count ({e:#})")), + } +} + +fn lanes(t: &Repo) -> impl Iterator, &Path)> { + (t.lanes.iter()) + .map(|(h, p)| (On(h.as_deref()), p.as_path())) + .filter(|(on, p)| { + let git = p.join(".git"); + match on.0 { + None => git.exists(), + Some(_) => on.ok("test", &["-e", &git.to_string_lossy()]).is_ok(), + } + }) +} + +fn ready(t: &Repo, p: &Plan) -> Vec { + let mut why = vec![]; + for fleet in &t.fleets { + match json("drover", &["status", fleet, "--json"]) { + Ok(v) => { + for s in v.as_array().into_iter().flatten() { + let state = s["state"].as_str().unwrap_or_default(); + if state.starts_with("review") || state.starts_with("verify") { + why.push(format!("#{} has a check lane working ({state})", s["issue"])); + } + } + } + Err(e) => why.push(format!("fleet {fleet}: drover status failed ({e:#})")), + } + } + for (on, wt) in lanes(t) { + if let Some(d) = dirty(on, &wt.to_string_lossy()) { + let host = on.0.map(|h| format!("{h}:")).unwrap_or_default(); + why.push(format!("{host}{}: {d}", wt.display())); + } + } + for n in &p.forks { + why.push(format!("PR #{n} comes from a fork")); + } + for m in p.refs.iter().filter(|m| m.class == "Detached" && m.pr.is_some()) { + why.push(format!( + "PR #{} would be detached: update or close it", + m.pr.unwrap_or_default() + )); + } + for b in [p.line.as_str(), "main"] { + let api = format!("repos/{}/branches/{b}/protection", p.repo); + let v = json("gh", &["api", &api]).unwrap_or(Value::Null); + if v["allow_force_pushes"]["enabled"] == false { + why.push(format!("force pushes are not allowed on {b}")); + } + } + why +} + +fn unready(t: &Repo, p: &Plan) -> Result<()> { + let why = ready(t, p); + if why.is_empty() { + return Ok(()); + } + refused("COMPACT_NOT_READY", why.join("; ")) +} + +/// Each issue's saved ids that now live in the new history: (fleet, issue, its `moved` list). +pub fn moves( + saved: &[(String, u64, String)], + m: &BTreeMap, + root: &str, +) -> Vec<(String, u64, Value)> { + let mut by: BTreeMap<(String, u64), Vec> = BTreeMap::new(); + for (fleet, i, sha) in saved { + let ids = by.entry((fleet.clone(), *i)).or_default(); + if !ids.contains(sha) { + ids.push(sha.clone()); + } + } + let mut out = vec![]; + for ((fleet, i), ids) in by { + let mut moved: Vec<(String, String, Vec)> = vec![]; + let kind = |s: &String| m.get(s).filter(|(to, _)| to != root).map(|(to, k)| (to, k.as_str())); + let mut ids: Vec<&String> = ids.iter().filter(|s| kind(s).is_some()).collect(); + ids.sort_by_key(|s| kind(s).map(|k| k.1 != "same")); + for s in ids { + match kind(s) { + Some((to, "same")) => moved.push((s.clone(), to.clone(), vec![])), + Some((to, "held")) => match moved.iter_mut().find(|x| &x.1 == to) { + Some(x) => x.2.push(s.clone()), + None => moved.push((String::new(), to.clone(), vec![s.clone()])), + }, + _ => {} + } + } + for x in moved.iter_mut().filter(|x| x.0.is_empty()) { + x.0 = m + .iter() + .find(|(_, v)| v.0 == x.1 && v.1 == "same") + .map(|(o, _)| o.clone()) + .unwrap_or_default(); + } + let v: Vec = moved + .into_iter() + .map(|(f, t, h)| json!({"from": f, "to": t, "held": h})) + .collect(); + if !v.is_empty() { + out.push((fleet, i, Value::Array(v))); + } + } + out +} + +fn report(out: &mut dyn Write, p: &Plan, mv: &[(String, u64, Value)], why: &[String]) -> Result<()> { + writeln!(out, "compact {} · line {} · cut {:.9}", p.repo, p.line, p.cut)?; + let [a, b] = p.commits; + writeln!(out, "commits {} {a} → {b} (1 root + {})", p.line, b - 1)?; + writeln!( + out, + "root {:.12} · history before the cut in {}", + p.root, p.archive + )?; + writeln!(out, "chain {}", p.chain.len())?; + for s in &p.chain { + writeln!( + out, + " {:.9} ← {:.9} {} holds {} old commits", + s.new, s.old, s.subject, s.held + )?; + } + let n = |c: &str| p.refs.iter().filter(|m| m.class == c).count(); + let classes = ["Line", "SameTree", "Carried", "Detached", "Merged", "Notes"]; + let each: Vec = classes.iter().map(|c| format!("{c} {}", n(c))).collect(); + writeln!(out, "refs {}: {}", p.refs.len(), each.join(" · "))?; + let open: Vec<&RefMove> = p.refs.iter().filter(|m| m.pr.is_some()).collect(); + writeln!(out, "open PRs {}, each costs one fresh review", open.len())?; + for m in open { + let new = m.new.as_deref().unwrap_or("deleted"); + writeln!( + out, + " #{} {} {:.9} → {new:.9} {}", + m.pr.unwrap_or_default(), + m.name, + m.old, + m.class + )?; + } + match p.main() { + Some(m) => writeln!( + out, + "main {:.9} → {:.9} · its own card", + m.old, + m.new.as_deref().unwrap_or_default() + )?, + None => writeln!(out, "main not moved")?, + } + writeln!(out, "events {} issues to remap", mv.len())?; + for (fleet, i, v) in mv { + for x in v.as_array().into_iter().flatten() { + let held = x["held"].as_array().map_or(0, Vec::len); + let (f, t) = ( + x["from"].as_str().unwrap_or_default(), + x["to"].as_str().unwrap_or_default(), + ); + writeln!(out, " {fleet}#{i} {f:.9} → {t:.9}, {held} lane heads held")?; + } + } + let checks = if why.is_empty() { + "ready ✓".to_string() + } else { + why.join(" · ") + }; + writeln!(out, "checks tip trees equal ✓ · {checks}")?; + writeln!(out, "new tip {} · nothing pushed", p.new_tip)?; + Ok(()) +} + +const RESET: &str = "cd \"$1\" && git fetch -q --prune --force origin '+refs/heads/*:refs/remotes/origin/*' \ + '+refs/notes/*:refs/notes/*' && b=$(git symbolic-ref -q --short HEAD) && git reset -q --keep \"origin/$b\""; + +fn reset(t: &Repo, out: &mut dyn Write) -> Result<()> { + let dirs = std::iter::once((On::default(), t.clone.as_path())).chain(lanes(t)); + for (on, d) in dirs { + let host = on.0.map(|h| format!("{h}:")).unwrap_or_default(); + match on.run_in("sh", &["-c", RESET, "sh", &d.to_string_lossy()], "") { + Ok(o) if o.code == 0 => writeln!(out, "reset {host}{}", d.display())?, + Ok(o) => writeln!(out, "could not reset {host}{}: {}", d.display(), o.stderr.trim())?, + Err(e) => writeln!(out, "could not reset {host}{}: {e:#}", d.display())?, + } + } + Ok(()) +} + +fn running(thread: Option<&str>, want: &str) -> bool { + let Some(t) = thread else { return false }; + let Ok(v) = json("drover", &["thread", "show", t, "--json"]) else { + return false; + }; + let items = v["items"].as_array().cloned().unwrap_or_default(); + let said = + |p: &str| (items.iter()).any(|i| i["from"] == "system" && i["text"].as_str().is_some_and(|s| s.starts_with(p))); + (items.iter()) + .filter(|i| i["card"]["cmd"] == want) + .filter_map(|i| i["card"]["id"].as_str()) + .any(|id| { + said(&format!("run {id} approved by owner, running in")) + && !said(&format!("run {id} approved by owner, ran in")) + }) +} + +fn card(thread: &str, cmd: &str, what: &str, blast: &str) -> Result { + let here = std::env::current_dir()?; + let a = [ + "card", + "post", + "--cmd", + cmd, + "--why", + what, + "--blast", + blast, + "--dir", + &here.to_string_lossy(), + "--timeout", + "3600", + thread, + ]; + let id = ok("drover", &a)?; + Ok(format!("run card {} posted: {cmd}", id.trim())) +} + +fn run(t: &Repo, act: &Act, dry: bool, out: &mut dyn Write) -> Result<()> { + let all = format!( + "force-moves every ref of {} but main (archive first, lease on each)", + t.repo + ); + let main_blast = |m: &RefMove, to: &str| { + format!( + "force-moves main of {} to {to:.12} (lease on {:.12}); the push may fire the repo's main-merge workflows (a prod deploy, migrations)", + t.repo, m.old + ) + }; + let thread = t.thread.as_deref().filter(|_| !dry); + match act { + Act::Cut(cut) => { + if let Some(done) = push::finished(t)? { + return Ok(writeln!(out, "{done}")?); + } + let p = build(t, cut)?; + let why = ready(t, &p); + report(out, &p, &moves(&t.saved()?, &map(&t.dir)?, &p.root), &why)?; + match thread { + None => Ok(()), + Some(_) if !why.is_empty() => refused("COMPACT_NOT_READY", why.join("; ")), + Some(th) => { + let cmd = t.cmd(&["--push", &p.new_tip]); + writeln!( + out, + "{}", + card(th, &cmd, "compact: archive, then one atomic push", &all)? + )?; + if let Some(m) = p.main() { + let to = m.new.as_deref().unwrap_or_default(); + let cmd = t.cmd(&["--main", "--push", to]); + let what = "compact main, after the line's card"; + writeln!(out, "{}", card(th, &cmd, what, &main_blast(m, to))?)?; + } + Ok(()) + } + } + } + Act::Undo => { + let p = load(&t.dir)?; + push::at(t, &p, true, false)?; + push::at(t, &p, true, true)?; + writeln!( + out, + "undo {} · {} refs back to their old values · line {:.9} → {:.9}", + p.repo, + p.refs.len(), + p.new_tip, + p.old_tip + )?; + match thread { + None => Ok(writeln!(out, "nothing pushed")?), + Some(th) => { + let cmd = t.cmd(&["--undo", "--push", &p.old_tip]); + writeln!(out, "{}", card(th, &cmd, "undo the compact", &all)?)?; + if let Some(m) = p.main() { + let cmd = t.cmd(&["--undo", "--main", "--push", &m.old]); + let what = "undo the compact of main"; + writeln!(out, "{}", card(th, &cmd, what, &main_blast(m, &m.old))?)?; + } + Ok(()) + } + } + } + Act::Push { tip, undo, main } => { + let mut words = vec![]; + words.extend(undo.then_some("--undo")); + words.extend(main.then_some("--main")); + words.extend(["--push", tip.as_str()]); + let want = t.cmd(&words); + if !running(t.thread.as_deref(), &want) { + return refused( + "COMPACT_UNAPPROVED", + format!("`{want}` runs only inside its approved run card"), + ); + } + let p = load(&t.dir)?; + let m = p.main(); + let at = match (*main, *undo) { + (false, false) => Some(p.new_tip.as_str()), + (false, true) => Some(p.old_tip.as_str()), + (true, false) => m.and_then(|m| m.new.as_deref()), + (true, true) => m.map(|m| m.old.as_str()), + }; + if at != Some(tip.as_str()) { + return refused( + "COMPACT_MOVED", + format!("{tip:.12} is not this plan's tip; run --cut again"), + ); + } + if *main { + if !*undo { + unready(t, &p)?; + if push::finished(t)?.is_none() { + return refused( + "COMPACT_NOT_READY", + format!("{} is not compacted yet: its card runs first", p.line), + ); + } + } + push::main(t, &p, *undo)?; + } else if *undo { + push::undo(t, &p)?; + } else { + unready(t, &p)?; + push::push(t, &p)?; + } + reset(t, out) + } + Act::Reset => reset(t, out), + } +} + +fn repo(o: &Opts) -> Result { + if o.repo.split('/').filter(|w| !w.is_empty()).count() != 2 { + return refused("BAD_VALUE", format!("--repo {} is not owner/name", o.repo)); + } + let abs = |p: &Path| std::path::absolute(p); + let clone = abs(&o.clone)?; + let dir = match &o.dir { + Some(d) => abs(d)?, + None => { + let home = std::env::var_os("HOME").context("no HOME: pass --dir")?; + PathBuf::from(home).join(".local/state/compact").join(&o.repo) + } + }; + let saved = o.saved.as_deref().map(abs).transpose()?; + let lanes = (o.lanes.iter()) + .map(|l| match l.split_once(':') { + Some((h, p)) if !h.is_empty() && !h.contains('/') => (Some(h.to_string()), PathBuf::from(p)), + _ => (None, PathBuf::from(l)), + }) + .collect(); + let mut base: Vec = ["compact", "--repo", &o.repo, "--line", &o.line, "--clone"] + .map(String::from) + .into(); + base.push(clone.to_string_lossy().into()); + for l in &o.lanes { + base.extend(["--lane".into(), l.clone()]); + } + for f in &o.fleets { + base.extend(["--fleet".into(), f.clone()]); + } + if let Some(s) = &saved { + base.extend(["--saved".into(), s.to_string_lossy().into()]); + } + base.extend(["--dir".into(), dir.to_string_lossy().into()]); + if let Some(th) = &o.thread { + base.extend(["--thread".into(), th.clone()]); + } + Ok(Repo { + repo: o.repo.clone(), + line: o.line.clone(), + clone, + lanes, + fleets: o.fleets.clone(), + saved, + dir, + thread: o.thread.clone(), + base, + }) +} + +fn main() { + let o = Opts::parse(); + let act = match (o.cut.clone(), o.push.clone()) { + _ if o.reset => Act::Reset, + (_, Some(tip)) => Act::Push { + tip, + undo: o.undo, + main: o.main, + }, + _ if o.undo => Act::Undo, + (Some(cut), None) => Act::Cut(cut), + (None, None) => { + eprintln!( + "usage: compact --repo --line --clone --cut | --undo | --reset" + ); + std::process::exit(2); + } + }; + let mut out = std::io::stdout(); + let res = repo(&o).and_then(|t| run(&t, &act, o.dry_run, &mut out)); + if let Err(e) = res { + let code = if e.downcast_ref::().is_some() { 3 } else { 1 }; + let _ = out.flush(); + eprintln!("{e:#}"); + std::process::exit(code); + } +} diff --git a/src/plan.rs b/src/plan.rs new file mode 100644 index 0000000..5e8aa20 --- /dev/null +++ b/src/plan.rs @@ -0,0 +1,241 @@ +use std::collections::{BTreeMap, HashMap, HashSet}; + +/// One old commit: its tree, parents, author and committer lines and message, as git stores them. +#[derive(Debug, Clone)] +pub struct Commit { + pub tree: String, + pub parents: Vec, + pub author: String, + pub committer: String, + pub message: String, +} + +/// The old repo, read once: commits, refs (`refs/pull//head` included), notes (ref, commit, text), open PRs. +#[derive(Debug, Default)] +pub struct Old { + pub commits: HashMap, + pub refs: Vec<(String, String)>, + pub notes: Vec<(String, String, String)>, + pub open: Vec<(u64, String)>, +} + +/// Where an old commit went: its own new commit (`Same`, tree-equal), its PR's (`Held`) or the root. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Same, + Held, + Root, +} + +impl Kind { + /// The word `compact-map.tsv` writes. + pub fn word(self) -> &'static str { + match self { + Kind::Same => "same", + Kind::Held => "held", + Kind::Root => "root", + } + } +} + +/// What a ref is to compact: the line, at a line commit, carried on its base, detached, merged (deleted) or notes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Class { + Line, + SameTree, + Carried, + Detached, + Merged, + Notes, +} + +/// A new commit before git names it: parents by index. +#[derive(Debug, Clone)] +pub struct Node { + pub tree: String, + pub parents: Vec, + pub author: String, + pub committer: String, + pub message: String, +} + +/// A ref's move: name, old value, the node it moves to (none: deleted), its class. +#[derive(Debug, Clone)] +pub struct Move { + pub name: String, + pub old: String, + pub to: Option, + pub class: Class, +} + +/// `plan`'s answer: node 0 is the root, then the line after the cut, then the copies. +#[derive(Debug, Default)] +pub struct Shape { + pub nodes: Vec, + pub place: HashMap, + pub line: Vec, + pub refs: Vec, + pub notes: Vec<(String, Vec<(usize, String)>)>, +} + +/// The PR number a line subject ends with: `title (#issue) (#pr)`. +pub fn pr_of(message: &str) -> Option { + let s = message.lines().next()?.trim_end().strip_suffix(')')?; + s.rsplit_once("(#")?.1.parse().ok() +} + +type ByNode<'a> = BTreeMap>; + +fn reach(old: &Old, starts: &[&str], seen: &mut HashSet) -> Vec { + let (mut out, mut todo) = (vec![], starts.iter().map(ToString::to_string).collect::>()); + while let Some(c) = todo.pop() { + if !seen.insert(c.clone()) { + continue; + } + if let Some(k) = old.commits.get(&c) { + todo.extend(k.parents.iter().cloned()); + out.push(c); + } + } + out +} + +fn node(c: &Commit, parents: Vec) -> Node { + Node { + tree: c.tree.clone(), + parents, + author: c.author.clone(), + committer: c.committer.clone(), + message: c.message.clone(), + } +} + +/// Place every old commit and ref (`line`: the branch name, `cut`: a commit on its first-parent chain); pure. +pub fn plan(old: &Old, line: &str, cut: &str, root_message: &str) -> Result { + let get = |s: &str| { + old.commits + .get(s) + .ok_or_else(|| format!("commit {s:.9} is not in the copy")) + }; + let line_ref = format!("refs/heads/{line}"); + let tip = (old.refs.iter().find(|r| r.0 == line_ref)).ok_or_else(|| format!("no branch {line}"))?; + let mut chain = vec![]; + let mut at = tip.1.clone(); + while at != cut { + let first = get(&at)?.parents.first().cloned(); + chain.push(std::mem::replace( + &mut at, + first.ok_or(format!("{cut:.9} is not on {line}"))?, + )); + } + chain.reverse(); + let c = get(cut)?; + let mut s = Shape { + nodes: vec![Node { + parents: vec![], + author: c.committer.replacen("committer ", "author ", 1), + message: root_message.to_string(), + ..node(c, vec![]) + }], + line: chain.clone(), + ..Shape::default() + }; + let mut seen = HashSet::new(); + for a in reach(old, &[cut], &mut seen) { + s.place.insert(a, (0, Kind::Root)); + } + s.place.insert(cut.to_string(), (0, Kind::Same)); + let pulls: HashMap<&str, &str> = (old.refs.iter()) + .filter_map(|(n, v)| Some((n.strip_prefix("refs/pull/")?.strip_suffix("/head")?, v.as_str()))) + .collect(); + for l in &chain { + let n = s.nodes.len(); + let k = get(l)?; + s.nodes.push(node(k, vec![n - 1])); + s.place.insert(l.clone(), (n, Kind::Same)); + seen.insert(l.clone()); + let pr = pr_of(&k.message).map(|p| p.to_string()); + let mut from: Vec<&str> = k.parents.iter().skip(1).map(String::as_str).collect(); + from.extend(pr.as_deref().and_then(|p| pulls.get(p))); + for h in reach(old, &from, &mut seen) { + s.place.insert(h, (n, Kind::Held)); + } + } + let mut rooted: Vec = vec![true; s.nodes.len()]; + let mut refs: Vec<&(String, String)> = old.refs.iter().collect(); + refs.sort(); + for (name, tip) in refs.iter().map(|r| (&r.0, &r.1)) { + if name.starts_with("refs/notes/") || name.starts_with("refs/pull/") { + continue; + } + let mut todo = vec![(tip.clone(), false)]; + while let Some((c, ready)) = todo.pop() { + if s.place.contains_key(&c) { + continue; + } + let k = get(&c)?; + if !ready { + todo.push((c, true)); + todo.extend(k.parents.iter().map(|p| (p.clone(), false))); + continue; + } + let ps: Vec = (k.parents.iter()) + .filter_map(|p| s.place.get(p).filter(|x| x.1 == Kind::Same).map(|x| x.0)) + .collect(); + rooted.push(ps.iter().any(|p| rooted.get(*p) == Some(&true))); + s.place.insert(c, (s.nodes.len(), Kind::Same)); + s.nodes.push(node(k, ps)); + } + let (n, kind) = s.place.get(tip.as_str()).copied().unwrap_or((0, Kind::Root)); + let class = match kind { + _ if *name == line_ref => Class::Line, + Kind::Same if n <= chain.len() => Class::SameTree, + Kind::Same if rooted.get(n) == Some(&true) => Class::Carried, + Kind::Same => Class::Detached, + Kind::Held | Kind::Root => Class::Merged, + }; + let to = (class != Class::Merged).then_some(n); + s.refs.push(Move { + name: name.clone(), + old: tip.clone(), + to, + class, + }); + } + let mut notes: BTreeMap<&str, ByNode> = (old.refs.iter()) + .filter(|r| r.0.starts_with("refs/notes/")) + .map(|r| (r.0.as_str(), BTreeMap::new())) + .collect(); + for (r, c, text) in &old.notes { + let Some(&(n, kind)) = s.place.get(c).filter(|p| p.1 != Kind::Root && p.0 > 0) else { + continue; + }; + let when = old.commits.get(c).map_or("", |k| k.committer.as_str()); + let key = if kind == Kind::Same { "" } else { when }; + if let Some(at) = notes.get_mut(r.as_str()) { + at.entry(n).or_default().push((key, text)); + } + } + for (r, by) in notes { + let mut one = vec![]; + for (n, mut texts) in by { + texts.sort_by_key(|t| (t.0.rsplit(' ').nth(1).and_then(|t| t.parse::().ok()), t.1)); + let own = texts.iter().find(|t| t.0.is_empty()).map(|t| t.1.trim().to_string()); + let joined = || texts.iter().map(|t| t.1.trim()).collect::>().join("\n\n"); + one.push((n, own.unwrap_or_else(joined) + "\n")); + } + s.refs.push(Move { + name: r.to_string(), + old: old + .refs + .iter() + .find(|x| x.0 == r) + .map(|x| x.1.clone()) + .unwrap_or_default(), + to: None, + class: Class::Notes, + }); + s.notes.push((r.to_string(), one)); + } + Ok(s) +} diff --git a/src/push.rs b/src/push.rs new file mode 100644 index 0000000..a90408a --- /dev/null +++ b/src/push.rs @@ -0,0 +1,245 @@ +use crate::sh::{json, ok, refused, run_in}; +use crate::{map, moves, Plan, Repo}; +use anyhow::{bail, Result}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +fn remote(url: &str) -> Result> { + let out = ok("git", &["ls-remote", url])?; + let row = |l: &str| l.split_once('\t').map(|(v, n)| (n.to_string(), v.to_string())); + Ok(out.lines().filter_map(row).collect()) +} + +fn push_all(copy: &Path, url: &str, moves: &[(&str, &str, Option<&str>)]) -> Result<()> { + let c = copy.to_string_lossy(); + let mut a: Vec = ["-C", &c, "push", "--atomic", "--porcelain", url] + .map(String::from) + .into(); + for (name, lease, _) in moves { + a.push(format!("--force-with-lease={name}:{lease}")); + } + a.extend( + moves + .iter() + .map(|(name, _, to)| format!("{}:{name}", to.unwrap_or_default())), + ); + let o = run_in("git", &a.iter().map(String::as_str).collect::>(), "")?; + if o.code != 0 { + bail!("the atomic push was refused, nothing moved: {}", o.stderr.trim()); + } + Ok(()) +} + +/// Every plan ref of one card (`main`: main alone, else all but main) on origin at its old value (`undo`: its new one), else `COMPACT_MOVED`; the refs still to move. +pub fn at(t: &Repo, p: &Plan, undo: bool, main: bool) -> Result { + let now = remote(&t.origin()?)?; + let (mut todo, mut moved) = (0, vec![]); + for m in p.refs.iter().filter(|m| p.is_main(m) == main) { + let (from, to) = if undo { + (m.new.as_deref(), Some(m.old.as_str())) + } else { + (Some(m.old.as_str()), m.new.as_deref()) + }; + let is = now.get(&m.name).map(String::as_str); + if is == from && from != to { + todo += 1; + } else if is != to { + moved.push(m.name.as_str()); + } + } + if !moved.is_empty() { + return refused("COMPACT_MOVED", format!("moved since the plan: {}", moved.join(", "))); + } + Ok(todo) +} + +fn archive(t: &Repo, p: &Plan) -> Result<()> { + let view = || json("gh", &["repo", "view", &p.archive, "--json", "visibility"]); + let v = if let Ok(v) = view() { + v + } else { + ok("gh", &["repo", "create", &p.archive, "--private"])?; + view()? + }; + if v["visibility"] != "PRIVATE" { + return refused( + "COMPACT_ARCHIVE", + format!("{} is not private; nothing was pushed", p.archive), + ); + } + let (url, copy) = (t.origin()?.replace(&t.repo, &p.archive), t.dir.join("old.git")); + let c = copy.to_string_lossy(); + let specs = [ + "+refs/heads/*:refs/heads/*", + "+refs/tags/*:refs/tags/*", + "+refs/notes/*:refs/notes/*", + "+refs/pull/*/head:refs/heads/pull/*", + ]; + ok("git", &[&["-C", &*c, "push", "-q", &url][..], &specs].concat())?; + let (old, there) = ( + ok("git", &["-C", &c, "for-each-ref", "--format=%(refname)\t%(objectname)"])?, + remote(&url)?, + ); + let as_there = |n: &str| match n.strip_prefix("refs/pull/").and_then(|x| x.strip_suffix("/head")) { + Some(pr) => Some(format!("refs/heads/pull/{pr}")), + None => (!n.starts_with("refs/pull/")).then(|| n.to_string()), + }; + let missing: Vec<&str> = (old.lines().filter_map(|l| l.split_once('\t'))) + .filter(|(n, v)| as_there(n).is_some_and(|t| there.get(&t) != Some(&(*v).to_string()))) + .map(|(n, _)| n) + .collect(); + if !missing.is_empty() { + return refused( + "COMPACT_ARCHIVE", + format!("the archive's read-back misses {}", missing.join(", ")), + ); + } + let g = |a: &[&str], input: &str| -> Result { + let o = run_in("git", &[&["-C", &*c][..], a].concat(), input)?; + Ok(o.stdout.trim().to_string()) + }; + let blob = |file: &str| -> Result { + g( + &["hash-object", "-w", "--stdin"], + &std::fs::read_to_string(t.dir.join(file))?, + ) + }; + let tree = format!( + "100644 blob {}\tcompact-map.tsv\n100644 blob {}\tplan.json\n", + blob("compact-map.tsv")?, + blob("plan.json")? + ); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH)? + .as_secs(); + let who = format!("drover {now} +0000"); + let raw = format!( + "tree {}\nauthor {who}\ncommitter {who}\n\ncompact {}\n", + g(&["mktree"], &tree)?, + p.new_tip + ); + let id = g(&["hash-object", "-t", "commit", "-w", "--stdin"], &raw)?; + ok( + "git", + &[ + "-C", + &c, + "push", + "-q", + "-f", + &url, + &format!("{id}:refs/heads/drover-compact"), + ], + ) + .map(drop) +} + +fn records(t: &Repo, p: &Plan) -> Result<()> { + let moved: Vec = (moves(&t.saved()?, &map(&t.dir)?, &p.root).into_iter()) + .map(|(fleet, issue, moved)| serde_json::json!({"fleet": fleet, "issue": issue, "run": p.new_tip, "moved": moved})) + .collect(); + std::fs::write(t.dir.join("moved.json"), serde_json::to_string_pretty(&moved)?)?; + Ok(()) +} + +fn bodies(t: &Repo, p: &Plan) -> Result<()> { + let m = map(&t.dir)?; + for pr in p.refs.iter().filter_map(|x| x.pr.filter(|_| x.new.is_some())) { + let n = pr.to_string(); + let body = json("gh", &["pr", "view", &n, "-R", &t.repo, "--json", "body"])?; + let body = body["body"].as_str().unwrap_or_default(); + let new = |w: &str| { + let hex = w.len() >= 7 && w.len() <= 40 && w.bytes().all(|b| b.is_ascii_hexdigit()); + let (_, (to, kind)) = m + .range(w.to_string()..) + .next() + .filter(|(o, _)| hex && o.starts_with(w))?; + (kind == "same").then(|| to.get(..w.len()).unwrap_or(to).to_string()) + }; + let mut out = String::new(); + let mut word = String::new(); + for ch in body.chars().chain(['\u{0}']) { + if ch.is_ascii_alphanumeric() { + word.push(ch); + continue; + } + out += &new(&word).unwrap_or(std::mem::take(&mut word)); + word.clear(); + out.extend(Some(ch).filter(|c| *c != '\u{0}')); + } + if out != body { + ok("gh", &["pr", "edit", &n, "-R", &t.repo, "--body", &out])?; + } + } + Ok(()) +} + +/// A repo whose origin is at the plan's new values: its `moved.json` written; the line to print. +pub fn finished(t: &Repo) -> Result> { + let Ok(p) = crate::load(&t.dir) else { return Ok(None) }; + if remote(&t.origin()?)?.get(&format!("refs/heads/{}", p.line)) != Some(&p.new_tip) { + return Ok(None); + } + records(t, &p)?; + Ok(Some(format!( + "{} is compacted at {:.12} ({} → {} commits)", + p.repo, p.new_tip, p.commits[0], p.commits[1] + ))) +} + +/// The approved run: archive, one atomic push with a lease on every ref, the records, the open PR bodies. +pub fn push(t: &Repo, p: &Plan) -> Result<()> { + if at(t, p, false, false)? > 0 { + archive(t, p)?; + let mv: Vec<(&str, &str, Option<&str>)> = (p.refs.iter().filter(|m| !p.is_main(m))) + .map(|m| (m.name.as_str(), m.old.as_str(), m.new.as_deref())) + .collect(); + push_all(&t.dir.join("old.git"), &t.origin()?, &mv)?; + } + finished(t)?; + bodies(t, p) +} + +fn copy(t: &Repo, p: &Plan) -> Result { + let copy = t.dir.join("old.git"); + if !copy.join("HEAD").exists() { + crate::write::mirror(&t.origin()?.replace(&t.repo, &p.archive), ©)?; + } + Ok(copy) +} + +/// The approved main card: main alone to its new value (`undo`: its old one), a lease on the value it leaves. +pub fn main(t: &Repo, p: &Plan, undo: bool) -> Result<()> { + let Some(m) = p.main() else { + return refused("COMPACT_MOVED", "this plan does not move main"); + }; + let new = m.new.as_deref().unwrap_or_default(); + let (from, to) = if undo { + (new, m.old.as_str()) + } else { + (m.old.as_str(), new) + }; + if at(t, p, undo, true)? > 0 { + push_all(©(t, p)?, &t.origin()?, &[(m.name.as_str(), from, Some(to))])?; + } + Ok(()) +} + +/// The approved undo: every ref but main back to its old value, a lease on its new one, then the `undone` file. +pub fn undo(t: &Repo, p: &Plan) -> Result<()> { + let copy = copy(t, p)?; + if at(t, p, true, false)? > 0 { + let mv: Vec<(&str, &str, Option<&str>)> = (p.refs.iter().filter(|m| !p.is_main(m))) + .map(|m| { + ( + m.name.as_str(), + m.new.as_deref().unwrap_or_default(), + Some(m.old.as_str()), + ) + }) + .collect(); + push_all(©, &t.origin()?, &mv)?; + } + std::fs::write(t.dir.join("undone"), format!("{}\n", p.new_tip))?; + Ok(()) +} diff --git a/src/sh.rs b/src/sh.rs new file mode 100644 index 0000000..e7cc854 --- /dev/null +++ b/src/sh.rs @@ -0,0 +1,110 @@ +use anyhow::{bail, Result}; +use serde_json::Value; +use std::fmt; +use std::io::Write; +use std::process::{Command, Stdio}; + +/// A refusal: printed `REFUSED : `, exit 3. +#[derive(Debug)] +pub struct Refused { + pub code: &'static str, + pub why: String, +} + +impl fmt::Display for Refused { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "REFUSED {}: {}", self.code, self.why) + } +} + +impl std::error::Error for Refused {} + +/// Refuse with `code`. +pub fn refused(code: &'static str, why: impl Into) -> Result { + Err(Refused { code, why: why.into() }.into()) +} + +/// A finished process: exit code and output. +pub struct Out { + pub code: i32, + pub stdout: String, + pub stderr: String, +} + +/// Where a command runs: this host, or another over ssh. +#[derive(Clone, Copy, Default)] +pub struct On<'a>(pub Option<&'a str>); + +fn quote(s: &str) -> String { + format!("'{}'", s.replace('\'', r"'\''")) +} + +impl On<'_> { + /// Run `prog` with `args`, `input` on its stdin. + pub fn run_in(self, prog: &str, args: &[&str], input: &str) -> Result { + let mut c = match self.0 { + None => { + let mut c = Command::new(prog); + c.args(args); + c + } + Some(host) => { + let line: Vec = std::iter::once(prog).chain(args.iter().copied()).map(quote).collect(); + let mut c = Command::new("ssh"); + c.args(["-oBatchMode=yes", "-oConnectTimeout=10", host, "--", &line.join(" ")]); + c + } + }; + let mut child = c + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| anyhow::anyhow!("{prog}: {e}"))?; + if let Some(mut stdin) = child.stdin.take() { + stdin.write_all(input.as_bytes())?; + } + let o = child.wait_with_output()?; + Ok(Out { + code: o.status.code().unwrap_or(1), + stdout: String::from_utf8_lossy(&o.stdout).into(), + stderr: String::from_utf8_lossy(&o.stderr).into(), + }) + } + /// `prog`'s stdout when it exits 0, else its stderr as the error. + pub fn ok(self, prog: &str, args: &[&str]) -> Result { + let o = self.run_in(prog, args, "")?; + if o.code != 0 { + bail!("{prog} {}: {}", args.join(" "), o.stderr.trim()); + } + Ok(o.stdout) + } +} + +/// `prog` on this host: its stdout when it exits 0. +pub fn ok(prog: &str, args: &[&str]) -> Result { + On::default().ok(prog, args) +} + +/// `prog` on this host, `input` on its stdin. +pub fn run_in(prog: &str, args: &[&str], input: &str) -> Result { + On::default().run_in(prog, args, input) +} + +/// `prog`'s stdout as JSON. +pub fn json(prog: &str, args: &[&str]) -> Result { + Ok(serde_json::from_str(&ok(prog, args)?)?) +} + +/// `cmd` as one shell line: each word quoted where it needs it. +pub fn line(cmd: &[String]) -> String { + let plain = |w: &str| { + !w.is_empty() + && w.bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_./:=@,+%".contains(&b)) + }; + let words: Vec = (cmd.iter()) + .map(|w| if plain(w) { w.clone() } else { quote(w) }) + .collect(); + words.join(" ") +} diff --git a/src/write.rs b/src/write.rs new file mode 100644 index 0000000..8b7fb96 --- /dev/null +++ b/src/write.rs @@ -0,0 +1,161 @@ +use crate::plan::{Commit, Node, Old, Shape}; +use crate::sh::{ok, run_in}; +use anyhow::{bail, Context, Result}; +use std::collections::HashMap; +use std::path::Path; + +const CHUNK: usize = 1000; + +fn git(dir: &Path, a: &[&str]) -> Result { + ok("git", &[&["-C", &dir.to_string_lossy()][..], a].concat()) +} + +fn git_in(dir: &Path, a: &[&str], input: &str) -> Result { + let o = run_in("git", &[&["-C", &dir.to_string_lossy()][..], a].concat(), input)?; + if o.code != 0 { + bail!("git {}: {}", a.join(" "), o.stderr.trim()); + } + Ok(o.stdout) +} + +/// Bring the bare copy at `dir` to `url`'s every ref, PR heads included; a push from it never moves its refs. +pub fn mirror(url: &str, dir: &Path) -> Result<()> { + if !dir.join("HEAD").exists() { + ok("git", &["clone", "-q", "--mirror", url, &dir.to_string_lossy()])?; + git(dir, &["config", "--unset-all", "remote.origin.fetch"])?; + git(dir, &["config", "--unset", "remote.origin.mirror"])?; + } + git(dir, &["fetch", "-q", "--prune", "origin", "+refs/*:refs/*"]).map(drop) +} + +fn objects(dir: &Path, ids: &[String]) -> Result> { + let mut out = String::new(); + for chunk in ids.chunks(CHUNK) { + out += &git_in(dir, &["cat-file", "--batch"], &(chunk.join("\n") + "\n"))?; + } + let (mut rest, mut all) = (out.as_str(), vec![]); + while let Some((head, body)) = rest.split_once('\n') { + let mut w = head.split(' '); + let (id, size) = (w.next().unwrap_or_default(), w.nth(1).and_then(|n| n.parse().ok())); + let size: usize = size.with_context(|| format!("cat-file: {head}"))?; + all.push(( + id.to_string(), + body.get(..size).context("cat-file: short object")?.to_string(), + )); + rest = body.get(size + 1..).unwrap_or_default(); + } + Ok(all) +} + +fn commit(raw: &str) -> Commit { + let (head, message) = raw.split_once("\n\n").unwrap_or((raw, "")); + let mut c = Commit { + tree: String::new(), + parents: vec![], + author: String::new(), + committer: String::new(), + message: message.to_string(), + }; + for l in head.lines() { + match l.split_once(' ') { + Some(("tree", t)) => c.tree = t.to_string(), + Some(("parent", p)) => c.parents.push(p.to_string()), + Some(("author", _)) => c.author = l.to_string(), + Some(("committer", _)) => c.committer = l.to_string(), + _ => {} + } + } + c +} + +/// The copy at `dir` read once into values: every commit of a branch, tag or PR head, the refs and the notes. +pub fn read(dir: &Path, open: Vec<(u64, String)>) -> Result { + let refs = git( + dir, + &["for-each-ref", "--format=%(refname) %(objectname) %(objecttype)"], + )?; + let mut old = Old { open, ..Old::default() }; + for l in refs.lines() { + match l.split(' ').collect::>().as_slice() { + [n, v, "commit"] => old.refs.push(((*n).to_string(), (*v).to_string())), + [n, _, kind] => bail!("{n} is a {kind}; compact moves commits only"), + _ => {} + } + } + let ids = git(dir, &["rev-list", "--branches", "--tags", "--glob=refs/pull/*"])?; + let ids: Vec = ids.lines().map(String::from).collect(); + for (id, raw) in objects(dir, &ids)? { + old.commits.insert(id, commit(&raw)); + } + let notes: Vec = (old.refs.iter().map(|x| x.0.clone())) + .filter(|n| n.starts_with("refs/notes/")) + .collect(); + for n in notes { + let rows = git(dir, &["ls-tree", "-r", &n])?; + let rows: Vec<(String, String)> = (rows.lines()) + .filter_map(|l| l.split_once('\t')) + .filter_map(|(m, p)| Some((m.rsplit(' ').next()?.to_string(), p.replace('/', "")))) + .collect(); + let blobs: Vec = rows.iter().map(|x| x.0.clone()).collect(); + let text: HashMap = objects(dir, &blobs)?.into_iter().collect(); + for (b, c) in rows { + old.notes + .push((n.clone(), c, text.get(&b).cloned().unwrap_or_default())); + } + } + Ok(old) +} + +/// The new ids by node, and each notes ref with its new commit. +pub type Written = (Vec, Vec<(String, String)>); + +fn raw(n: &Node, ids: &[String]) -> String { + let mut s = format!("tree {}\n", n.tree); + for p in &n.parents { + s += &format!("parent {}\n", ids.get(*p).map_or("", String::as_str)); + } + format!("{s}{}\n{}\n\n{}", n.author, n.committer, n.message) +} + +/// Write the shape's commits and rebuilt notes into the copy; the new ids by node, and each notes ref's new commit. +pub fn write(dir: &Path, s: &Shape) -> Result { + let mut ids: Vec = Vec::with_capacity(s.nodes.len()); + for n in &s.nodes { + let id = git_in(dir, &["hash-object", "-t", "commit", "-w", "--stdin"], &raw(n, &ids))?; + ids.push(id.trim().to_string()); + } + let mut notes = vec![]; + for (name, rows) in &s.notes { + let mut tree = String::new(); + for (n, text) in rows { + let blob = git_in(dir, &["hash-object", "-w", "--stdin"], text)?; + tree += &format!( + "100644 blob {}\t{}\n", + blob.trim(), + ids.get(*n).map_or("", String::as_str) + ); + } + let tree = git_in(dir, &["mktree"], &tree)?; + let tip = commit(&git(dir, &["cat-file", "commit", name])?); + let n = Node { + tree: tree.trim().to_string(), + parents: vec![], + author: tip.author, + committer: tip.committer, + message: tip.message, + }; + let id = git_in(dir, &["hash-object", "-t", "commit", "-w", "--stdin"], &raw(&n, &[]))?; + notes.push((name.clone(), id.trim().to_string())); + } + Ok((ids, notes)) +} + +/// The trees of `ids` as git reads them, in order. +pub fn trees(dir: &Path, ids: &[&str]) -> Result> { + let mut out = String::new(); + for chunk in ids.chunks(CHUNK) { + let input: String = chunk.iter().map(|i| format!("{i}^{{tree}}\n")).collect(); + out += &git_in(dir, &["cat-file", "--batch-check=%(objectname)"], &input)?; + } + Ok(out.lines().map(String::from).collect()) +} diff --git a/tests/compact.rs b/tests/compact.rs new file mode 100644 index 0000000..12f4526 --- /dev/null +++ b/tests/compact.rs @@ -0,0 +1,453 @@ +use serde_json::json; +use std::path::{Path, PathBuf}; +use std::process::Command; + +const GH: &str = r#"#!/bin/sh +printf '%s\n' "$*" >> "$FAKE/gh.log" +case "$1 $2" in + "pr list") cat "$FAKE/prs.json" ;; + "repo view") echo '{"visibility": "PRIVATE"}' ;; + "repo create") ;; + "pr view") cat "$FAKE/pr-$3.json" ;; + "pr edit") printf '%s' "$7" > "$FAKE/edit-$3" ;; + *) exit 1 ;; +esac +"#; + +const DROVER: &str = r#"#!/bin/sh +case "$1 $2" in + "card post") + shift 2 + while [ $# -gt 1 ]; do + case "$1" in --cmd) cmd=$2 ;; --blast) blast=$2 ;; esac + shift 2 + done + id="r$(( $(ls "$FAKE/cards" | grep -c '\.cmd$') + 1 ))" + printf '%s' "$cmd" > "$FAKE/cards/$id.cmd" + printf '%s' "$blast" > "$FAKE/cards/$id.blast" + echo "$id" ;; + "thread show") cat "$FAKE/thread.json" ;; + "status "*) cat "$FAKE/status.json" ;; + *) exit 1 ;; +esac +"#; + +fn tmpdir(name: &str) -> PathBuf { + let d = Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn g(dir: &Path, args: &[&str]) -> String { + let o = Command::new("git") + .args([ + "-c", + "user.name=t", + "-c", + "user.email=t@t", + "-c", + "init.defaultBranch=staging", + "-C", + ]) + .arg(dir) + .args(args) + .output() + .unwrap(); + assert!( + o.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&o.stderr) + ); + String::from_utf8_lossy(&o.stdout).trim().to_string() +} + +fn commit(dir: &Path, file: &str, text: &str, msg: &str) -> String { + std::fs::write(dir.join(file), text).unwrap(); + g(dir, &["add", "."]); + g(dir, &["commit", "-qm", msg]); + g(dir, &["rev-parse", "HEAD"]) +} + +const NOTE: &str = "Decided: count twice\nOwner: the meter counts two\n"; + +struct Fake { + dir: PathBuf, + bin: PathBuf, + args: Vec, +} + +impl Fake { + fn new(dir: &Path, args: Vec) -> Fake { + let (fake, bin) = (dir.join("fake"), dir.join("bin")); + std::fs::create_dir_all(fake.join("cards")).unwrap(); + std::fs::create_dir_all(&bin).unwrap(); + for (name, text) in [("gh", GH), ("drover", DROVER)] { + let p = bin.join(name); + std::fs::write(&p, text).unwrap(); + Command::new("chmod").arg("+x").arg(&p).status().unwrap(); + } + std::fs::write(fake.join("status.json"), "[]").unwrap(); + let f = Fake { dir: fake, bin, args }; + f.thread(&[], &[]); + f + } + fn put(&self, file: &str, text: &str) { + std::fs::write(self.dir.join(file), text).unwrap(); + } + fn get(&self, file: &str) -> String { + std::fs::read_to_string(self.dir.join(file)).unwrap_or_default() + } + fn cards(&self) -> Vec<(String, String, String)> { + (1..) + .map(|n| format!("r{n}")) + .take_while(|id| self.dir.join(format!("cards/{id}.cmd")).exists()) + .map(|id| { + let (c, b) = ( + self.get(&format!("cards/{id}.cmd")), + self.get(&format!("cards/{id}.blast")), + ); + (id, c, b) + }) + .collect() + } + fn thread(&self, approved: &[&str], ran: &[&str]) { + let mut items: Vec = (self.cards().into_iter()) + .map(|(id, cmd, _)| json!({"from": "orchestrator", "card": {"id": id, "cmd": cmd}, "open": false})) + .collect(); + for id in approved { + let text = format!("run {id} approved by owner, running in /x…"); + items.push(json!({"from": "system", "text": text})); + } + for id in ran { + let text = format!("run {id} approved by owner, ran in /x: exit 0"); + items.push(json!({"from": "system", "text": text})); + } + self.put("thread.json", &json!({"thread": "t", "items": items}).to_string()); + } + fn run(&self, extra: &[&str]) -> (i32, String) { + let path = format!("{}:{}", self.bin.display(), std::env::var("PATH").unwrap()); + let o = Command::new(env!("CARGO_BIN_EXE_compact")) + .args(&self.args) + .args(extra) + .env("PATH", path) + .env("FAKE", &self.dir) + .output() + .unwrap(); + let out = String::from_utf8_lossy(&o.stdout).to_string() + &String::from_utf8_lossy(&o.stderr); + (o.status.code().unwrap_or(-1), out) + } +} + +#[test] +fn compact_keeps_every_tree_needs_a_fresh_review_and_undoes_exactly() { + let dir = tmpdir("compact-sim"); + let (origin, archive, seed, local, lane) = ( + dir.join("jirathip-dev/sendmeter"), + dir.join("jirathip-dev/sendmeter-history"), + dir.join("seed"), + dir.join("local"), + dir.join("lane"), + ); + for b in [&origin, &archive] { + g(&dir, &["init", "-q", "--bare", b.to_str().unwrap()]); + } + g(&dir, &["init", "-q", seed.to_str().unwrap()]); + g(&seed, &["remote", "add", "origin", origin.to_str().unwrap()]); + commit(&seed, "a.rs", "one\ntwo\nthree\n", "base"); + g(&seed, &["checkout", "-qb", "old-wip"]); + commit(&seed, "w.rs", "wip\n", "wip: never merged"); + g(&seed, &["checkout", "-q", "staging"]); + g(&seed, &["checkout", "-qb", "issue-5"]); + let c5 = commit(&seed, "a.rs", "ONE\ntwo\nthree\n", "a: old line"); + g( + &seed, + &["notes", "--ref", "why", "add", "-m", "Owner: the old note", &c5], + ); + g(&seed, &["checkout", "-q", "staging"]); + g(&seed, &["merge", "-q", "--no-ff", "-m", "a: old (#5) (#50)", "issue-5"]); + let cut = g(&seed, &["rev-parse", "HEAD"]); + g(&seed, &["checkout", "-qb", "issue-1"]); + commit(&seed, "a.rs", "ONE\nTWO\nthree\n", "a: two"); + g(&seed, &["checkout", "-q", "staging"]); + commit(&seed, "b.rs", "b\n", "direct: b"); + g(&seed, &["checkout", "-q", "issue-1"]); + g(&seed, &["merge", "-q", "--no-edit", "staging"]); + let l2 = commit(&seed, "c.rs", "c\n", "a: test it"); + g(&seed, &["notes", "--ref", "why", "add", "-m", NOTE.trim(), &l2]); + g(&seed, &["checkout", "-q", "staging"]); + g(&seed, &["merge", "-q", "--no-ff", "-m", "a: two (#1) (#11)", "issue-1"]); + let m1 = g(&seed, &["rev-parse", "HEAD"]); + g(&seed, &["checkout", "-qb", "main", &format!("{cut}^1")]); + g(&seed, &["merge", "-q", "--no-ff", "-m", "release", &m1]); + g(&seed, &["checkout", "-q", "staging"]); + g(&seed, &["checkout", "-qb", "issue-2"]); + commit(&seed, "d.rs", "d\n", "d: add"); + g(&seed, &["checkout", "-q", "staging"]); + commit(&seed, "e.rs", "e\n", "direct: e"); + g(&seed, &["checkout", "-q", "issue-2"]); + g(&seed, &["merge", "-q", "--no-edit", "staging"]); + let o2 = g(&seed, &["rev-parse", "HEAD"]); + let all = [ + "staging", + "main", + "issue-1", + "issue-2", + "issue-5", + "old-wip", + "refs/notes/why", + ]; + g(&seed, &[&["push", "-q", "origin"][..], &all].concat()); + g(&seed, &["push", "-q", "origin", "issue-2:refs/pull/22/head"]); + for d in [&local, &lane] { + g(&dir, &["clone", "-q", origin.to_str().unwrap(), d.to_str().unwrap()]); + } + g(&local, &["fetch", "-q", "origin", "refs/notes/why:refs/notes/why"]); + g(&lane, &["checkout", "-q", "issue-2"]); + let saved = [ + (5, &c5), + (5, &cut), + (5, &c5), + (1, &l2), + (1, &l2), + (1, &m1), + (1, &l2), + (2, &o2), + ]; + let rows: String = saved.iter().map(|(i, s)| format!("sendmeter\t{i}\t{s}\n")).collect(); + std::fs::write(dir.join("saved.tsv"), rows).unwrap(); + let (saved_file, state) = (dir.join("saved.tsv"), dir.join("state/compact")); + let args = [ + "--repo", + "jirathip-dev/sendmeter", + "--line", + "staging", + "--clone", + local.to_str().unwrap(), + "--lane", + lane.to_str().unwrap(), + "--fleet", + "sendmeter", + "--saved", + saved_file.to_str().unwrap(), + "--dir", + state.to_str().unwrap(), + ]; + let fake = Fake::new(&dir, args.map(String::from).into()); + let refs = || g(&dir, &["ls-remote", origin.to_str().unwrap()]); + let before = refs(); + let undo = before.lines().find(|l| l.ends_with("refs/heads/staging")).unwrap()[..40].to_string(); + let old_tree = g(&local, &["rev-parse", "origin/staging^{tree}"]); + let main_old = g(&local, &["rev-parse", "origin/main"]); + let main_tree = g(&local, &["rev-parse", "origin/main^{tree}"]); + let body = format!("Closes #2\n\n## Evidence (head {o2:.9})"); + let prs = json!([{"number": 22, "headRefName": "issue-2", "isCrossRepository": false}]); + fake.put("prs.json", &prs.to_string()); + fake.put("pr-22.json", &json!({"body": body}).to_string()); + + let (code, out) = fake.run(&["--cut", &cut, "--dry-run"]); + assert_eq!(code, 0, "{out}"); + assert!(out.contains("commits staging 9 → 4 (1 root + 3)"), "{out}"); + assert!(out.contains("a: two (#1) (#11) holds 3 old commits"), "{out}"); + assert!( + out.contains("#22 refs/heads/issue-2") && out.contains("Carried"), + "{out}" + ); + assert!(out.contains("Detached 1 · Merged 2 · Notes 1"), "{out}"); + assert!( + out.contains("events 2 issues to remap") && out.contains("1 lane heads held"), + "{out}" + ); + assert!(out.contains("checks tip trees equal ✓ · ready ✓"), "{out}"); + assert_eq!(refs(), before, "a dry run pushes nothing"); + let tip = |o: &str| { + o.lines() + .find_map(|l| l.strip_prefix("new tip ")) + .unwrap() + .split(' ') + .next() + .unwrap() + .to_string() + }; + let new = tip(&out); + let (_, again) = fake.run(&["--cut", &cut, "--dry-run"]); + assert_eq!(tip(&again), new, "the plan is the same on a second run"); + + let moved = out + .lines() + .find_map(|l| l.strip_prefix(&format!("main {main_old:.9} → "))); + assert!(moved.unwrap().ends_with("· its own card"), "{out}"); + + std::fs::write(lane.join("d.rs"), "changed\n").unwrap(); + fake.put("status.json", r#"[{"issue": 7, "state": "review(1)"}]"#); + let (code, out) = fake.run(&["--cut", &cut, "--thread", "t"]); + assert_eq!((code, out.contains("COMPACT_NOT_READY")), (3, true), "{out}"); + assert!( + out.contains("#7 has a check lane working (review(1))") && out.contains("1 uncommitted change(s)"), + "{out}" + ); + assert!(fake.cards().is_empty(), "no card while not ready"); + g(&lane, &["checkout", "-q", "d.rs"]); + fake.put("status.json", "[]"); + + let (code, out) = fake.run(&["--push", &new]); + assert_eq!((code, out.contains("COMPACT_UNAPPROVED")), (3, true), "{out}"); + let (code, out) = fake.run(&["--cut", &cut, "--thread", "t"]); + assert_eq!(code, 0, "{out}"); + let posted = fake.cards(); + assert_eq!(posted.len(), 2, "two separate cards: {posted:?}"); + let (line, main) = (&posted[0], &posted[1]); + let base = format!( + "compact {} --thread t", + args.iter().map(|a| a.to_string()).collect::>().join(" ") + ); + assert_eq!(line.1, format!("{base} --push {new}")); + assert!( + line.2.contains("every ref of jirathip-dev/sendmeter but main"), + "{line:?}" + ); + let main_new = main + .1 + .strip_prefix(&format!("{base} --main --push ")) + .unwrap() + .to_string(); + assert!(moved.unwrap().starts_with(&main_new[..9]), "{main:?}"); + assert!( + main.2.contains(&format!("lease on {main_old:.12}")) && main.2.contains("main-merge workflows"), + "{main:?}" + ); + let on = |b: &str| g(&dir, &["--git-dir", origin.to_str().unwrap(), "rev-parse", b]); + let t = ["--thread", "t"]; + fake.thread(&["r1"], &[]); + let (code, out) = fake.run(&[&t[..], &["--main", "--push", &main_new]].concat()); + assert_eq!( + (code, out.contains("COMPACT_UNAPPROVED")), + (3, true), + "the line's card does not cover main: {out}" + ); + fake.thread(&["r1", "r2"], &[]); + let (code, out) = fake.run(&[&t[..], &["--main", "--push", &main_new]].concat()); + assert_eq!((code, out.contains("COMPACT_NOT_READY")), (3, true), "{out}"); + assert_eq!(refs(), before, "main waits for the line's card"); + let (code, out) = fake.run(&[&t[..], &["--push", &new]].concat()); + assert_eq!(code, 0, "{out}"); + assert_eq!(on("staging"), new); + assert_eq!(on("main"), main_old, "the line's card leaves main alone"); + fake.thread(&["r1", "r2"], &["r1"]); + let (code, out) = fake.run(&[&t[..], &["--push", &new]].concat()); + assert_eq!( + (code, out.contains("COMPACT_UNAPPROVED")), + (3, true), + "a card that ran is spent: {out}" + ); + let (code, out) = fake.run(&[&t[..], &["--main", "--push", &main_new]].concat()); + assert_eq!(code, 0, "{out}"); + assert_eq!(on("main"), main_new); + assert_ne!(main_new, main_old); + assert_eq!(on("main^{tree}"), main_tree, "main's tip tree is identical"); + assert_eq!(on("main^1"), on("staging~1"), "main's release stands on the new line"); + assert_eq!(on("staging^{tree}"), old_tree, "the tip tree is identical"); + assert_eq!( + g( + &dir, + &["--git-dir", origin.to_str().unwrap(), "rev-list", "--count", "staging"] + ), + "4" + ); + assert!( + !refs().contains("refs/heads/issue-5"), + "a fully merged branch is deleted" + ); + let arc = |b: &str| g(&dir, &["--git-dir", archive.to_str().unwrap(), "rev-parse", b]); + assert_eq!(arc("staging"), undo, "the archive holds the old tip"); + assert_eq!(arc("pull/22"), o2, "and each PR head"); + assert_eq!(arc("drover-compact:compact-map.tsv").len(), 40); + let o2_new = on("issue-2"); + assert_eq!( + on("issue-2^{tree}"), + g(&seed, &["rev-parse", &format!("{o2}^{{tree}}")]) + ); + assert_eq!( + fake.get("edit-22"), + format!("Closes #2\n\n## Evidence (head {o2_new:.9})") + ); + assert_eq!(g(&local, &["rev-parse", "HEAD"]), new, "the fleet's clone is reset"); + assert_eq!(g(&lane, &["rev-parse", "HEAD"]), o2_new, "and each lane folder"); + let records: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(dir.join("state/compact/moved.json")).unwrap()).unwrap(); + let issues: Vec = (records.as_array().unwrap().iter()) + .map(|r| r["issue"].as_u64().unwrap()) + .collect(); + assert_eq!(issues, [1, 2], "the records drover logs: {records}"); + assert_eq!(records[1]["moved"][0], json!({"from": o2, "to": o2_new, "held": []})); + assert_eq!(records[0]["moved"][0]["held"].as_array().unwrap().len(), 1); + + let (code, out) = fake.run(&["--cut", &cut, "--dry-run"]); + assert_eq!(code, 0, "{out}"); + assert!(out.contains("jirathip-dev/sendmeter is compacted at"), "{out}"); + + let (code, out) = fake.run(&["--undo", "--thread", "t"]); + assert_eq!(code, 0, "{out}"); + let posted = fake.cards(); + let undo_cmds: Vec<&str> = posted[2..].iter().map(|p| p.1.as_str()).collect(); + assert_eq!( + undo_cmds, + [ + format!("{base} --undo --push {undo}"), + format!("{base} --undo --main --push {main_old}") + ] + ); + fake.thread(&["r1", "r2", "r3"], &["r1", "r2"]); + let (code, out) = fake.run(&[&t[..], &["--undo", "--push", &undo]].concat()); + assert_eq!(code, 0, "{out}"); + assert_eq!(on("main"), main_new, "the line's undo leaves main alone"); + fake.thread(&["r1", "r2", "r3", "r4"], &["r1", "r2", "r3"]); + let (code, out) = fake.run(&[&t[..], &["--undo", "--main", "--push", &main_old]].concat()); + assert_eq!(code, 0, "{out}"); + assert_eq!(refs(), before, "undo restores the old tip and every ref exactly"); + assert_eq!( + std::fs::read_to_string(dir.join("state/compact/undone")) + .unwrap() + .trim(), + new + ); + assert_eq!(g(&local, &["rev-parse", "HEAD"]), undo, "the clone is reset back"); +} + +#[test] +fn a_cut_date_with_no_commit_before_it_is_refused() { + let dir = tmpdir("compact-date"); + let (origin, local) = (dir.join("o/r"), dir.join("local")); + g(&dir, &["init", "-q", "--bare", origin.to_str().unwrap()]); + g( + &dir, + &["clone", "-q", origin.to_str().unwrap(), local.to_str().unwrap()], + ); + commit(&local, "a", "a\n", "base"); + g(&local, &["push", "-q", "origin", "HEAD:staging"]); + let state = dir.join("state"); + let args = [ + "--repo", + "o/r", + "--line", + "staging", + "--clone", + local.to_str().unwrap(), + "--dir", + state.to_str().unwrap(), + ]; + let fake = Fake::new(&dir, args.map(String::from).into()); + fake.put("prs.json", "[]"); + let (code, out) = fake.run(&["--cut", "1990-01-01", "--dry-run"]); + assert_eq!( + ( + code, + out.contains("REFUSED BAD_VALUE: no commit on staging before 1990-01-01") + ), + (3, true), + "{out}" + ); + let (code, out) = fake.run(&["--cut", "2090-01-01", "--dry-run"]); + assert_eq!(code, 0, "{out}"); + assert!(out.contains("commits staging 1 → 1 (1 root + 0)"), "{out}"); +}