diff --git a/CHANGELOG.md b/CHANGELOG.md index 72a40a78..af6f1bc0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 asks once per branch, with the same answer. On a kinisi_ros clone with 36 branches that check fell from 146 `git` spawns and 20 s to 8 spawns and 0.5 s ([#720](https://github.com/blooop/devlaunch/pull/720)). +- **The squash rule no longer merges pairs that cannot pass.** It merged every + point of a branch into every remote ref it compares with, and on a kinisi_ros clone + one `dl --ls` row made 824 merges, none of which could pass. One `git rev-parse` of + the merge bases and one `git diff-tree` of the changed paths now rule those pairs out + first, and any failure of either merges every pair as before. On that clone the rule + fell from 18–20 s to 4–6 s, with the same answer + ([#721](https://github.com/blooop/devlaunch/pull/721)). ## [0.64.3] - 2026-11-18 diff --git a/rust/devlaunch-core/src/clients/git.rs b/rust/devlaunch-core/src/clients/git.rs index af70694c..de9ffdec 100644 --- a/rust/devlaunch-core/src/clients/git.rs +++ b/rust/devlaunch-core/src/clients/git.rs @@ -1133,6 +1133,78 @@ impl<'r> Git<'r> { }) } + /// The merge bases of each of *pairs*, with the commit its remote ref + /// names, in the order of *pairs*; `None` when the output is not one + /// answer per pair. + /// + /// One `rev-parse ...` per pair, all in one spawn. For a + /// symmetric range `rev-parse` prints the right side, the left side and then + /// each merge base with a `^` before it. Those are the bases `merge-base + /// --all` gives, the ones [`Git::holds_the_change_of`] asks for, so the + /// squash rule can tell before any merge that a pair with two bases, or a + /// ref with no change of its own since its base, cannot pass. + pub(crate) fn merge_bases_of( + &self, + clone: &Path, + pairs: &[(&str, &RemoteRef)], + ) -> GitAnswer>> { + if pairs.is_empty() { + return GitAnswer::Said(Some(Vec::new())); + } + let ranges: Vec = pairs + .iter() + .map(|(point, other)| format!("{}...{point}", other.as_str())) + .collect(); + let mut args = vec!["rev-parse"]; + args.extend(ranges.iter().map(String::as_str)); + self.about(clone, &args) + .map(|stdout| pair_bases_in(&stdout, pairs)) + } + + /// The paths each of *diffs* changes, `(commit, base)` read as the change + /// from *base* to *commit*, in the order of *diffs*; `None` when the output + /// is not one answer per diff. + /// + /// One `diff-tree --stdin` for all of them: a line ` ` names + /// *base* as the commit's one parent, whatever its real parents are. `-r` + /// lists files, not directories, and `--no-renames` lists a rename as the + /// path it left and the path it took. `--always` prints the commit's line + /// even for an empty diff, so every diff is accounted for, and `-z` ends + /// each field with a NUL, so no path is quoted. + pub(crate) fn paths_changed( + &self, + clone: &Path, + diffs: &[(&str, &str)], + ) -> GitAnswer>>> { + if diffs.is_empty() { + return GitAnswer::Said(Some(Vec::new())); + } + let lines: String = diffs + .iter() + .map(|(commit, base)| format!("{commit} {base}\n")) + .collect(); + let Some(input) = tempfile::NamedTempFile::new() + .ok() + .filter(|file| std::fs::write(file.path(), &lines).is_ok()) + else { + return GitAnswer::Said(None); + }; + let args = [ + "diff-tree", + "--stdin", + "-r", + "--no-renames", + "--name-status", + "-z", + "--always", + ]; + let spec = SpawnSpec::new(pinned(clone, &args)) + .with_timeout(ABOUT_ONE_REPO) + .with_stdin_file(input.path()); + self.captured(&args.join(" "), &spec) + .map(|stdout| paths_changed_in(&stdout, diffs)) + } + /// How *clone* merges as text, or `None` when it cannot: an /// `info/attributes` that could name a merge driver, or objects named in a /// format [`empty_tree_of`] does not know. @@ -2354,6 +2426,96 @@ fn commit_graph_in(output: &str) -> Option { Some(graph) } +/// What [`Git::merge_bases_of`] found for one pair: the commit its remote ref +/// names, and its merge bases, none, one or more. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct PairBases { + pub(crate) other: String, + pub(crate) bases: Vec, +} + +/// What a diff did to one path, as far as the squash rule cares: whether the +/// path is new, gone, or there on both sides. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Change { + Added, + Deleted, + /// Modified, or its type changed. + Altered, +} + +/// One path a diff changed, and how. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct PathChange { + pub(crate) change: Change, + pub(crate) path: String, +} + +/// Whether *word* is a full object name, SHA-1 or SHA-256. +fn is_full_hash(word: &str) -> bool { + matches!(word.len(), 40 | 64) && word.bytes().all(|byte| byte.is_ascii_hexdigit()) +} + +/// The bases of each of *pairs* in `rev-parse ...` output: the +/// point, the ref's commit and a `^` line per base, pair after pair. +/// `None` for output of any other shape, a point that is not the one asked +/// for included. +fn pair_bases_in(output: &str, pairs: &[(&str, &RemoteRef)]) -> Option> { + let mut lines = output.lines().peekable(); + let mut found = Vec::with_capacity(pairs.len()); + for (point, _) in pairs { + if lines.next()? != *point { + return None; + } + let other = lines.next().filter(|other| is_full_hash(other))?; + let mut bases = Vec::new(); + while let Some(base) = lines.peek().and_then(|line| line.strip_prefix('^')) { + if !is_full_hash(base) { + return None; + } + bases.push(base.to_owned()); + lines.next(); + } + found.push(PairBases { + other: other.to_owned(), + bases, + }); + } + lines.next().is_none().then_some(found) +} + +/// The paths each of *diffs* changes in `diff-tree --stdin -z --always +/// --name-status` output: each diff's commit, then a status and a path per +/// changed path, every field ended by a NUL. `None` for output of any other +/// shape. +fn paths_changed_in(output: &str, diffs: &[(&str, &str)]) -> Option>> { + let mut fields = output.split('\0'); + let mut found: Vec> = Vec::with_capacity(diffs.len()); + let mut field = fields.next()?; + for (commit, _) in diffs { + if field != *commit { + return None; + } + let mut changed = Vec::new(); + loop { + field = fields.next()?; + let change = match field { + "A" => Change::Added, + "D" => Change::Deleted, + "M" | "T" => Change::Altered, + _ => break, + }; + let path = fields.next().filter(|path| !path.is_empty())?; + changed.push(PathChange { + change, + path: path.to_owned(), + }); + } + found.push(changed); + } + (field.is_empty() && fields.next().is_none()).then_some(found) +} + /// What [`Git::text_merge`] found a clone can merge with: the `--attr-source` /// that names the empty tree in the clone's object format. #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/rust/devlaunch-core/src/clients/git/tests.rs b/rust/devlaunch-core/src/clients/git/tests.rs index 6e089d4d..3aaa774f 100644 --- a/rust/devlaunch-core/src/clients/git/tests.rs +++ b/rust/devlaunch-core/src/clients/git/tests.rs @@ -1724,3 +1724,175 @@ fn clean_merge_trees_are_read_from_merge_tree_stdin_output() { assert_eq!(clean_merge_trees_in("1\0aaa\0", 1), None); assert_eq!(clean_merge_trees_in("", 1), None); } + +const POINT: &str = "1111111111111111111111111111111111111111"; +const REF_AT: &str = "2222222222222222222222222222222222222222"; +const BASE: &str = "3333333333333333333333333333333333333333"; +const OTHER_BASE: &str = "4444444444444444444444444444444444444444"; + +#[test] +fn the_squash_rule_asks_every_pair_s_bases_in_one_rev_parse() { + // `...`, the ref on the left, so `rev-parse` prints the point + // first: that is the order `pair_bases_in` reads. + let (dir, _root) = a_clone(); + let fake = ScriptedRunner::new(); + let feature = RemoteRef::of("origin", "feature"); + let main = RemoteRef::of("origin", "main"); + + Git::new(&fake).merge_bases_of(dir.path(), &[(POINT, &feature), (BASE, &main)]); + + assert_eq!( + strs(&argv(&fake))[3..], + [ + "rev-parse", + &format!("refs/remotes/origin/feature...{POINT}"), + &format!("refs/remotes/origin/main...{BASE}"), + ] + ); +} + +#[test] +fn the_squash_rule_asks_every_change_in_one_diff_tree() { + // `--no-renames`: a rename is the path it left and the path it took, both + // of which the path check has to see. `--always`: an empty diff still + // prints its commit, so every diff is accounted for. + let (dir, _root) = a_clone(); + let fake = ScriptedRunner::new(); + + Git::new(&fake).paths_changed(dir.path(), &[(POINT, BASE), (REF_AT, BASE)]); + + let call = fake.only_call(); + assert_eq!( + strs(&call.argv())[3..], + [ + "diff-tree", + "--stdin", + "-r", + "--no-renames", + "--name-status", + "-z", + "--always", + ] + ); + assert!( + matches!( + call.spec().map(|spec| &spec.stdin), + Some(crate::runner::StdinPlan::File(_)) + ), + "the ` ` lines go in on stdin" + ); +} + +#[test] +fn nothing_to_ask_spawns_nothing() { + let (dir, _root) = a_clone(); + let fake = ScriptedRunner::new(); + let git = Git::new(&fake); + + assert_eq!( + git.merge_bases_of(dir.path(), &[]).said(), + Some(Some(vec![])) + ); + assert_eq!( + git.paths_changed(dir.path(), &[]).said(), + Some(Some(vec![])) + ); + assert!(fake.calls().is_empty()); +} + +#[test] +fn merge_bases_are_read_from_rev_parse_symmetric_range_output() { + let feature = RemoteRef::of("origin", "feature"); + let pairs = [(POINT, &feature), (POINT, &feature), (POINT, &feature)]; + // One base, two bases, and none (histories with no common commit). + let output = format!( + "{POINT}\n{REF_AT}\n^{BASE}\n\ + {POINT}\n{REF_AT}\n^{BASE}\n^{OTHER_BASE}\n\ + {POINT}\n{REF_AT}\n" + ); + let bases = |found: &[&str]| PairBases { + other: REF_AT.to_owned(), + bases: found.iter().map(|base| (*base).to_owned()).collect(), + }; + assert_eq!( + pair_bases_in(&output, &pairs), + Some(vec![bases(&[BASE]), bases(&[BASE, OTHER_BASE]), bases(&[])]) + ); + + // A SHA-256 clone names its objects in 64 digits. + let long = "a".repeat(64); + let base = "b".repeat(64); + assert_eq!( + pair_bases_in( + &format!("{long}\n{long}\n^{base}\n"), + &[(long.as_str(), &feature)] + ), + Some(vec![PairBases { + other: long.clone(), + bases: vec![base] + }]) + ); + + // Fewer answers than pairs, more, a point that is not the one asked for, a + // ref or a base that is not a full hash: no answer at all. + let one = [(POINT, &feature)]; + for (output, why) in [ + (String::new(), "nothing"), + (format!("{POINT}\n"), "no ref"), + ( + format!("{POINT}\n{REF_AT}\n{POINT}\n{REF_AT}\n"), + "a pair too many", + ), + (format!("{BASE}\n{REF_AT}\n"), "another point"), + ( + format!("{POINT}\nrefs/remotes/origin/feature\n"), + "a ref by name", + ), + (format!("{POINT}\n{REF_AT}\n^abc\n"), "a short base"), + ] { + assert_eq!(pair_bases_in(&output, &one), None, "{why}"); + } +} + +#[test] +fn changed_paths_are_read_from_diff_tree_stdin_output() { + let diffs = [(POINT, BASE), (REF_AT, BASE), (BASE, BASE)]; + // Each kind of change, a path with a space and a newline (`-z` quotes + // none), and an empty diff that `--always` still names. + let output = format!( + "{POINT}\0A\0new dir/a.txt\0D\0gone.txt\0{REF_AT}\0M\0line\nbreak.txt\0T\0link\0{BASE}\0" + ); + let change = |change: Change, path: &str| PathChange { + change, + path: path.to_owned(), + }; + assert_eq!( + paths_changed_in(&output, &diffs), + Some(vec![ + vec![ + change(Change::Added, "new dir/a.txt"), + change(Change::Deleted, "gone.txt") + ], + vec![ + change(Change::Altered, "line\nbreak.txt"), + change(Change::Altered, "link") + ], + vec![], + ]) + ); + + // A diff missing, a diff too many, another commit, a status this does not + // know (a rename `--no-renames` should have split) and a path cut short: + // no answer at all. + let one = [(POINT, BASE)]; + for (output, why) in [ + (String::new(), "nothing"), + (format!("{POINT}\0{REF_AT}\0"), "a diff too many"), + (format!("{REF_AT}\0"), "another commit"), + (format!("{POINT}\0R100\0a\0b\0"), "a rename"), + (format!("{POINT}\0A\0"), "no path"), + (format!("{POINT}\0A\0a"), "no NUL at the end"), + ] { + assert_eq!(paths_changed_in(&output, &one), None, "{why}"); + } +} diff --git a/rust/devlaunch-core/src/domain/workspace_state.rs b/rust/devlaunch-core/src/domain/workspace_state.rs index fbc67428..f1cf8b2b 100644 --- a/rust/devlaunch-core/src/domain/workspace_state.rs +++ b/rust/devlaunch-core/src/domain/workspace_state.rs @@ -72,7 +72,9 @@ use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; -use crate::clients::git::{Git, GitAnswer, LocalBranch, REFS_HEADS, RemoteRef, TagRef, TextMerge}; +use crate::clients::git::{ + Change, Git, GitAnswer, LocalBranch, PathChange, REFS_HEADS, RemoteRef, TagRef, TextMerge, +}; /// The bare cache a clone was made from, when there is one to consult. /// @@ -930,9 +932,11 @@ fn already_on_a_remote(git: &Git<'_>, clone: &Path, local_tags: &[String]) -> Ve /// It runs only when the copy rule left a commit counted, so a clone the copy /// rule accounted for pays nothing here. When it runs it pays three spawns for /// the clone and one `rev-list` per local branch, and only a branch that still -/// reaches a counted commit is merged: one more `rev-list` and one -/// `merge-tree --stdin` of up to [`LOOK_BACK`] points times its remote refs, -/// and three spawns more for each pair whose merge gives its ref's tree. A +/// reaches a counted commit is merged: one more `rev-list`, one `rev-parse` +/// and one `diff-tree` that rule out the pairs that cannot pass +/// ([`Asked::worth_merging`]), one `merge-tree --stdin` of the rest of up to +/// [`LOOK_BACK`] points times its remote refs, and three spawns more for each +/// pair whose merge gives its ref's tree. A /// pass costs one more read of the commits off every branch. The /// merges in one clone are bounded by [`MERGE_BUDGET`]. /// @@ -974,6 +978,7 @@ fn squashed_onto_a_remote( merge: &merge, ref_trees: &ref_trees, merges_left: MERGE_BUDGET, + could_pass: HashMap::new(), }; let mut cleared: HashSet = HashSet::new(); let mut held_back: HashSet = HashSet::new(); @@ -1155,13 +1160,19 @@ struct Asked<'g, 'a> { merge: &'a TextMerge, ref_trees: &'a HashMap, merges_left: usize, + /// Whether a point and a remote ref's commit could pass, for every pair + /// [`Asked::worth_merging`] has answered for. Two branches on one commit, + /// or with commits in common, ask the same pairs. + could_pass: HashMap<(String, String), bool>, } impl Asked<'_, '_> { /// The commits *branch* passes at: every unpushed commit on the highest /// passing point's first-parent line, or none. /// - /// Every point is merged into every remote ref the clone has in one + /// Every point is paired with every remote ref the clone has, and the + /// budget counts all those pairs. [`Asked::worth_merging`] drops the pairs + /// that cannot pass, the rest are merged in one /// [`Git::trees_of_clean_merges`], and only a pair whose merge gives its /// ref's tree is asked [`Git::holds_the_change_of`], the question that /// decides. @@ -1185,6 +1196,12 @@ impl Asked<'_, '_> { return HashSet::new(); } self.merges_left -= pairs.len(); + let worth = self.worth_merging(&pairs); + let pairs: Vec<(&str, &RemoteRef)> = pairs + .into_iter() + .zip(worth) + .filter_map(|(pair, worth)| worth.then_some(pair)) + .collect(); let Some(merged) = self .git .trees_of_clean_merges(self.clone, self.merge, &pairs) @@ -1214,6 +1231,116 @@ impl Asked<'_, '_> { .map(|reached| reached.into_iter().collect()) .unwrap_or_default() } + + /// Which of *pairs* could pass, in their order: `false` only for a pair + /// that [`Git::holds_the_change_of`] is sure to refuse. + /// + /// Most pairs cannot pass, and their merges are what the squash rule paid + /// for: on a kinisi_ros clone a merge of a branch hundreds of commits ahead + /// takes 20 ms to 240 ms, nearly all of it in rename detection, and one + /// `--ls` row made 824 of them. Three things rule a pair out with no merge: + /// + /// - It has no merge base, or more than one. + /// - Its base is the ref's commit, so the ref changed nothing since. + /// - The point changes a path the ref does not ([`changes_a_path_the_ref_kept`]). + /// + /// It costs one `rev-parse` for the bases and one `diff-tree` for the + /// changes of the pairs it has not answered for before. **Every failure + /// rules nothing out**: a refusal or output it cannot read leaves those + /// pairs to be merged, as they were before. + fn worth_merging(&mut self, pairs: &[(&str, &RemoteRef)]) -> Vec { + let Some(Some(found)) = self.git.merge_bases_of(self.clone, pairs).said() else { + return vec![true; pairs.len()]; + }; + let mut asked: Vec<(&str, &str)> = Vec::new(); + for ((point, _), bases) in pairs.iter().zip(&found) { + let key = ((*point).to_owned(), bases.other.clone()); + if self.could_pass.contains_key(&key) { + continue; + } + match bases.bases.as_slice() { + [base] if *base != bases.other => { + for diff in [ + (*point, base.as_str()), + (bases.other.as_str(), base.as_str()), + ] { + if !asked.contains(&diff) { + asked.push(diff); + } + } + } + _ => { + self.could_pass.insert(key, false); + } + } + } + let changed = match self.git.paths_changed(self.clone, &asked) { + GitAnswer::Said(Some(changed)) => changed, + _ => Vec::new(), + }; + let changes_of = |commit: &str, base: &str| { + asked + .iter() + .position(|diff| *diff == (commit, base)) + .and_then(|at| changed.get(at)) + }; + pairs + .iter() + .zip(&found) + .map(|((point, _), bases)| { + let key = ((*point).to_owned(), bases.other.clone()); + if let Some(could) = self.could_pass.get(&key) { + return *could; + } + let [base] = bases.bases.as_slice() else { + return true; + }; + match (changes_of(point, base), changes_of(&bases.other, base)) { + (Some(point_changes), Some(ref_changes)) => { + let could = !changes_a_path_the_ref_kept(point_changes, ref_changes); + self.could_pass.insert(key, could); + could + } + _ => true, + } + }) + .collect() + } +} + +/// Whether *point* changes a path that *other* left as it was at their +/// merge base, as [`Git::paths_changed`] lists each since that base. When it +/// does, merging the point into the ref brings that change in, so the merge +/// cannot give the ref's tree and [`Git::holds_the_change_of`] is `false`. +/// +/// **Except for a path the point adds under a directory the ref may have +/// renamed.** With `merge.directoryRenames` set to `true`, git moves a file +/// added in a directory the other side renamed into the new directory, so the +/// path the point added is not where the merge puts it. A directory can be +/// renamed only when the ref removed every file under it, so an added path +/// with a file the ref deleted somewhere above it proves nothing here and is +/// left for the merge to decide. +/// +/// Every other path in the point's change and not in the ref's comes through +/// the merge as the point has it: no rename on the ref's side starts or ends at +/// a path the ref left alone, and git takes a change made on one side only. +fn changes_a_path_the_ref_kept(point: &[PathChange], other: &[PathChange]) -> bool { + let touched: HashSet<&str> = other.iter().map(|change| change.path.as_str()).collect(); + let emptied: HashSet<&str> = other + .iter() + .filter(|change| change.change == Change::Deleted) + .flat_map(|change| directories_above(&change.path)) + .collect(); + point.iter().any(|change| { + !touched.contains(change.path.as_str()) + && !(change.change == Change::Added + && directories_above(&change.path).any(|dir| emptied.contains(dir))) + }) +} + +/// Each directory *path* is under, the top one first, with no `/` at the end. +fn directories_above(path: &str) -> impl Iterator { + path.match_indices('/').map(|(at, _)| &path[..at]) } /// The remote refs [`already_on_a_remote`] compares *branch* with, its own diff --git a/rust/devlaunch-core/src/domain/workspace_state/tests.rs b/rust/devlaunch-core/src/domain/workspace_state/tests.rs index ceb77d57..df0b45b6 100644 --- a/rust/devlaunch-core/src/domain/workspace_state/tests.rs +++ b/rust/devlaunch-core/src/domain/workspace_state/tests.rs @@ -1314,7 +1314,9 @@ fn the_squash_rule_makes_no_more_merges_than_its_budget() { // 32 branches, each on an upstream of its own with eight counted points: // each branch merges 8 points into 32 refs, 256 merges, so 16 branches fit // and the other 16 are not merged. The spawns grow with the branches, not - // with the merges. + // with the merges: a merged branch adds a `rev-parse` of its pairs' bases, + // which this fake answers with nothing, so no `diff-tree` follows and every + // pair is merged, as before the pairs were ruled out. let branches = 32; let at = |verb: &'static str| ["git", "--git-dir=/ws/.git", "--work-tree=/ws", verb]; let listing: String = (0..branches) @@ -1360,6 +1362,14 @@ fn the_squash_rule_makes_no_more_merges_than_its_budget() { .filter(|call| call.argv().iter().any(|arg| arg == "--stdin")) .count(); assert_eq!(merged, MERGE_BUDGET / (LOOK_BACK * branches)); + let bases = calls + .iter() + .filter(|call| call.argv().iter().any(|arg| arg.contains("..."))) + .count(); + assert_eq!( + bases, merged, + "one `rev-parse` of the bases per merged branch" + ); assert!( calls.len() <= 3 * branches + 3, "{} spawns for {branches} branches", @@ -1406,6 +1416,262 @@ fn a_change_measured_from_two_merge_bases_clears_nothing() { ); } +/// The one point [`scripted_squash`] counts, its remote ref's commit and their +/// base, as `rev-parse` and `diff-tree` name them. +const SQUASHED: &str = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678"; +const REF_AT: &str = "2222222222222222222222222222222222222222"; +const BASE_AT: &str = "3333333333333333333333333333333333333333"; + +/// [`scripted_squash`] with a clean merge that gives the ref's tree, so a pair +/// that is merged passes, and with `rev-parse` and `diff-tree` answering +/// *bases* and *changed* for the pair before any merge. +fn scripted_squash_ruled_by(bases: Response, changed: Response) -> ScriptedRunner { + let first = ScriptedRunner::new() + .with_script( + [ + "git", + "--git-dir=/ws/.git", + "--work-tree=/ws", + "rev-parse", + &format!("refs/remotes/origin/feature...{SQUASHED}"), + ], + bases, + ) + .with_script( + ["git", "--git-dir=/ws/.git", "--work-tree=/ws", "diff-tree"], + changed, + ); + scripted_squash_after( + first, + Response::stdout("base\n"), + Response::stdout(""), + Response::stdout("remote-tree\n"), + ) +} + +/// How many merges *fake* was asked for, `--stdin` batches and single ones. +fn merges(fake: &ScriptedRunner) -> usize { + fake.calls() + .iter() + .filter(|call| call.argv().iter().any(|arg| arg == "merge-tree")) + .count() +} + +#[test] +fn the_squash_rule_merges_no_pair_that_cannot_pass() { + // The cost this is about: on a kinisi_ros clone one `--ls` row made 824 + // merges, none of which could pass. A pair ruled out before the merge is + // not merged at all. + let counted = ["a1b2c3d squashed".to_owned()]; + let one_base = || Response::stdout(format!("{SQUASHED}\n{REF_AT}\n^{BASE_AT}\n")); + let ruled_out = [ + ( + Response::stdout(format!("{SQUASHED}\n{REF_AT}\n^{BASE_AT}\n^{SQUASHED}\n")), + Response::stdout(""), + "two merge bases", + ), + ( + Response::stdout(format!("{SQUASHED}\n{REF_AT}\n")), + Response::stdout(""), + "no merge base", + ), + ( + Response::stdout(format!("{SQUASHED}\n{REF_AT}\n^{REF_AT}\n")), + Response::stdout(""), + "a ref that changed nothing since the base", + ), + ( + one_base(), + Response::stdout(format!( + "{SQUASHED}\0A\0later.txt\0{REF_AT}\0M\0notes.txt\0" + )), + "a point that changes a path the ref kept", + ), + ]; + for (bases, changed, why) in ruled_out { + let fake = scripted_squash_ruled_by(bases, changed); + assert_eq!( + squashed_onto_a_remote(&Git::new(&fake), Path::new("/ws"), &counted, &[]), + Vec::::new(), + "{why}" + ); + assert_eq!(merges(&fake), 0, "{why}"); + } + + // The control: the ref changed the same path, so the pair is merged, and + // its pass clears the commit. The `diff-tree` answer above was read. + let same_path = scripted_squash_ruled_by( + one_base(), + Response::stdout(format!( + "{SQUASHED}\0A\0notes.txt\0{REF_AT}\0A\0notes.txt\0" + )), + ); + assert_eq!( + squashed_onto_a_remote(&Git::new(&same_path), Path::new("/ws"), &counted, &[]), + vec![SQUASHED.to_owned()] + ); + assert_eq!(merges(&same_path), 2, "the batch, then the question"); + + // **Every failure rules nothing out**: a refusal, or output in a shape this + // cannot read, from either git leaves the pair to be merged as before. + let failed = || Response::failed(128, "fatal: nope"); + for (bases, changed, why) in [ + (failed(), Response::stdout(""), "rev-parse refused"), + ( + Response::stdout("tip-tree\n"), + Response::stdout(""), + "rev-parse unreadable", + ), + (one_base(), failed(), "diff-tree refused"), + ( + one_base(), + Response::stdout("R100\0a\0b\0"), + "diff-tree unreadable", + ), + ] { + let fake = scripted_squash_ruled_by(bases, changed); + assert_eq!( + squashed_onto_a_remote(&Git::new(&fake), Path::new("/ws"), &counted, &[]), + vec![SQUASHED.to_owned()], + "{why}" + ); + assert_eq!(merges(&fake), 2, "{why}"); + } +} + +#[test] +fn a_point_that_changes_a_path_the_ref_kept_cannot_pass() { + let change = |change: Change, path: &str| PathChange { + change, + path: path.to_owned(), + }; + let added = |path: &str| change(Change::Added, path); + let deleted = |path: &str| change(Change::Deleted, path); + let altered = |path: &str| change(Change::Altered, path); + + // Paths the ref changed too are the merge's to decide. + assert!(!changes_a_path_the_ref_kept( + &[added("a.txt"), altered("src/b.rs"), deleted("c.txt")], + &[ + added("a.txt"), + altered("src/b.rs"), + deleted("c.txt"), + added("d.txt") + ], + )); + // A path the ref left alone, whatever the point did to it, comes through + // the merge as the point has it. + for point in [added("later.txt"), altered("src/b.rs"), deleted("c.txt")] { + assert!( + changes_a_path_the_ref_kept(std::slice::from_ref(&point), &[added("a.txt")]), + "{point:?}" + ); + } + // An empty change is no path at all; the merge rejects it elsewhere. + assert!(!changes_a_path_the_ref_kept(&[], &[added("a.txt")])); + + // `merge.directoryRenames=true` moves a file added under a directory the + // ref renamed, so an added path under any directory the ref deleted a file + // from is left to the merge, however deep either one is. + let renamed_old = [deleted("old/sub/a.txt"), added("new/sub/a.txt")]; + for point in ["old/new.txt", "old/sub/new.txt", "old/sub/deeper/new.txt"] { + assert!( + !changes_a_path_the_ref_kept(&[added(point)], &renamed_old), + "{point}" + ); + } + // Only an added path: a file the point altered or deleted was there at the + // base, so a ref that renamed its directory deleted that very path. + assert!(changes_a_path_the_ref_kept( + &[altered("old/kept.txt")], + &renamed_old + )); + // And only under a directory the ref deleted from: not beside it, not in a + // directory whose name starts the same, and not at the top level, which + // cannot be renamed. + for point in ["older/new.txt", "new.txt", "olden.txt"] { + assert!( + changes_a_path_the_ref_kept(&[added(point)], &renamed_old), + "{point}" + ); + } +} + +#[test] +fn real_git_answers_rule_out_pairs_before_any_merge() { + // The parsers against what git really prints, so a change of shape cannot + // quietly turn the rule off: an unreadable answer would merge every pair, + // and every one of these would come back `true`. + let fixture = Fixture::new(); + let clone = fixture.clone(); + three_commits(&clone); + squash_feature_into_main(&teammate(&fixture)); + more_commits(&clone, 1); + git(&clone, &["fetch", "-q", "origin"]); + let tip = git(&clone, &["rev-parse", "feature"]); + let squashed = git(&clone, &["rev-parse", "feature~1"]); + let main = RemoteRef::of("origin", "main"); + let feature = RemoteRef::of("origin", "feature"); + + let runner = ProcessRunner::new(); + let git = Git::new(&runner); + let merge = git + .text_merge(&clone) + .said() + .flatten() + .expect("the clone merges as text"); + let ref_trees = HashMap::new(); + let mut asked = Asked { + git: &git, + clone: &clone, + merge: &merge, + ref_trees: &ref_trees, + merges_left: MERGE_BUDGET, + could_pass: HashMap::new(), + }; + let pairs = [ + (tip.as_str(), &main), + (squashed.as_str(), &main), + (tip.as_str(), &feature), + (squashed.as_str(), &feature), + ]; + + // The tip adds `later-0.txt`, which `main` never had; the squashed commit + // is `main`'s squash; and `origin/feature` is the base of both, so it + // changed nothing since. + assert_eq!(asked.worth_merging(&pairs), [false, true, false, false]); + assert_eq!(asked.could_pass.len(), 4); +} + +#[test] +fn a_squash_that_renamed_the_directory_the_branch_added_to_is_found() { + // With `merge.directoryRenames=true` git moves `old/new.txt` to + // `new/new.txt` because `main` renamed `old/` to `new/`, and `main` already + // holds it there. The path check must leave that pair to the merge. + let fixture = Fixture::new(); + let clone = fixture.clone(); + let mate = teammate(&fixture); + git(&mate, &["checkout", "-q", "main"]); + write(&mate.join("old/a.txt"), "a file\nwith lines\nthree\n"); + commit(&mate, "old"); + git(&mate, &["push", "-q", "origin", "main"]); + git(&clone, &["fetch", "-q", "origin"]); + git(&clone, &["checkout", "-q", "-b", "work", "origin/main"]); + write(&clone.join("old/new.txt"), "new\n"); + commit(&clone, "new"); + git(&mate, &["mv", "old", "new"]); + write(&mate.join("new/new.txt"), "new\n"); + commit(&mate, "rename old, with new (#4)"); + git(&mate, &["push", "-q", "origin", "main"]); + git(&clone, &["fetch", "-q", "origin"]); + + // git's default, `conflict`, stops the merge, so the commit stays counted. + assert_eq!(would_lose(&held(&clone)), "1 unpushed commit(s)"); + + git(&clone, &["config", "merge.directoryRenames", "true"]); + assert_eq!(held(&clone), Unsaved::NothingToLose); +} + #[test] fn refs_that_are_not_branches_git_will_not_list_clear_nothing() { // What was not read may reach the commit, so a passing branch clears