| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Landing a change on a branch: fast-forward when the change was built on |
| 5 | //! the head, otherwise rebase it onto the head path by path. |
| 6 | //! |
| 7 | //! The rebase looks at files, as the change list does. For each path the |
| 8 | //! change touches, it compares the file in the change's base (B), on the head |
| 9 | //! (H, "ours") and in the change (C, "theirs"); a directory counts as no |
| 10 | //! file. If H left the file as it was in B, C's value is taken; if H already |
| 11 | //! has C's value, there is nothing to do; otherwise both changed it, and only |
| 12 | //! two regular files can still be merged, line by line. |
| 13 | //! |
| 14 | //! Braid is stricter than git about the structure around those files. These |
| 15 | //! are conflicts too: |
| 16 | //! |
| 17 | //! - a file against a directory: C sets a file where H has a directory, or |
| 18 | //! sets something below a path that H made a file; |
| 19 | //! - a directory that existed in B, removed by one side while the other added |
| 20 | //! a file under it; |
| 21 | //! - a name that C adds next to a name that H added, when the two differ only |
| 22 | //! in letter case or Unicode normalisation. |
| 23 | //! |
| 24 | //! The directory rule applies in both directions, so two changes that touch |
| 25 | //! unrelated paths land the same whichever goes first. |
| 26 | |
| 27 | use std::collections::{BTreeSet, HashMap, HashSet}; |
| 28 | use std::rc::Rc; |
| 29 | |
| 30 | use braid_format::{ |
| 31 | Change, ChangeOp, ChangesetParts, Entry, EntryKind, Kind, ObjectId, Objects, Signature, |
| 32 | }; |
| 33 | use unicode_normalization::UnicodeNormalization; |
| 34 | |
| 35 | use crate::access::{Found, Trees, read_blob, read_changes, read_changeset}; |
| 36 | use crate::ancestry::all_ancestors; |
| 37 | use crate::apply::{Applied, apply_sorted, write_nodes}; |
| 38 | use crate::commit::store_assembled; |
| 39 | use crate::diff::diff_trees; |
| 40 | use crate::error::{ApplyProblem, Error, store_error}; |
| 41 | use crate::merge::{ConflictHunk, MergeResult, merge3}; |
| 42 | use crate::path::{check_depth, join}; |
| 43 | |
| 44 | /// The extra field a rebased changeset carries: the id, in hex, of the |
| 45 | /// changeset it was rebased from. |
| 46 | pub const REBASED_FROM: &[u8] = b"rebased-from"; |
| 47 | |
| 48 | /// The extra field naming the agent that made a changeset: its label, as |
| 49 | /// the command line's `--agent` gives it. A rebased changeset keeps the |
| 50 | /// original's, as it keeps every extra field but [`REBASED_FROM`], so the |
| 51 | /// field names the agent that made the change, wherever it landed. |
| 52 | pub const AGENT: &[u8] = b"agent"; |
| 53 | |
| 54 | /// The extra field a revert carries: the id, in hex, of the changeset it |
| 55 | /// undoes. A rebased revert keeps it, as it keeps every extra field but |
| 56 | /// [`REBASED_FROM`]. It says what the revert undoes; it proves nothing about |
| 57 | /// who made it. |
| 58 | pub const REVERTS: &[u8] = b"reverts"; |
| 59 | |
| 60 | /// What landing a change does to the branch. |
| 61 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 62 | pub enum LandOutcome { |
| 63 | /// The change was built on the head: the branch moves to the change |
| 64 | /// itself. |
| 65 | FastForward(ObjectId), |
| 66 | /// The change was rebased onto the head as a new, stored changeset; the |
| 67 | /// branch moves to it. |
| 68 | Rebased { |
| 69 | /// The new changeset. |
| 70 | changeset: ObjectId, |
| 71 | /// The paths both sides changed, merged line by line or by kind. |
| 72 | merged_paths: Vec<Vec<u8>>, |
| 73 | }, |
| 74 | /// The head already has everything the change does: the change itself, |
| 75 | /// or a changeset rebased from it, is on the head's first-parent chain, |
| 76 | /// or, rebased, it would change no file and every parent it has besides |
| 77 | /// its base is already an ancestor of the head. Nothing was stored. |
| 78 | AlreadyApplied, |
| 79 | /// The change conflicts with the head. Nothing was stored, and the branch |
| 80 | /// does not move. |
| 81 | Conflicts(Vec<Conflict>), |
| 82 | } |
| 83 | |
| 84 | /// One conflict found while rebasing a change onto the head. |
| 85 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 86 | pub struct Conflict { |
| 87 | /// Where the conflict is. |
| 88 | pub path: Vec<u8>, |
| 89 | /// What kind of conflict it is. |
| 90 | pub kind: ConflictKind, |
| 91 | /// The entry at `path` in the base of the change. |
| 92 | pub base: Option<EntryKind>, |
| 93 | /// The entry at `path` on the head of the branch. |
| 94 | pub ours: Option<EntryKind>, |
| 95 | /// The entry at `path` in the change being landed. |
| 96 | pub theirs: Option<EntryKind>, |
| 97 | } |
| 98 | |
| 99 | /// The kinds of conflict. |
| 100 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 101 | #[non_exhaustive] |
| 102 | pub enum ConflictKind { |
| 103 | /// Both sides changed the content, and the changes overlap. A conflict |
| 104 | /// on binary files, symlink targets or gitlinks has no hunks. |
| 105 | Content { |
| 106 | /// The conflicting regions of a text file. |
| 107 | hunks: Vec<ConflictHunk>, |
| 108 | }, |
| 109 | /// One side deleted the file, the other changed it. |
| 110 | ModifyDelete, |
| 111 | /// The sides disagree on what the path is: a regular file, an executable, |
| 112 | /// a symlink or a gitlink, and the base does not settle it. |
| 113 | Mode, |
| 114 | /// A file on one side, a directory on the other. |
| 115 | DirectoryFile, |
| 116 | /// A directory that existed in the base was removed on one side, and the |
| 117 | /// other side added the file at `path` under it. |
| 118 | DirectoryRemoved { |
| 119 | /// The removed directory. |
| 120 | directory: Vec<u8>, |
| 121 | }, |
| 122 | /// The change adds a name that differs only in letter case or Unicode |
| 123 | /// normalisation from a name the head added at `existing`. |
| 124 | Case { |
| 125 | /// The path of the name already on the head. |
| 126 | existing: Vec<u8>, |
| 127 | }, |
| 128 | } |
| 129 | |
| 130 | impl ConflictKind { |
| 131 | /// A short, stable name for the kind, for reports and JSON: |
| 132 | /// `CONTENT`, `MODIFY_DELETE`, `MODE`, `DF`, `DIR_REMOVED` or `CASE`. |
| 133 | pub fn code(&self) -> &'static str { |
| 134 | match self { |
| 135 | ConflictKind::Content { .. } => "CONTENT", |
| 136 | ConflictKind::ModifyDelete => "MODIFY_DELETE", |
| 137 | ConflictKind::Mode => "MODE", |
| 138 | ConflictKind::DirectoryFile => "DF", |
| 139 | ConflictKind::DirectoryRemoved { .. } => "DIR_REMOVED", |
| 140 | ConflictKind::Case { .. } => "CASE", |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | fn rank(&self) -> u8 { |
| 145 | match self { |
| 146 | ConflictKind::Content { .. } => 0, |
| 147 | ConflictKind::ModifyDelete => 1, |
| 148 | ConflictKind::Mode => 2, |
| 149 | ConflictKind::DirectoryFile => 3, |
| 150 | ConflictKind::DirectoryRemoved { .. } => 4, |
| 151 | ConflictKind::Case { .. } => 5, |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /// Lands `change` on a branch whose head is `head` (`None` for a branch |
| 157 | /// without changesets). |
| 158 | /// |
| 159 | /// The first parent of `change` is its base. The base must be on the head's |
| 160 | /// first-parent chain, or else the branch is empty and the change has no |
| 161 | /// parents; otherwise this fails with [`Error::BaseNotOnBranch`]. |
| 162 | /// |
| 163 | /// If `change` is already on the head's first-parent chain, or a changeset |
| 164 | /// rebased from it (one whose [`REBASED_FROM`] names it) is on the chain |
| 165 | /// above its base, it has landed before, and the outcome is |
| 166 | /// [`AlreadyApplied`](LandOutcome::AlreadyApplied): a request sent again |
| 167 | /// after a lost answer never lands twice. |
| 168 | /// If its base is the head, the branch fast-forwards to `change`, whatever it |
| 169 | /// contains. Otherwise the change is rebased onto the head: the new changeset |
| 170 | /// has the parents `[head] + change.parents[1..]`, the merged tree, the change |
| 171 | /// list against the head, the author, message and extra fields of `change` |
| 172 | /// (with [`REBASED_FROM`] naming it), and `committer`. When the merged tree is |
| 173 | /// the head's own, the outcome is `AlreadyApplied` only if every parent of |
| 174 | /// `change` after the first is already an ancestor of the head; otherwise the |
| 175 | /// new changeset is made anyway, with an empty change list, so that a merge |
| 176 | /// keeps its ancestry. Blobs, directories and the changeset are stored only |
| 177 | /// when the outcome is [`Rebased`](LandOutcome::Rebased). |
| 178 | /// |
| 179 | /// This decides and writes objects, but does not move the branch: the caller |
| 180 | /// runs it inside its serialized section for the branch and publishes the |
| 181 | /// outcome. The cost follows the size of the change, except for two walks of |
| 182 | /// history: the one that checks the base, which follows its distance from the |
| 183 | /// head, and, for a merge that changes no file, the one that looks for its |
| 184 | /// other parents among the head's ancestors. |
| 185 | pub fn land<O: Objects>( |
| 186 | objects: &O, |
| 187 | head: Option<ObjectId>, |
| 188 | change: ObjectId, |
| 189 | committer: Signature, |
| 190 | ) -> Result<LandOutcome, Error> { |
| 191 | let theirs = read_changeset(objects, change)?; |
| 192 | let (head_id, base_id) = match (head, theirs.parents.first().copied()) { |
| 193 | (Some(head), _) if head == change => return Ok(LandOutcome::AlreadyApplied), |
| 194 | (None, None) => return Ok(LandOutcome::FastForward(change)), |
| 195 | (Some(head), Some(base)) if head == base => return Ok(LandOutcome::FastForward(change)), |
| 196 | (Some(head), Some(base)) => match locate(objects, head, base, change)? { |
| 197 | OnChain::Base => (head, base), |
| 198 | // Landed already, by a fast-forward or a rebase: nothing to do |
| 199 | // again. |
| 200 | OnChain::Change => return Ok(LandOutcome::AlreadyApplied), |
| 201 | OnChain::Neither => { |
| 202 | return Err(Error::BaseNotOnBranch { |
| 203 | base: Some(base), |
| 204 | head: Some(head), |
| 205 | }); |
| 206 | } |
| 207 | }, |
| 208 | (head, base) => return Err(Error::BaseNotOnBranch { base, head }), |
| 209 | }; |
| 210 | let ours = read_changeset(objects, head_id)?; |
| 211 | let base = read_changeset(objects, base_id)?; |
| 212 | |
| 213 | let changes = read_changes(objects, change, &theirs)?; |
| 214 | // Every walk below follows these paths: refuse deep ones first. |
| 215 | for item in changes.iter() { |
| 216 | check_depth(&item.path)?; |
| 217 | } |
| 218 | let mut rebase = Rebase::new(objects, base.root, ours.root, theirs.root); |
| 219 | for item in changes.iter() { |
| 220 | rebase.path(item)?; |
| 221 | } |
| 222 | let applied = rebase.structure()?; |
| 223 | if !rebase.conflicts.is_empty() { |
| 224 | return Ok(LandOutcome::Conflicts(rebase.into_conflicts())); |
| 225 | } |
| 226 | if applied.root == ours.root && all_ancestors(objects, &theirs.parents[1..], head_id)? { |
| 227 | return Ok(LandOutcome::AlreadyApplied); |
| 228 | } |
| 229 | |
| 230 | for (_, bytes, ours) in &rebase.blobs { |
| 231 | objects |
| 232 | .put_similar(Kind::Blob, bytes, ours) |
| 233 | .map_err(store_error)?; |
| 234 | } |
| 235 | write_nodes(objects, &applied.nodes)?; |
| 236 | let mut extras: Vec<(Vec<u8>, Vec<u8>)> = theirs |
| 237 | .extras |
| 238 | .into_iter() |
| 239 | .filter(|(key, _)| key.as_slice() != REBASED_FROM) |
| 240 | .collect(); |
| 241 | extras.push((REBASED_FROM.to_vec(), change.to_hex().into_bytes())); |
| 242 | let parents = std::iter::once(head_id) |
| 243 | .chain(theirs.parents.iter().skip(1).copied()) |
| 244 | .collect(); |
| 245 | let assembled = ChangesetParts { |
| 246 | parents, |
| 247 | root: applied.root, |
| 248 | changes: rebase.resolved, |
| 249 | author: theirs.author, |
| 250 | committer, |
| 251 | message: theirs.message, |
| 252 | extras, |
| 253 | git_origin: None, |
| 254 | } |
| 255 | .assemble() |
| 256 | .map_err(Error::Assemble)?; |
| 257 | store_assembled(objects, &assembled)?; |
| 258 | Ok(LandOutcome::Rebased { |
| 259 | changeset: assembled.id, |
| 260 | merged_paths: rebase.merged, |
| 261 | }) |
| 262 | } |
| 263 | |
| 264 | /// What the walk down the head's first-parent chain meets first. |
| 265 | enum OnChain { |
| 266 | /// The change's base. |
| 267 | Base, |
| 268 | /// The change itself, or a changeset rebased from it; either is above |
| 269 | /// its base. |
| 270 | Change, |
| 271 | /// Neither, down to the first changeset. |
| 272 | Neither, |
| 273 | } |
| 274 | |
| 275 | /// Walks the first parents of `head` until it meets `base`, `change`, or a |
| 276 | /// changeset rebased from `change`. The cost follows the distance from the |
| 277 | /// head to the base. |
| 278 | fn locate<O: Objects>( |
| 279 | objects: &O, |
| 280 | head: ObjectId, |
| 281 | base: ObjectId, |
| 282 | change: ObjectId, |
| 283 | ) -> Result<OnChain, Error> { |
| 284 | let origin = change.to_hex().into_bytes(); |
| 285 | let mut current = head; |
| 286 | loop { |
| 287 | if current == change { |
| 288 | return Ok(OnChain::Change); |
| 289 | } |
| 290 | if current == base { |
| 291 | return Ok(OnChain::Base); |
| 292 | } |
| 293 | let changeset = read_changeset(objects, current)?; |
| 294 | if changeset |
| 295 | .extras |
| 296 | .iter() |
| 297 | .any(|(key, value)| key.as_slice() == REBASED_FROM && *value == origin) |
| 298 | { |
| 299 | return Ok(OnChain::Change); |
| 300 | } |
| 301 | match changeset.parents.first() { |
| 302 | Some(parent) => current = *parent, |
| 303 | None => return Ok(OnChain::Neither), |
| 304 | } |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | /// A regular file: its blob, size and executable bit. |
| 309 | #[derive(Clone, Copy)] |
| 310 | struct Regular { |
| 311 | blob: ObjectId, |
| 312 | size: u64, |
| 313 | executable: bool, |
| 314 | } |
| 315 | |
| 316 | impl Regular { |
| 317 | fn of(kind: &EntryKind) -> Option<Self> { |
| 318 | match kind { |
| 319 | EntryKind::File { blob, size } => Some(Regular { |
| 320 | blob: *blob, |
| 321 | size: *size, |
| 322 | executable: false, |
| 323 | }), |
| 324 | EntryKind::Executable { blob, size } => Some(Regular { |
| 325 | blob: *blob, |
| 326 | size: *size, |
| 327 | executable: true, |
| 328 | }), |
| 329 | _ => None, |
| 330 | } |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | /// The file part of an entry: `None` for a directory. |
| 335 | fn file(entry: Option<&EntryKind>) -> Option<EntryKind> { |
| 336 | entry |
| 337 | .filter(|kind| !matches!(kind, EntryKind::Tree { .. })) |
| 338 | .cloned() |
| 339 | } |
| 340 | |
| 341 | /// A name as file systems that ignore case and normalisation compare it: |
| 342 | /// Unicode NFC, lowercased. A name that is not UTF-8 is lowercased as ASCII. |
| 343 | fn fold(name: &[u8]) -> Vec<u8> { |
| 344 | match core::str::from_utf8(name) { |
| 345 | Ok(text) => text |
| 346 | .nfc() |
| 347 | .flat_map(char::to_lowercase) |
| 348 | .nfc() |
| 349 | .collect::<String>() |
| 350 | .into_bytes(), |
| 351 | Err(_) => name.to_ascii_lowercase(), |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | /// The names of one directory, by folded name. |
| 356 | type FoldedNames = HashMap<Vec<u8>, Vec<Vec<u8>>>; |
| 357 | |
| 358 | /// The state of one rebase. [`merge`](crate::merge) runs one too. |
| 359 | pub(crate) struct Rebase<'o, O> { |
| 360 | trees: Trees<'o, O>, |
| 361 | /// Root trees of the base, the head and the change. |
| 362 | base: ObjectId, |
| 363 | ours: ObjectId, |
| 364 | theirs: ObjectId, |
| 365 | /// The change list against the head, in path order. |
| 366 | pub(crate) resolved: Vec<Change>, |
| 367 | /// Paths merged from both sides. |
| 368 | pub(crate) merged: Vec<Vec<u8>>, |
| 369 | /// Merged contents to store: their id, their bytes, and the head's blob |
| 370 | /// at the same path, which they are probably close to. |
| 371 | pub(crate) blobs: Vec<(ObjectId, Vec<u8>, ObjectId)>, |
| 372 | /// Paths the change adds that had no file in the base or on the head. |
| 373 | added: Vec<Vec<u8>>, |
| 374 | /// Paths the change deletes. |
| 375 | deleted: Vec<Vec<u8>>, |
| 376 | pub(crate) conflicts: Vec<Conflict>, |
| 377 | /// For each directory of the head, its names by folded name. |
| 378 | folded: HashMap<ObjectId, Rc<FoldedNames>>, |
| 379 | /// Names the change adds that were checked for collisions already. |
| 380 | case_checked: HashSet<Vec<u8>>, |
| 381 | } |
| 382 | |
| 383 | impl<'o, O: Objects> Rebase<'o, O> { |
| 384 | pub(crate) fn new(objects: &'o O, base: ObjectId, ours: ObjectId, theirs: ObjectId) -> Self { |
| 385 | Rebase { |
| 386 | trees: Trees::new(objects), |
| 387 | base, |
| 388 | ours, |
| 389 | theirs, |
| 390 | resolved: Vec::new(), |
| 391 | merged: Vec::new(), |
| 392 | blobs: Vec::new(), |
| 393 | added: Vec::new(), |
| 394 | deleted: Vec::new(), |
| 395 | conflicts: Vec::new(), |
| 396 | folded: HashMap::new(), |
| 397 | case_checked: HashSet::new(), |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | /// Records a conflict at `path`, with what each side has there. |
| 402 | fn conflict(&mut self, path: &[u8], kind: ConflictKind) -> Result<(), Error> { |
| 403 | let base = self.trees.find(self.base, path)?.into_entry(); |
| 404 | let ours = self.trees.find(self.ours, path)?.into_entry(); |
| 405 | let theirs = self.trees.find(self.theirs, path)?.into_entry(); |
| 406 | self.conflicts.push(Conflict { |
| 407 | path: path.to_vec(), |
| 408 | kind, |
| 409 | base, |
| 410 | ours, |
| 411 | theirs, |
| 412 | }); |
| 413 | Ok(()) |
| 414 | } |
| 415 | |
| 416 | /// Resolves one path of the change list. |
| 417 | pub(crate) fn path(&mut self, change: &Change) -> Result<(), Error> { |
| 418 | let path = change.path.as_slice(); |
| 419 | if matches!(change.op, ChangeOp::Delete) { |
| 420 | self.deleted.push(path.to_vec()); |
| 421 | } |
| 422 | let in_base = self.trees.find(self.base, path)?; |
| 423 | let in_ours = self.trees.find(self.ours, path)?; |
| 424 | let base_file = file(in_base.entry()); |
| 425 | let ours_file = file(in_ours.entry()); |
| 426 | let theirs_file = change.op.to_entry(); |
| 427 | |
| 428 | if theirs_file == ours_file { |
| 429 | // The head already has the change's value. |
| 430 | return Ok(()); |
| 431 | } |
| 432 | if base_file == ours_file { |
| 433 | // The head left this file alone: take the change's value. |
| 434 | if base_file.is_none() { |
| 435 | self.added.push(path.to_vec()); |
| 436 | } |
| 437 | self.resolved.push(change.clone()); |
| 438 | return Ok(()); |
| 439 | } |
| 440 | // Both sides changed this file, differently. |
| 441 | match (ours_file, theirs_file) { |
| 442 | (Some(ours), Some(theirs)) => self.merge(path, base_file, ours, theirs), |
| 443 | (None, Some(_)) => match in_ours { |
| 444 | // The head replaced the file with a directory. |
| 445 | Found::Entry(EntryKind::Tree { .. }) => { |
| 446 | self.conflict(path, ConflictKind::DirectoryFile) |
| 447 | } |
| 448 | // The head made a directory above it a file. |
| 449 | Found::Blocked(at) => self.conflict(&path[..at], ConflictKind::DirectoryFile), |
| 450 | _ => self.conflict(path, ConflictKind::ModifyDelete), |
| 451 | }, |
| 452 | (Some(_), None) | (None, None) => self.conflict(path, ConflictKind::ModifyDelete), |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | /// Both sides changed the file at `path` to different entries. |
| 457 | fn merge( |
| 458 | &mut self, |
| 459 | path: &[u8], |
| 460 | base: Option<EntryKind>, |
| 461 | ours: EntryKind, |
| 462 | theirs: EntryKind, |
| 463 | ) -> Result<(), Error> { |
| 464 | let (Some(o), Some(t)) = (Regular::of(&ours), Regular::of(&theirs)) else { |
| 465 | // Symlinks and gitlinks have no lines to merge. |
| 466 | let kind = if ours.code() == theirs.code() { |
| 467 | ConflictKind::Content { hunks: Vec::new() } |
| 468 | } else { |
| 469 | ConflictKind::Mode |
| 470 | }; |
| 471 | return self.conflict(path, kind); |
| 472 | }; |
| 473 | let b = base.as_ref().and_then(Regular::of); |
| 474 | |
| 475 | // The executable bit merges on its own: a side that kept the base's |
| 476 | // bit yields to the other. |
| 477 | let executable = match b { |
| 478 | _ if o.executable == t.executable => Some(o.executable), |
| 479 | Some(b) if b.executable == o.executable => Some(t.executable), |
| 480 | Some(b) if b.executable == t.executable => Some(o.executable), |
| 481 | _ => None, |
| 482 | }; |
| 483 | |
| 484 | let mut content = None; |
| 485 | let mut hunks = None; |
| 486 | if o.blob == t.blob { |
| 487 | content = Some((o.blob, o.size, None)); |
| 488 | } else { |
| 489 | let objects = self.trees.objects(); |
| 490 | let base_bytes = match b { |
| 491 | Some(b) => read_blob(objects, b.blob)?, |
| 492 | // Added on both sides, or a regular file on both sides only now. |
| 493 | None => Vec::new(), |
| 494 | }; |
| 495 | let ours_bytes = read_blob(objects, o.blob)?; |
| 496 | let theirs_bytes = read_blob(objects, t.blob)?; |
| 497 | match merge3(&base_bytes, &ours_bytes, &theirs_bytes) { |
| 498 | MergeResult::Clean(bytes) => { |
| 499 | let blob = ObjectId::hash(Kind::Blob, &bytes); |
| 500 | content = Some((blob, bytes.len() as u64, Some(bytes))); |
| 501 | } |
| 502 | MergeResult::Conflict { hunks: found } => hunks = Some(found), |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | if executable.is_none() { |
| 507 | self.conflict(path, ConflictKind::Mode)?; |
| 508 | } |
| 509 | if let Some(hunks) = hunks { |
| 510 | self.conflict(path, ConflictKind::Content { hunks })?; |
| 511 | } |
| 512 | let (Some(executable), Some((blob, size, bytes))) = (executable, content) else { |
| 513 | return Ok(()); |
| 514 | }; |
| 515 | let op = if executable { |
| 516 | ChangeOp::Executable { blob, size } |
| 517 | } else { |
| 518 | ChangeOp::File { blob, size } |
| 519 | }; |
| 520 | if op.to_entry().as_ref() == Some(&ours) { |
| 521 | // The merge gives what the head has. |
| 522 | return Ok(()); |
| 523 | } |
| 524 | if let Some(bytes) = bytes { |
| 525 | self.blobs.push((blob, bytes, o.blob)); |
| 526 | } |
| 527 | self.resolved.push(Change { |
| 528 | path: path.to_vec(), |
| 529 | op, |
| 530 | }); |
| 531 | self.merged.push(path.to_vec()); |
| 532 | Ok(()) |
| 533 | } |
| 534 | |
| 535 | /// Checks the structure around the resolved changes, applies them to the |
| 536 | /// head without storing anything, and turns structural problems into |
| 537 | /// conflicts. |
| 538 | pub(crate) fn structure(&mut self) -> Result<Applied, Error> { |
| 539 | self.removed_under_added()?; |
| 540 | self.added_under_removed()?; |
| 541 | let sets: Vec<Vec<u8>> = self |
| 542 | .resolved |
| 543 | .iter() |
| 544 | .filter(|change| !matches!(change.op, ChangeOp::Delete)) |
| 545 | .map(|change| change.path.clone()) |
| 546 | .collect(); |
| 547 | for path in sets { |
| 548 | self.check_case(&path)?; |
| 549 | } |
| 550 | |
| 551 | let resolved = std::mem::take(&mut self.resolved); |
| 552 | let sorted: Vec<&Change> = resolved.iter().collect(); |
| 553 | let mut problems = Vec::new(); |
| 554 | let applied = apply_sorted(&mut self.trees, self.ours, &sorted, &mut problems)?; |
| 555 | self.resolved = resolved; |
| 556 | for problem in problems { |
| 557 | match problem.problem { |
| 558 | ApplyProblem::NotADirectory | ApplyProblem::DirectoryNotEmpty => { |
| 559 | self.conflict(&problem.path, ConflictKind::DirectoryFile)?; |
| 560 | } |
| 561 | // The resolved list only deletes files the head has and only |
| 562 | // sets what the head does not have, so nothing else can fail |
| 563 | // unless the change itself is not canonical. |
| 564 | _ => return Err(problem.into_error()), |
| 565 | } |
| 566 | } |
| 567 | Ok(applied) |
| 568 | } |
| 569 | |
| 570 | /// The change adds a file under a directory that existed in the base and |
| 571 | /// that the head removed. |
| 572 | fn removed_under_added(&mut self) -> Result<(), Error> { |
| 573 | for path in std::mem::take(&mut self.added) { |
| 574 | let deepest = self.trees.deepest_directory(self.base, &path)?; |
| 575 | if deepest == 0 { |
| 576 | continue; |
| 577 | } |
| 578 | let directory = &path[..deepest]; |
| 579 | if self.trees.find(self.ours, directory)? == Found::Absent { |
| 580 | self.conflict( |
| 581 | &path, |
| 582 | ConflictKind::DirectoryRemoved { |
| 583 | directory: directory.to_vec(), |
| 584 | }, |
| 585 | )?; |
| 586 | } |
| 587 | } |
| 588 | Ok(()) |
| 589 | } |
| 590 | |
| 591 | /// The change removes a directory that existed in the base, and the head |
| 592 | /// added files under it. |
| 593 | fn added_under_removed(&mut self) -> Result<(), Error> { |
| 594 | let mut removed = BTreeSet::new(); |
| 595 | for path in std::mem::take(&mut self.deleted) { |
| 596 | if let Some(len) = self.trees.first_missing_directory(self.theirs, &path)? { |
| 597 | removed.insert(path[..len].to_vec()); |
| 598 | } |
| 599 | } |
| 600 | for directory in removed { |
| 601 | let before = self.trees.find(self.base, &directory)?; |
| 602 | let after = self.trees.find(self.ours, &directory)?; |
| 603 | let ( |
| 604 | Found::Entry(EntryKind::Tree { tree: before }), |
| 605 | Found::Entry(EntryKind::Tree { tree: after }), |
| 606 | ) = (before, after) |
| 607 | else { |
| 608 | continue; |
| 609 | }; |
| 610 | for item in diff_trees(&mut self.trees, &directory, Some(before), Some(after))? { |
| 611 | if item.old.is_none() && item.new.is_some() { |
| 612 | self.conflict( |
| 613 | &item.path, |
| 614 | ConflictKind::DirectoryRemoved { |
| 615 | directory: directory.clone(), |
| 616 | }, |
| 617 | )?; |
| 618 | } |
| 619 | } |
| 620 | } |
| 621 | Ok(()) |
| 622 | } |
| 623 | |
| 624 | /// The change sets `path`. Find the first name on it that the head does |
| 625 | /// not have; if the head added a name there that folds to the same name, |
| 626 | /// the two would collide on a file system that ignores case or |
| 627 | /// normalisation. |
| 628 | fn check_case(&mut self, path: &[u8]) -> Result<(), Error> { |
| 629 | let mut dir = self.ours; |
| 630 | let mut start = 0; |
| 631 | loop { |
| 632 | let slash = path[start..].iter().position(|byte| *byte == b'/'); |
| 633 | let end = slash.map_or(path.len(), |slash| start + slash); |
| 634 | let name = &path[start..end]; |
| 635 | match (self.trees.entry(dir, name)?, slash) { |
| 636 | (Some(EntryKind::Tree { tree }), Some(_)) => { |
| 637 | dir = tree; |
| 638 | start = end + 1; |
| 639 | } |
| 640 | // The head has this name already. |
| 641 | (Some(_), _) => return Ok(()), |
| 642 | (None, _) => { |
| 643 | if !self.case_checked.insert(path[..end].to_vec()) { |
| 644 | // Another path of the change goes through this name. |
| 645 | return Ok(()); |
| 646 | } |
| 647 | let parent = &path[..start.saturating_sub(1)]; |
| 648 | // A new name is compared with every name of the |
| 649 | // directory: only now is it read whole. |
| 650 | let entries = self.trees.read(dir)?; |
| 651 | let index = self.folded_names(dir, &entries); |
| 652 | let others = index.get(&fold(name)).cloned().unwrap_or_default(); |
| 653 | for other in others { |
| 654 | // Only a name the head brought counts: one already in |
| 655 | // the base, or one the change has too, makes the |
| 656 | // collision the change's own. |
| 657 | let existing = join(parent, &other); |
| 658 | let in_base = self.trees.find(self.base, &existing)?; |
| 659 | let in_change = self.trees.find(self.theirs, &existing)?; |
| 660 | if in_base.entry().is_none() && in_change.entry().is_none() { |
| 661 | self.conflict(&path[..end], ConflictKind::Case { existing })?; |
| 662 | } |
| 663 | } |
| 664 | return Ok(()); |
| 665 | } |
| 666 | } |
| 667 | } |
| 668 | } |
| 669 | |
| 670 | /// The names of a directory of the head, by folded name. |
| 671 | fn folded_names(&mut self, dir: ObjectId, entries: &[Entry]) -> Rc<FoldedNames> { |
| 672 | Rc::clone(self.folded.entry(dir).or_insert_with(|| { |
| 673 | let mut index = FoldedNames::new(); |
| 674 | for entry in entries { |
| 675 | index |
| 676 | .entry(fold(&entry.name)) |
| 677 | .or_default() |
| 678 | .push(entry.name.clone()); |
| 679 | } |
| 680 | Rc::new(index) |
| 681 | })) |
| 682 | } |
| 683 | |
| 684 | /// The conflicts, sorted by path and kind, without repeats. |
| 685 | pub(crate) fn into_conflicts(self) -> Vec<Conflict> { |
| 686 | let mut conflicts = self.conflicts; |
| 687 | conflicts.sort_by(|a, b| { |
| 688 | a.path |
| 689 | .cmp(&b.path) |
| 690 | .then_with(|| a.kind.rank().cmp(&b.kind.rank())) |
| 691 | }); |
| 692 | conflicts.dedup_by(|a, b| a.path == b.path && a.kind == b.kind); |
| 693 | conflicts |
| 694 | } |
| 695 | } |
| 696 | |
| 697 | #[cfg(test)] |
| 698 | mod tests { |
| 699 | use super::*; |
| 700 | use crate::commit::{admit, store_assembled}; |
| 701 | use crate::diff::diff; |
| 702 | use crate::merge::HunkSide; |
| 703 | use crate::path::MAX_PATH_DEPTH; |
| 704 | use crate::testing::{Hinted, Repo, deep_path, delete, gitlink, signature, text_map}; |
| 705 | use braid_format::Changes; |
| 706 | |
| 707 | struct Setup { |
| 708 | repo: Repo, |
| 709 | base: ObjectId, |
| 710 | head: ObjectId, |
| 711 | change: ObjectId, |
| 712 | } |
| 713 | |
| 714 | /// A base with `files`, a head that applies `ours` to it, and a change |
| 715 | /// that applies `theirs` to it. |
| 716 | fn setup( |
| 717 | files: &[(&str, &str)], |
| 718 | ours: impl FnOnce(&Repo) -> Vec<Change>, |
| 719 | theirs: impl FnOnce(&Repo) -> Vec<Change>, |
| 720 | ) -> Setup { |
| 721 | let repo = Repo::new(); |
| 722 | let start: Vec<Change> = files.iter().map(|(p, c)| repo.set(p, c)).collect(); |
| 723 | let base = repo.commit(&[], start); |
| 724 | let head = repo.commit(&[base], ours(&repo)); |
| 725 | let change = repo.commit(&[base], theirs(&repo)); |
| 726 | Setup { |
| 727 | repo, |
| 728 | base, |
| 729 | head, |
| 730 | change, |
| 731 | } |
| 732 | } |
| 733 | |
| 734 | fn land_it(setup: &Setup) -> LandOutcome { |
| 735 | land( |
| 736 | &setup.repo.objects, |
| 737 | Some(setup.head), |
| 738 | setup.change, |
| 739 | signature("lander"), |
| 740 | ) |
| 741 | .unwrap() |
| 742 | } |
| 743 | |
| 744 | fn rebased(setup: &Setup) -> (ObjectId, Vec<Vec<u8>>) { |
| 745 | match land_it(setup) { |
| 746 | LandOutcome::Rebased { |
| 747 | changeset, |
| 748 | merged_paths, |
| 749 | } => { |
| 750 | // Whatever lands is admissible, and its list is the diff. |
| 751 | let objects = &setup.repo.objects; |
| 752 | admit(objects, changeset, |id| *id == setup.head).unwrap(); |
| 753 | let new = read_changeset(objects, changeset).unwrap(); |
| 754 | let list = read_changes(objects, changeset, &new).unwrap().into_owned(); |
| 755 | let head_root = setup.repo.root(setup.head); |
| 756 | assert_eq!(list, diff(objects, head_root, new.root).unwrap()); |
| 757 | (changeset, merged_paths) |
| 758 | } |
| 759 | other => panic!("expected a rebase, got {other:?}"), |
| 760 | } |
| 761 | } |
| 762 | |
| 763 | fn conflicts(setup: &Setup) -> Vec<(String, &'static str)> { |
| 764 | match land_it(setup) { |
| 765 | LandOutcome::Conflicts(conflicts) => conflicts |
| 766 | .iter() |
| 767 | .map(|c| (String::from_utf8(c.path.clone()).unwrap(), c.kind.code())) |
| 768 | .collect(), |
| 769 | other => panic!("expected conflicts, got {other:?}"), |
| 770 | } |
| 771 | } |
| 772 | |
| 773 | fn pairs(expected: &[(&str, &'static str)]) -> Vec<(String, &'static str)> { |
| 774 | expected |
| 775 | .iter() |
| 776 | .map(|(path, code)| (path.to_string(), *code)) |
| 777 | .collect() |
| 778 | } |
| 779 | |
| 780 | #[test] |
| 781 | fn fast_forward_when_the_base_is_the_head() { |
| 782 | let s = setup(&[("a", "1")], |r| vec![r.set("a", "2")], |_| Vec::new()); |
| 783 | let on_head = s.repo.commit(&[s.head], vec![s.repo.set("b", "3")]); |
| 784 | assert_eq!( |
| 785 | land(&s.repo.objects, Some(s.head), on_head, signature("x")).unwrap(), |
| 786 | LandOutcome::FastForward(on_head) |
| 787 | ); |
| 788 | // Even a change that changes nothing. |
| 789 | assert_eq!( |
| 790 | land(&s.repo.objects, Some(s.base), s.change, signature("x")).unwrap(), |
| 791 | LandOutcome::FastForward(s.change) |
| 792 | ); |
| 793 | // The first changeset of an empty branch. |
| 794 | let root = s.repo.commit(&[], vec![s.repo.set("r", "1")]); |
| 795 | assert_eq!( |
| 796 | land(&s.repo.objects, None, root, signature("x")).unwrap(), |
| 797 | LandOutcome::FastForward(root) |
| 798 | ); |
| 799 | } |
| 800 | |
| 801 | #[test] |
| 802 | fn landing_again_is_already_applied() { |
| 803 | let s = setup(&[("a", "1")], |r| vec![r.set("a", "2")], |_| Vec::new()); |
| 804 | let on_head = s.repo.commit(&[s.head], vec![s.repo.set("b", "3")]); |
| 805 | let objects = &s.repo.objects; |
| 806 | // The change is the head. |
| 807 | assert_eq!( |
| 808 | land(objects, Some(on_head), on_head, signature("x")).unwrap(), |
| 809 | LandOutcome::AlreadyApplied |
| 810 | ); |
| 811 | // The change is further down the first-parent chain. |
| 812 | let later = s.repo.commit(&[on_head], vec![s.repo.set("b", "4")]); |
| 813 | assert_eq!( |
| 814 | land(objects, Some(later), on_head, signature("x")).unwrap(), |
| 815 | LandOutcome::AlreadyApplied |
| 816 | ); |
| 817 | // A first changeset that is the head. |
| 818 | let root = s.repo.commit(&[], vec![s.repo.set("r", "1")]); |
| 819 | assert_eq!( |
| 820 | land(objects, Some(root), root, signature("x")).unwrap(), |
| 821 | LandOutcome::AlreadyApplied |
| 822 | ); |
| 823 | } |
| 824 | |
| 825 | #[test] |
| 826 | fn landing_again_after_a_rebase_is_already_applied() { |
| 827 | let s = setup( |
| 828 | &[("a", "1"), ("b", "1")], |
| 829 | |r| vec![r.set("a", "2")], |
| 830 | |r| vec![r.set("b", "2")], |
| 831 | ); |
| 832 | let (rebased, _) = rebased(&s); |
| 833 | let objects = &s.repo.objects; |
| 834 | assert_eq!( |
| 835 | land(objects, Some(rebased), s.change, signature("x")).unwrap(), |
| 836 | LandOutcome::AlreadyApplied |
| 837 | ); |
| 838 | // Neither a later edit of the same file nor putting it back makes |
| 839 | // the change land a second time. |
| 840 | for content in ["3", "1"] { |
| 841 | let later = s.repo.commit(&[rebased], vec![s.repo.set("b", content)]); |
| 842 | assert_eq!( |
| 843 | land(objects, Some(later), s.change, signature("x")).unwrap(), |
| 844 | LandOutcome::AlreadyApplied |
| 845 | ); |
| 846 | } |
| 847 | } |
| 848 | |
| 849 | #[test] |
| 850 | fn merges_that_change_no_file_keep_their_ancestry() { |
| 851 | let repo = Repo::new(); |
| 852 | let base = repo.commit(&[], vec![repo.set("a", "1")]); |
| 853 | let head = repo.commit(&[base], vec![repo.set("h", "1")]); |
| 854 | let side = repo.commit(&[base], vec![repo.set("s", "1")]); |
| 855 | // Merges `side` but keeps none of its files: no change against `base`. |
| 856 | let merge = commit_with_extras(&repo, vec![base, side], Vec::new(), Vec::new()); |
| 857 | let objects = &repo.objects; |
| 858 | |
| 859 | let outcome = land(objects, Some(head), merge, signature("x")).unwrap(); |
| 860 | let LandOutcome::Rebased { |
| 861 | changeset, |
| 862 | merged_paths, |
| 863 | } = outcome |
| 864 | else { |
| 865 | panic!("expected a rebase, got {outcome:?}"); |
| 866 | }; |
| 867 | assert!(merged_paths.is_empty()); |
| 868 | let new = read_changeset(objects, changeset).unwrap(); |
| 869 | assert_eq!(new.parents, [head, side]); |
| 870 | assert_eq!(new.root, repo.root(head)); |
| 871 | assert_eq!(new.changes, Changes::Inline(Vec::new())); |
| 872 | admit(objects, changeset, |id| [head, side].contains(id)).unwrap(); |
| 873 | |
| 874 | // Landed again on the new head, the merge has nothing left to add. |
| 875 | assert_eq!( |
| 876 | land(objects, Some(changeset), merge, signature("x")).unwrap(), |
| 877 | LandOutcome::AlreadyApplied |
| 878 | ); |
| 879 | // Nor has another merge of the same side, once `side` is in history. |
| 880 | let again = commit_with_extras( |
| 881 | &repo, |
| 882 | vec![base, side], |
| 883 | Vec::new(), |
| 884 | vec![(b"note".to_vec(), b"again".to_vec())], |
| 885 | ); |
| 886 | assert_eq!( |
| 887 | land(objects, Some(changeset), again, signature("x")).unwrap(), |
| 888 | LandOutcome::AlreadyApplied |
| 889 | ); |
| 890 | // A merge built on the head fast-forwards, changes or not. |
| 891 | let on_head = commit_with_extras(&repo, vec![head, side], Vec::new(), Vec::new()); |
| 892 | assert_eq!( |
| 893 | land(objects, Some(head), on_head, signature("x")).unwrap(), |
| 894 | LandOutcome::FastForward(on_head) |
| 895 | ); |
| 896 | } |
| 897 | |
| 898 | #[test] |
| 899 | fn landing_respects_the_depth_limit() { |
| 900 | let deepest = deep_path(MAX_PATH_DEPTH); |
| 901 | let s = setup( |
| 902 | &[("a", "1")], |
| 903 | |r| vec![r.set("a", "2")], |
| 904 | |r| vec![r.set(&deepest, "c")], |
| 905 | ); |
| 906 | let (id, _) = rebased(&s); |
| 907 | assert_eq!( |
| 908 | s.repo.files(s.repo.root(id)), |
| 909 | text_map(&[("a", "2"), (&deepest, "c")]) |
| 910 | ); |
| 911 | |
| 912 | // A change one name deeper, made by hand since `commit` refuses it. |
| 913 | let forged = ChangesetParts { |
| 914 | parents: vec![s.base], |
| 915 | root: s.repo.root(s.base), |
| 916 | changes: vec![s.repo.set(&deep_path(MAX_PATH_DEPTH + 1), "c")], |
| 917 | author: signature("a"), |
| 918 | committer: signature("a"), |
| 919 | message: Vec::new(), |
| 920 | extras: Vec::new(), |
| 921 | git_origin: None, |
| 922 | } |
| 923 | .assemble() |
| 924 | .unwrap(); |
| 925 | store_assembled(&s.repo.objects, &forged).unwrap(); |
| 926 | let result = land(&s.repo.objects, Some(s.head), forged.id, signature("x")); |
| 927 | assert!(matches!(result, Err(Error::TooDeep { .. })), "{result:?}"); |
| 928 | } |
| 929 | |
| 930 | #[test] |
| 931 | fn base_must_be_on_the_branch() { |
| 932 | let s = setup( |
| 933 | &[("a", "1")], |
| 934 | |r| vec![r.set("a", "2")], |
| 935 | |r| vec![r.set("b", "1")], |
| 936 | ); |
| 937 | let objects = &s.repo.objects; |
| 938 | // A change built on a changeset that is not on the branch. |
| 939 | let on_side = s.repo.commit(&[s.change], vec![s.repo.set("c", "1")]); |
| 940 | assert!(matches!( |
| 941 | land(objects, Some(s.head), on_side, signature("x")), |
| 942 | Err(Error::BaseNotOnBranch { .. }) |
| 943 | )); |
| 944 | // A change with parents on an empty branch, and a root change on a |
| 945 | // branch with a head. |
| 946 | assert!(matches!( |
| 947 | land(objects, None, s.change, signature("x")), |
| 948 | Err(Error::BaseNotOnBranch { head: None, .. }) |
| 949 | )); |
| 950 | let root = s.repo.commit(&[], vec![s.repo.set("r", "1")]); |
| 951 | assert!(matches!( |
| 952 | land(objects, Some(s.head), root, signature("x")), |
| 953 | Err(Error::BaseNotOnBranch { base: None, .. }) |
| 954 | )); |
| 955 | // A base further down the first-parent chain is fine. |
| 956 | let later = s.repo.commit(&[s.head], vec![s.repo.set("d", "1")]); |
| 957 | assert!(matches!( |
| 958 | land(objects, Some(later), s.change, signature("x")).unwrap(), |
| 959 | LandOutcome::Rebased { .. } |
| 960 | )); |
| 961 | } |
| 962 | |
| 963 | #[test] |
| 964 | fn disjoint_changes_rebase_cleanly() { |
| 965 | let s = setup( |
| 966 | &[("a", "1"), ("d/b", "2")], |
| 967 | |r| vec![r.set("a", "head"), r.set("d/new", "h")], |
| 968 | |r| vec![r.set("d/b", "change"), r.set("e/f", "c")], |
| 969 | ); |
| 970 | let (id, merged) = rebased(&s); |
| 971 | assert!(merged.is_empty()); |
| 972 | assert_eq!( |
| 973 | s.repo.files(s.repo.root(id)), |
| 974 | text_map(&[ |
| 975 | ("a", "head"), |
| 976 | ("d/b", "change"), |
| 977 | ("d/new", "h"), |
| 978 | ("e/f", "c") |
| 979 | ]) |
| 980 | ); |
| 981 | let new = read_changeset(&s.repo.objects, id).unwrap(); |
| 982 | let original = read_changeset(&s.repo.objects, s.change).unwrap(); |
| 983 | assert_eq!(new.parents, [s.head]); |
| 984 | assert_eq!(new.author, original.author); |
| 985 | assert_eq!(new.message, original.message); |
| 986 | assert_eq!(new.committer, signature("lander")); |
| 987 | assert_eq!( |
| 988 | new.extras, |
| 989 | [(REBASED_FROM.to_vec(), s.change.to_hex().into_bytes())] |
| 990 | ); |
| 991 | assert_eq!(new.git_origin, None); |
| 992 | } |
| 993 | |
| 994 | #[test] |
| 995 | fn rebasing_keeps_extra_parents_and_replaces_rebased_from() { |
| 996 | let repo = Repo::new(); |
| 997 | let base = repo.commit(&[], vec![repo.set("a", "1")]); |
| 998 | let head = repo.commit(&[base], vec![repo.set("h", "1")]); |
| 999 | let other = repo.commit(&[base], vec![repo.set("o", "1")]); |
| 1000 | let merge = commit_with_extras( |
| 1001 | &repo, |
| 1002 | vec![base, other], |
| 1003 | vec![repo.set("m", "1")], |
| 1004 | vec![ |
| 1005 | (b"keep".to_vec(), b"me".to_vec()), |
| 1006 | (REBASED_FROM.to_vec(), b"old".to_vec()), |
| 1007 | ], |
| 1008 | ); |
| 1009 | let outcome = land(&repo.objects, Some(head), merge, signature("x")).unwrap(); |
| 1010 | let LandOutcome::Rebased { changeset, .. } = outcome else { |
| 1011 | panic!("expected a rebase, got {outcome:?}"); |
| 1012 | }; |
| 1013 | let new = read_changeset(&repo.objects, changeset).unwrap(); |
| 1014 | assert_eq!(new.parents, [head, other]); |
| 1015 | assert_eq!( |
| 1016 | new.extras, |
| 1017 | [ |
| 1018 | (b"keep".to_vec(), b"me".to_vec()), |
| 1019 | (REBASED_FROM.to_vec(), merge.to_hex().into_bytes()), |
| 1020 | ] |
| 1021 | ); |
| 1022 | } |
| 1023 | |
| 1024 | #[test] |
| 1025 | fn a_rebased_revert_keeps_what_it_reverts() { |
| 1026 | // A revert of `culprit` is a changeset on it whose changes are the |
| 1027 | // diff back to its parent. Rebased onto a head that moved, the merge |
| 1028 | // takes base = culprit, ours = head, theirs = the culprit's parent. |
| 1029 | let repo = Repo::new(); |
| 1030 | let base = repo.commit( |
| 1031 | &[], |
| 1032 | vec![repo.set("f", "1\n2\n3\n4\n5\n"), repo.set("g", "1")], |
| 1033 | ); |
| 1034 | let culprit = repo.commit(&[base], vec![repo.set("f", "1\n2\nbad\n4\n5\n")]); |
| 1035 | let head = repo.commit(&[culprit], vec![repo.set("f", "one\n2\nbad\n4\n5\n")]); |
| 1036 | let back = diff(&repo.objects, repo.root(culprit), repo.root(base)).unwrap(); |
| 1037 | let extras = vec![ |
| 1038 | (AGENT.to_vec(), b"verifier".to_vec()), |
| 1039 | (REVERTS.to_vec(), culprit.to_hex().into_bytes()), |
| 1040 | ]; |
| 1041 | let revert = commit_with_extras(&repo, vec![culprit], back, extras.clone()); |
| 1042 | let outcome = land(&repo.objects, Some(head), revert, signature("x")).unwrap(); |
| 1043 | let LandOutcome::Rebased { changeset, .. } = outcome else { |
| 1044 | panic!("expected a rebase, got {outcome:?}"); |
| 1045 | }; |
| 1046 | let new = read_changeset(&repo.objects, changeset).unwrap(); |
| 1047 | assert_eq!( |
| 1048 | repo.files(new.root), |
| 1049 | text_map(&[("f", "one\n2\n3\n4\n5\n"), ("g", "1")]) |
| 1050 | ); |
| 1051 | let mut expected = extras; |
| 1052 | expected.push((REBASED_FROM.to_vec(), revert.to_hex().into_bytes())); |
| 1053 | assert_eq!(new.extras, expected); |
| 1054 | } |
| 1055 | |
| 1056 | fn commit_with_extras( |
| 1057 | repo: &Repo, |
| 1058 | parents: Vec<ObjectId>, |
| 1059 | changes: Vec<Change>, |
| 1060 | extras: Vec<(Vec<u8>, Vec<u8>)>, |
| 1061 | ) -> ObjectId { |
| 1062 | crate::commit::commit( |
| 1063 | &repo.objects, |
| 1064 | parents, |
| 1065 | changes, |
| 1066 | signature("author"), |
| 1067 | signature("author"), |
| 1068 | b"merge\n".to_vec(), |
| 1069 | extras, |
| 1070 | ) |
| 1071 | .unwrap() |
| 1072 | } |
| 1073 | |
| 1074 | #[test] |
| 1075 | fn a_merged_file_names_the_heads_version() { |
| 1076 | let objects = Hinted::default(); |
| 1077 | let file = |path: &str, text: &str| Change { |
| 1078 | path: path.as_bytes().to_vec(), |
| 1079 | op: ChangeOp::File { |
| 1080 | blob: objects.put(Kind::Blob, text.as_bytes()).unwrap(), |
| 1081 | size: text.len() as u64, |
| 1082 | }, |
| 1083 | }; |
| 1084 | let commit = |parents: Vec<ObjectId>, changes| { |
| 1085 | crate::commit::commit( |
| 1086 | &objects, |
| 1087 | parents, |
| 1088 | changes, |
| 1089 | signature("author"), |
| 1090 | signature("author"), |
| 1091 | b"change\n".to_vec(), |
| 1092 | Vec::new(), |
| 1093 | ) |
| 1094 | .unwrap() |
| 1095 | }; |
| 1096 | let base = commit(Vec::new(), vec![file("f", "1\n2\n3\n4\n5\n")]); |
| 1097 | let head = commit(vec![base], vec![file("f", "ONE\n2\n3\n4\n5\n")]); |
| 1098 | let change = commit(vec![base], vec![file("f", "1\n2\n3\n4\nFIVE\n")]); |
| 1099 | objects.hints.take(); |
| 1100 | let outcome = land(&objects, Some(head), change, signature("x")).unwrap(); |
| 1101 | assert!( |
| 1102 | matches!(outcome, LandOutcome::Rebased { .. }), |
| 1103 | "{outcome:?}" |
| 1104 | ); |
| 1105 | let merged = ObjectId::hash(Kind::Blob, b"ONE\n2\n3\n4\nFIVE\n"); |
| 1106 | let heads = ObjectId::hash(Kind::Blob, b"ONE\n2\n3\n4\n5\n"); |
| 1107 | let hints = objects.hints.take(); |
| 1108 | assert!(hints.contains(&(merged, heads)), "{hints:?}"); |
| 1109 | } |
| 1110 | |
| 1111 | #[test] |
| 1112 | fn both_sides_editing_a_file_merge_line_by_line() { |
| 1113 | let s = setup( |
| 1114 | &[("f", "1\n2\n3\n4\n5\n")], |
| 1115 | |r| vec![r.set("f", "ONE\n2\n3\n4\n5\n")], |
| 1116 | |r| vec![r.set("f", "1\n2\n3\n4\nFIVE\n")], |
| 1117 | ); |
| 1118 | let (id, merged) = rebased(&s); |
| 1119 | assert_eq!(merged, [b"f".to_vec()]); |
| 1120 | assert_eq!( |
| 1121 | s.repo.files(s.repo.root(id)), |
| 1122 | text_map(&[("f", "ONE\n2\n3\n4\nFIVE\n")]) |
| 1123 | ); |
| 1124 | } |
| 1125 | |
| 1126 | #[test] |
| 1127 | fn executable_bit_and_content_merge_separately() { |
| 1128 | let s = setup( |
| 1129 | &[("run", "1\n2\n3\n")], |
| 1130 | |r| vec![r.exec("run", "1\n2\n3\n")], |
| 1131 | |r| vec![r.set("run", "1\n2\nthree\n")], |
| 1132 | ); |
| 1133 | let (id, merged) = rebased(&s); |
| 1134 | assert_eq!(merged, [b"run".to_vec()]); |
| 1135 | assert_eq!( |
| 1136 | s.repo.files(s.repo.root(id)), |
| 1137 | text_map(&[("run", "exec:1\n2\nthree\n")]) |
| 1138 | ); |
| 1139 | } |
| 1140 | |
| 1141 | #[test] |
| 1142 | fn already_applied() { |
| 1143 | let s = setup( |
| 1144 | &[("a", "1"), ("b", "2")], |
| 1145 | |r| vec![r.set("a", "new"), delete("b"), r.set("c", "3")], |
| 1146 | |r| vec![r.set("a", "new"), delete("b")], |
| 1147 | ); |
| 1148 | assert_eq!(land_it(&s), LandOutcome::AlreadyApplied); |
| 1149 | // A merge that gives what the head has is nothing to do either. |
| 1150 | let s = setup( |
| 1151 | &[("f", "1\n2\n3\n4\n5\n")], |
| 1152 | |r| vec![r.set("f", "ONE\n2\n3\n4\nFIVE\n")], |
| 1153 | |r| vec![r.set("f", "ONE\n2\n3\n4\n5\n")], |
| 1154 | ); |
| 1155 | assert_eq!(land_it(&s), LandOutcome::AlreadyApplied); |
| 1156 | } |
| 1157 | |
| 1158 | #[test] |
| 1159 | fn content_conflict() { |
| 1160 | let s = setup( |
| 1161 | &[("f", "1\n2\n3\n")], |
| 1162 | |r| vec![r.set("f", "1\nours\n3\n")], |
| 1163 | |r| vec![r.set("f", "1\ntheirs\n3\n")], |
| 1164 | ); |
| 1165 | let LandOutcome::Conflicts(found) = land_it(&s) else { |
| 1166 | panic!("expected conflicts"); |
| 1167 | }; |
| 1168 | assert_eq!(found.len(), 1); |
| 1169 | let conflict = &found[0]; |
| 1170 | assert_eq!(conflict.path, b"f"); |
| 1171 | assert_eq!(conflict.base, Some(s.repo.file_kind("1\n2\n3\n"))); |
| 1172 | assert_eq!(conflict.ours, Some(s.repo.file_kind("1\nours\n3\n"))); |
| 1173 | assert_eq!(conflict.theirs, Some(s.repo.file_kind("1\ntheirs\n3\n"))); |
| 1174 | let ConflictKind::Content { hunks } = &conflict.kind else { |
| 1175 | panic!("expected a content conflict"); |
| 1176 | }; |
| 1177 | let side = |lines, text: &str| HunkSide { |
| 1178 | lines, |
| 1179 | text: text.as_bytes().to_vec(), |
| 1180 | }; |
| 1181 | assert_eq!( |
| 1182 | hunks, |
| 1183 | &[ConflictHunk { |
| 1184 | base: side(1..2, "2\n"), |
| 1185 | ours: side(1..2, "ours\n"), |
| 1186 | theirs: side(1..2, "theirs\n"), |
| 1187 | }] |
| 1188 | ); |
| 1189 | |
| 1190 | // Both sides add the same path with different content. |
| 1191 | let s = setup( |
| 1192 | &[], |
| 1193 | |r| vec![r.set("n", "a\n")], |
| 1194 | |r| vec![r.set("n", "b\n")], |
| 1195 | ); |
| 1196 | assert_eq!(conflicts(&s), pairs(&[("n", "CONTENT")])); |
| 1197 | // Two symlink targets, and two gitlink commits. |
| 1198 | let s = setup( |
| 1199 | &[("x", "1")], |
| 1200 | |r| vec![r.symlink("l", "one"), gitlink("g", 1)], |
| 1201 | |r| vec![r.symlink("l", "two"), gitlink("g", 2)], |
| 1202 | ); |
| 1203 | assert_eq!(conflicts(&s), pairs(&[("g", "CONTENT"), ("l", "CONTENT")])); |
| 1204 | // Binary content. |
| 1205 | let s = setup( |
| 1206 | &[("bin", "\0base")], |
| 1207 | |r| vec![r.set("bin", "\0ours")], |
| 1208 | |r| vec![r.set("bin", "\0theirs")], |
| 1209 | ); |
| 1210 | let LandOutcome::Conflicts(found) = land_it(&s) else { |
| 1211 | panic!("expected conflicts"); |
| 1212 | }; |
| 1213 | assert_eq!(found[0].kind, ConflictKind::Content { hunks: Vec::new() }); |
| 1214 | } |
| 1215 | |
| 1216 | #[test] |
| 1217 | fn modify_delete_conflict() { |
| 1218 | let s = setup( |
| 1219 | &[("f", "1"), ("g", "1")], |
| 1220 | |r| vec![r.set("f", "2"), delete("g")], |
| 1221 | |r| vec![delete("f"), r.set("g", "2")], |
| 1222 | ); |
| 1223 | assert_eq!( |
| 1224 | conflicts(&s), |
| 1225 | pairs(&[("f", "MODIFY_DELETE"), ("g", "MODIFY_DELETE")]) |
| 1226 | ); |
| 1227 | } |
| 1228 | |
| 1229 | #[test] |
| 1230 | fn mode_conflict() { |
| 1231 | // Both changed the kind, differently. |
| 1232 | let s = setup( |
| 1233 | &[("f", "1")], |
| 1234 | |r| vec![r.symlink("f", "target")], |
| 1235 | |r| vec![r.exec("f", "1")], |
| 1236 | ); |
| 1237 | assert_eq!(conflicts(&s), pairs(&[("f", "MODE")])); |
| 1238 | // Added on both sides, executable on one only: the base cannot settle |
| 1239 | // the bit. |
| 1240 | let s = setup( |
| 1241 | &[], |
| 1242 | |r| vec![r.exec("n", "same")], |
| 1243 | |r| vec![r.set("n", "same")], |
| 1244 | ); |
| 1245 | assert_eq!(conflicts(&s), pairs(&[("n", "MODE")])); |
| 1246 | } |
| 1247 | |
| 1248 | #[test] |
| 1249 | fn directory_file_conflicts() { |
| 1250 | // The change sets a file where the head now has a directory. |
| 1251 | let s = setup( |
| 1252 | &[("a", "1")], |
| 1253 | |r| vec![r.set("x/y", "h")], |
| 1254 | |r| vec![r.set("x", "c")], |
| 1255 | ); |
| 1256 | assert_eq!(conflicts(&s), pairs(&[("x", "DF")])); |
| 1257 | // The change sets something below a path the head made a file. |
| 1258 | let s = setup( |
| 1259 | &[("d/a", "1")], |
| 1260 | |r| vec![delete("d/a"), r.set("d", "file")], |
| 1261 | |r| vec![r.set("d/b", "c")], |
| 1262 | ); |
| 1263 | assert_eq!(conflicts(&s), pairs(&[("d", "DF")])); |
| 1264 | // The change edits a file below a path the head made a file. |
| 1265 | let s = setup( |
| 1266 | &[("d/a", "1")], |
| 1267 | |r| vec![delete("d/a"), r.set("d", "file")], |
| 1268 | |r| vec![r.set("d/a", "2")], |
| 1269 | ); |
| 1270 | assert_eq!(conflicts(&s), pairs(&[("d", "DF")])); |
| 1271 | // The change edits a file the head replaced with a directory. |
| 1272 | let s = setup( |
| 1273 | &[("f", "1")], |
| 1274 | |r| vec![delete("f"), r.set("f/inner", "h")], |
| 1275 | |r| vec![r.set("f", "2")], |
| 1276 | ); |
| 1277 | assert_eq!(conflicts(&s), pairs(&[("f", "DF")])); |
| 1278 | // The change replaces a directory with a file, and the head added a |
| 1279 | // file to that directory. |
| 1280 | let s = setup( |
| 1281 | &[("p/x", "1")], |
| 1282 | |r| vec![r.set("p/new", "h")], |
| 1283 | |r| vec![delete("p/x"), r.set("p", "file")], |
| 1284 | ); |
| 1285 | assert_eq!(conflicts(&s), pairs(&[("p", "DF")])); |
| 1286 | } |
| 1287 | |
| 1288 | #[test] |
| 1289 | fn replacing_a_directory_the_head_also_emptied() { |
| 1290 | // The head deleted one file of `p`; the change deleted both and put a |
| 1291 | // file in its place. Nothing is left in the directory: no conflict. |
| 1292 | let s = setup( |
| 1293 | &[("p/x", "1"), ("p/y", "2")], |
| 1294 | |_| vec![delete("p/y")], |
| 1295 | |r| vec![delete("p/x"), delete("p/y"), r.set("p", "file")], |
| 1296 | ); |
| 1297 | let (id, _) = rebased(&s); |
| 1298 | assert_eq!(s.repo.files(s.repo.root(id)), text_map(&[("p", "file")])); |
| 1299 | // The head replaced a file with a directory, and the change deleted |
| 1300 | // the file: both removed it, the directory stays. |
| 1301 | let s = setup( |
| 1302 | &[("f", "1"), ("g", "1")], |
| 1303 | |r| vec![delete("f"), r.set("f/inner", "h")], |
| 1304 | |r| vec![delete("f"), r.set("g", "2")], |
| 1305 | ); |
| 1306 | let (id, _) = rebased(&s); |
| 1307 | assert_eq!( |
| 1308 | s.repo.files(s.repo.root(id)), |
| 1309 | text_map(&[("f/inner", "h"), ("g", "2")]) |
| 1310 | ); |
| 1311 | } |
| 1312 | |
| 1313 | #[test] |
| 1314 | fn directory_removed_conflicts() { |
| 1315 | // The head removed `d`; the change adds a file in it. |
| 1316 | let s = setup( |
| 1317 | &[("d/a", "1"), ("k", "1")], |
| 1318 | |_| vec![delete("d/a")], |
| 1319 | |r| vec![r.set("d/b", "2")], |
| 1320 | ); |
| 1321 | let LandOutcome::Conflicts(found) = land_it(&s) else { |
| 1322 | panic!("expected conflicts"); |
| 1323 | }; |
| 1324 | assert_eq!(found.len(), 1); |
| 1325 | assert_eq!(found[0].path, b"d/b"); |
| 1326 | assert_eq!( |
| 1327 | found[0].kind, |
| 1328 | ConflictKind::DirectoryRemoved { |
| 1329 | directory: b"d".to_vec() |
| 1330 | } |
| 1331 | ); |
| 1332 | // Also when the new file is deeper, in a directory the change creates. |
| 1333 | let s = setup( |
| 1334 | &[("d/e/a", "1"), ("k", "1")], |
| 1335 | |_| vec![delete("d/e/a")], |
| 1336 | |r| vec![r.set("d/e/new/f", "2")], |
| 1337 | ); |
| 1338 | assert_eq!(conflicts(&s), pairs(&[("d/e/new/f", "DIR_REMOVED")])); |
| 1339 | // The other way: the change removed `d`, the head added a file in it. |
| 1340 | let s = setup( |
| 1341 | &[("d/a", "1"), ("k", "1")], |
| 1342 | |r| vec![r.set("d/b", "2")], |
| 1343 | |_| vec![delete("d/a")], |
| 1344 | ); |
| 1345 | let LandOutcome::Conflicts(found) = land_it(&s) else { |
| 1346 | panic!("expected conflicts"); |
| 1347 | }; |
| 1348 | assert_eq!(found[0].path, b"d/b"); |
| 1349 | assert_eq!(found[0].ours, Some(s.repo.file_kind("2"))); |
| 1350 | assert_eq!(found[0].theirs, None); |
| 1351 | // A directory that keeps other files is not removed. |
| 1352 | let s = setup( |
| 1353 | &[("d/a", "1"), ("d/z", "1")], |
| 1354 | |_| vec![delete("d/a")], |
| 1355 | |r| vec![r.set("d/b", "2")], |
| 1356 | ); |
| 1357 | let (id, _) = rebased(&s); |
| 1358 | assert_eq!( |
| 1359 | s.repo.files(s.repo.root(id)), |
| 1360 | text_map(&[("d/b", "2"), ("d/z", "1")]) |
| 1361 | ); |
| 1362 | } |
| 1363 | |
| 1364 | #[test] |
| 1365 | fn case_conflicts() { |
| 1366 | let s = setup( |
| 1367 | &[("x", "1")], |
| 1368 | |r| vec![r.set("README", "h")], |
| 1369 | |r| vec![r.set("readme", "c")], |
| 1370 | ); |
| 1371 | let LandOutcome::Conflicts(found) = land_it(&s) else { |
| 1372 | panic!("expected conflicts"); |
| 1373 | }; |
| 1374 | assert_eq!(found.len(), 1); |
| 1375 | assert_eq!(found[0].path, b"readme"); |
| 1376 | assert_eq!( |
| 1377 | found[0].kind, |
| 1378 | ConflictKind::Case { |
| 1379 | existing: b"README".to_vec() |
| 1380 | } |
| 1381 | ); |
| 1382 | // Unicode normalisation: precomposed and decomposed forms. |
| 1383 | let s = setup( |
| 1384 | &[("x", "1")], |
| 1385 | |r| vec![r.set("docs/caf\u{e9}.md", "h")], |
| 1386 | |r| vec![r.set("docs/cafe\u{301}.md", "c")], |
| 1387 | ); |
| 1388 | assert_eq!(conflicts(&s), pairs(&[("docs/cafe\u{301}.md", "CASE")])); |
| 1389 | // A directory name that collides, reported once. |
| 1390 | let s = setup( |
| 1391 | &[("x", "1")], |
| 1392 | |r| vec![r.set("Docs/a", "h")], |
| 1393 | |r| vec![r.set("docs/b", "c"), r.set("docs/c", "c")], |
| 1394 | ); |
| 1395 | assert_eq!(conflicts(&s), pairs(&[("docs", "CASE")])); |
| 1396 | // A collision with a name that was already in the base is the |
| 1397 | // change's own business. |
| 1398 | let s = setup( |
| 1399 | &[("README", "1")], |
| 1400 | |r| vec![r.set("x", "h")], |
| 1401 | |r| vec![r.set("readme", "c")], |
| 1402 | ); |
| 1403 | rebased(&s); |
| 1404 | // Renaming by case alone is fine too. |
| 1405 | let s = setup( |
| 1406 | &[("README", "1")], |
| 1407 | |r| vec![r.set("x", "h")], |
| 1408 | |r| vec![delete("README"), r.set("Readme", "1")], |
| 1409 | ); |
| 1410 | rebased(&s); |
| 1411 | // Two names on the head fold to the name the change adds: each |
| 1412 | // collision is reported once, however many files go through it. |
| 1413 | let s = setup( |
| 1414 | &[("x", "1")], |
| 1415 | |r| vec![r.set("Docs/a", "h"), r.set("DOCS/b", "h")], |
| 1416 | |r| vec![r.set("docs/c", "c"), r.set("docs/d", "c")], |
| 1417 | ); |
| 1418 | let LandOutcome::Conflicts(found) = land_it(&s) else { |
| 1419 | panic!("expected conflicts"); |
| 1420 | }; |
| 1421 | let existing: Vec<&ConflictKind> = found.iter().map(|c| &c.kind).collect(); |
| 1422 | assert_eq!( |
| 1423 | existing, |
| 1424 | [ |
| 1425 | &ConflictKind::Case { |
| 1426 | existing: b"DOCS".to_vec() |
| 1427 | }, |
| 1428 | &ConflictKind::Case { |
| 1429 | existing: b"Docs".to_vec() |
| 1430 | }, |
| 1431 | ] |
| 1432 | ); |
| 1433 | // Both sides create the directory `cafe\u{301}`, and the change also |
| 1434 | // adds `caf\u{e9}` next to it. That collision is the change's own, |
| 1435 | // whichever side lands first. |
| 1436 | let dir = |r: &Repo| vec![r.set("cafe\u{301}/z", "h")]; |
| 1437 | let own = |r: &Repo| vec![r.set("cafe\u{301}/b", "c"), r.set("caf\u{e9}", "c")]; |
| 1438 | rebased(&setup(&[("x", "1")], dir, own)); |
| 1439 | rebased(&setup(&[("x", "1")], own, dir)); |
| 1440 | } |
| 1441 | |
| 1442 | #[test] |
| 1443 | fn several_conflicts_are_all_reported_in_order() { |
| 1444 | let s = setup( |
| 1445 | &[("a", "1\n"), ("b", "1"), ("c", "1")], |
| 1446 | |r| vec![r.set("a", "ours\n"), delete("b"), r.set("Z", "h")], |
| 1447 | |r| { |
| 1448 | vec![ |
| 1449 | r.set("a", "theirs\n"), |
| 1450 | r.set("b", "2"), |
| 1451 | r.set("z", "c"), |
| 1452 | r.set("c", "2"), |
| 1453 | ] |
| 1454 | }, |
| 1455 | ); |
| 1456 | let stored = s.repo.objects.len(); |
| 1457 | assert_eq!( |
| 1458 | conflicts(&s), |
| 1459 | pairs(&[("a", "CONTENT"), ("b", "MODIFY_DELETE"), ("z", "CASE")]) |
| 1460 | ); |
| 1461 | // A landing with conflicts stores nothing. |
| 1462 | assert_eq!(s.repo.objects.len(), stored); |
| 1463 | } |
| 1464 | } |