| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Putting a workspace's own changesets on top of a branch head. |
| 5 | //! |
| 6 | //! A workspace's unlanded changesets form a stack: each one's first parent |
| 7 | //! is the one before, and the first one's is on the branch. The first is |
| 8 | //! landed with [`braid_engine::land`], which needs its base on the head's |
| 9 | //! first-parent chain. The ones after it are based on a changeset that the |
| 10 | //! landing may have just rewritten, so each is rebased with the changeset it |
| 11 | //! was built on as the merge base, onto the rewritten one: the engine is |
| 12 | //! asked to land it on a temporary changeset whose first parent is its |
| 13 | //! original base and whose tree is the rewritten one's, and the result is |
| 14 | //! given the rewritten one as its parent. The temporary changesets stay in |
| 15 | //! the store, unreferenced. |
| 16 | |
| 17 | use braid_engine::{ |
| 18 | AGENT, Conflict, LandOutcome, REBASED_FROM, commit, diff, entry_at, land, read_blob, |
| 19 | read_changes, read_changeset, |
| 20 | }; |
| 21 | use braid_format::{ |
| 22 | Change, ChangeOp, ChangesetParts, EntryKind, Kind, ObjectId, Objects, Signature, |
| 23 | }; |
| 24 | |
| 25 | use crate::error::Error; |
| 26 | use crate::markers; |
| 27 | use crate::paths::is_within; |
| 28 | use crate::state::RecordedConflict; |
| 29 | use crate::tree::root_of; |
| 30 | use crate::workspace::Placed; |
| 31 | |
| 32 | /// The extra field a temporary base carries, so that it can be told apart. |
| 33 | pub const TEMPORARY: &[u8] = b"braid-temporary-base"; |
| 34 | |
| 35 | /// How a replay ended. |
| 36 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 37 | pub(crate) enum Replayed { |
| 38 | /// Every changeset is on top of the head; `tip` is the last of them, or |
| 39 | /// the head itself when it had all of them already. |
| 40 | Done { |
| 41 | tip: ObjectId, |
| 42 | rebased: bool, |
| 43 | /// Where each changeset of the stack went, in order. |
| 44 | placed: Vec<Placed>, |
| 45 | /// The paths both sides changed, over the whole stack, sorted. |
| 46 | merged_paths: Vec<Vec<u8>>, |
| 47 | }, |
| 48 | /// The changeset at `index` of the stack conflicts with `onto`, the head |
| 49 | /// or the last changeset replayed before it. |
| 50 | Stopped { |
| 51 | index: usize, |
| 52 | onto: ObjectId, |
| 53 | conflicts: Vec<Conflict>, |
| 54 | /// Where the changesets before `index` went. |
| 55 | placed: Vec<Placed>, |
| 56 | }, |
| 57 | } |
| 58 | |
| 59 | /// How the first changeset of a stack goes onto the head. |
| 60 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 61 | pub(crate) enum First { |
| 62 | /// Landed: its base must be on the head's first-parent chain. |
| 63 | MustBeOnBranch, |
| 64 | /// Landed if its base is on the chain, and otherwise rebased from its |
| 65 | /// own base wherever that is, as an update allows. |
| 66 | Anywhere, |
| 67 | /// Rebased from its own base, which is known not to be on the chain: |
| 68 | /// what continuing a rebase after a resolution does. |
| 69 | Pick, |
| 70 | } |
| 71 | |
| 72 | /// Replays `stack`, oldest first, onto `head` (`None` for an empty |
| 73 | /// branch). Fails with [`Error::NotOnBranch`] when the first changeset's |
| 74 | /// base is not on the branch and `first` requires it. |
| 75 | pub(crate) fn replay<O: Objects>( |
| 76 | objects: &O, |
| 77 | branch: &str, |
| 78 | head: Option<ObjectId>, |
| 79 | stack: &[ObjectId], |
| 80 | committer: &Signature, |
| 81 | first: First, |
| 82 | ) -> Result<Replayed, Error> { |
| 83 | let mut tip = head; |
| 84 | let mut rebased = false; |
| 85 | let mut placed = Vec::with_capacity(stack.len()); |
| 86 | let mut merged = Vec::new(); |
| 87 | for (index, &change) in stack.iter().enumerate() { |
| 88 | let outcome = match tip { |
| 89 | Some(onto) if index > 0 || first == First::Pick => { |
| 90 | replay_one(objects, onto, change, committer)? |
| 91 | } |
| 92 | _ => match land(objects, tip, change, committer.clone()) { |
| 93 | Err(braid_engine::Error::BaseNotOnBranch { .. }) => match (first, tip) { |
| 94 | (First::Anywhere, Some(onto)) => replay_one(objects, onto, change, committer)?, |
| 95 | // A first changeset without a parent is based on the |
| 96 | // empty tree, where every branch starts: rebase it from |
| 97 | // there rather than asking for an update. A path the |
| 98 | // branch added too is a conflict, never overwritten. |
| 99 | (First::MustBeOnBranch, Some(onto)) |
| 100 | if read_changeset(objects, change)?.parents.is_empty() => |
| 101 | { |
| 102 | replay_one(objects, onto, change, committer)? |
| 103 | } |
| 104 | _ => { |
| 105 | return Err(Error::NotOnBranch { |
| 106 | branch: branch.to_owned(), |
| 107 | }); |
| 108 | } |
| 109 | }, |
| 110 | other => other?, |
| 111 | }, |
| 112 | }; |
| 113 | let to = match outcome { |
| 114 | LandOutcome::FastForward(id) => Some(id), |
| 115 | LandOutcome::Rebased { |
| 116 | changeset, |
| 117 | merged_paths, |
| 118 | } => { |
| 119 | rebased = true; |
| 120 | merged.extend(merged_paths); |
| 121 | Some(changeset) |
| 122 | } |
| 123 | LandOutcome::AlreadyApplied => None, |
| 124 | LandOutcome::Conflicts(conflicts) => { |
| 125 | let onto = tip.ok_or(Error::NotOnBranch { |
| 126 | branch: branch.to_owned(), |
| 127 | })?; |
| 128 | return Ok(Replayed::Stopped { |
| 129 | index, |
| 130 | onto, |
| 131 | conflicts, |
| 132 | placed, |
| 133 | }); |
| 134 | } |
| 135 | }; |
| 136 | tip = to.or(tip); |
| 137 | placed.push(Placed { from: change, to }); |
| 138 | } |
| 139 | merged.sort(); |
| 140 | merged.dedup(); |
| 141 | match tip { |
| 142 | Some(tip) => Ok(Replayed::Done { |
| 143 | tip, |
| 144 | rebased, |
| 145 | placed, |
| 146 | merged_paths: merged, |
| 147 | }), |
| 148 | None => Err(Error::NotOnBranch { |
| 149 | branch: branch.to_owned(), |
| 150 | }), |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | /// Rebases `change` onto `onto`, with `change`'s first parent as the merge |
| 155 | /// base, whatever history connects them. A first changeset, which has no |
| 156 | /// parent, is rebased from the empty tree. |
| 157 | pub(crate) fn replay_one<O: Objects>( |
| 158 | objects: &O, |
| 159 | onto: ObjectId, |
| 160 | change: ObjectId, |
| 161 | committer: &Signature, |
| 162 | ) -> Result<LandOutcome, Error> { |
| 163 | let theirs = read_changeset(objects, change)?; |
| 164 | let (stand_in, base) = match theirs.parents.first() { |
| 165 | Some(&base) if base == onto => return Ok(LandOutcome::FastForward(change)), |
| 166 | Some(&base) => (change, base), |
| 167 | None => { |
| 168 | // The same change on an empty first changeset: its tree and |
| 169 | // its change list stay what they are. |
| 170 | let empty = commit( |
| 171 | objects, |
| 172 | Vec::new(), |
| 173 | Vec::new(), |
| 174 | committer.clone(), |
| 175 | committer.clone(), |
| 176 | b"braid: empty base of a rebase\n".to_vec(), |
| 177 | vec![(TEMPORARY.to_vec(), Vec::new())], |
| 178 | )?; |
| 179 | let changes = read_changes(objects, change, &theirs)?.into_owned(); |
| 180 | let copy = store_parts( |
| 181 | objects, |
| 182 | ChangesetParts { |
| 183 | parents: vec![empty], |
| 184 | root: theirs.root, |
| 185 | changes, |
| 186 | author: theirs.author.clone(), |
| 187 | committer: theirs.committer.clone(), |
| 188 | message: theirs.message.clone(), |
| 189 | extras: theirs.extras.clone(), |
| 190 | git_origin: None, |
| 191 | }, |
| 192 | )?; |
| 193 | (copy, empty) |
| 194 | } |
| 195 | }; |
| 196 | let onto_root = read_changeset(objects, onto)?.root; |
| 197 | let base_root = read_changeset(objects, base)?.root; |
| 198 | let temporary = commit( |
| 199 | objects, |
| 200 | vec![base], |
| 201 | diff(objects, base_root, onto_root)?, |
| 202 | committer.clone(), |
| 203 | committer.clone(), |
| 204 | b"braid: temporary base of a rebase\n".to_vec(), |
| 205 | vec![(TEMPORARY.to_vec(), onto.to_hex().into_bytes())], |
| 206 | )?; |
| 207 | let outcome = land(objects, Some(temporary), stand_in, committer.clone())?; |
| 208 | let LandOutcome::Rebased { |
| 209 | changeset, |
| 210 | merged_paths, |
| 211 | } = outcome |
| 212 | else { |
| 213 | return Ok(outcome); |
| 214 | }; |
| 215 | // The same tree and change list, with `onto` as the first parent (the |
| 216 | // temporary base has `onto`'s tree), naming the original change. The |
| 217 | // other extra fields are the original's, its agent among them. |
| 218 | let landed = read_changeset(objects, changeset)?; |
| 219 | let changes = read_changes(objects, changeset, &landed)?.into_owned(); |
| 220 | let parents = std::iter::once(onto) |
| 221 | .chain(landed.parents.iter().skip(1).copied()) |
| 222 | .collect(); |
| 223 | let mut extras: Vec<(Vec<u8>, Vec<u8>)> = landed |
| 224 | .extras |
| 225 | .into_iter() |
| 226 | .filter(|(key, _)| key.as_slice() != REBASED_FROM) |
| 227 | .collect(); |
| 228 | extras.push((REBASED_FROM.to_vec(), change.to_hex().into_bytes())); |
| 229 | let rebased = store_parts( |
| 230 | objects, |
| 231 | ChangesetParts { |
| 232 | parents, |
| 233 | root: landed.root, |
| 234 | changes, |
| 235 | author: landed.author, |
| 236 | committer: landed.committer, |
| 237 | message: landed.message, |
| 238 | extras, |
| 239 | git_origin: None, |
| 240 | }, |
| 241 | )?; |
| 242 | Ok(LandOutcome::Rebased { |
| 243 | changeset: rebased, |
| 244 | merged_paths, |
| 245 | }) |
| 246 | } |
| 247 | |
| 248 | /// Assembles and stores a changeset whose tree is stored already. |
| 249 | fn store_parts<O: Objects>(objects: &O, parts: ChangesetParts) -> Result<ObjectId, Error> { |
| 250 | let assembled = parts.assemble()?; |
| 251 | if let Some((_, list)) = &assembled.external_list { |
| 252 | objects.put(Kind::Blob, list).map_err(store_error)?; |
| 253 | } |
| 254 | objects |
| 255 | .put(Kind::Changeset, &assembled.encoded) |
| 256 | .map_err(store_error)?; |
| 257 | Ok(assembled.id) |
| 258 | } |
| 259 | |
| 260 | fn store_error<E: std::error::Error + Send + Sync + 'static>(error: E) -> Error { |
| 261 | Error::Engine(braid_engine::Error::Store(Box::new(error))) |
| 262 | } |
| 263 | |
| 264 | /// A regular file's blob and executable bit. |
| 265 | fn regular(kind: Option<&ChangeOp>) -> Option<(ObjectId, bool)> { |
| 266 | match kind { |
| 267 | Some(ChangeOp::File { blob, .. }) => Some((*blob, false)), |
| 268 | Some(ChangeOp::Executable { blob, .. }) => Some((*blob, true)), |
| 269 | _ => None, |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | /// The file at `path` of the tree `root`, if there is one there. |
| 274 | fn file_at<O: Objects>( |
| 275 | objects: &O, |
| 276 | root: ObjectId, |
| 277 | path: &[u8], |
| 278 | ) -> Result<Option<ChangeOp>, Error> { |
| 279 | Ok(entry_at(objects, root, path)? |
| 280 | .filter(|kind| !matches!(kind, EntryKind::Tree { .. })) |
| 281 | .and_then(|kind| ChangeOp::from_entry(&kind))) |
| 282 | } |
| 283 | |
| 284 | /// What to write when `change` stopped on `conflicts` against `onto`: the |
| 285 | /// tree of `onto`, with every path of the change that merges cleanly, and, |
| 286 | /// for each content conflict between two regular files, the merge with |
| 287 | /// conflict markers. Other conflicts keep `onto`'s version. Returns the |
| 288 | /// tree, stored, and the conflicts as the workspace records them. |
| 289 | pub(crate) fn conflict_tree<O: Objects>( |
| 290 | objects: &O, |
| 291 | onto: ObjectId, |
| 292 | change: ObjectId, |
| 293 | conflicts: &[Conflict], |
| 294 | labels: (&str, &str), |
| 295 | ) -> Result<(ObjectId, Vec<RecordedConflict>), Error> { |
| 296 | let theirs = read_changeset(objects, change)?; |
| 297 | let base_root = root_of(objects, theirs.parents.first().copied())?; |
| 298 | let onto_root = read_changeset(objects, onto)?.root; |
| 299 | let changes = read_changes(objects, change, &theirs)?.into_owned(); |
| 300 | let conflicting = |path: &[u8]| { |
| 301 | conflicts |
| 302 | .iter() |
| 303 | .any(|c| is_within(path, &c.path) || is_within(&c.path, path)) |
| 304 | }; |
| 305 | |
| 306 | let mut writes: Vec<Change> = Vec::new(); |
| 307 | for item in &changes { |
| 308 | if conflicting(&item.path) { |
| 309 | continue; |
| 310 | } |
| 311 | let ours = file_at(objects, onto_root, &item.path)?; |
| 312 | let base = file_at(objects, base_root, &item.path)?; |
| 313 | let theirs_op = (!matches!(item.op, ChangeOp::Delete)).then(|| item.op.clone()); |
| 314 | if theirs_op == ours { |
| 315 | continue; |
| 316 | } |
| 317 | if base == ours { |
| 318 | writes.push(item.clone()); |
| 319 | continue; |
| 320 | } |
| 321 | // Both changed it and the engine found no conflict: two regular |
| 322 | // files whose lines merge. |
| 323 | let (Some((o, o_exec)), Some((t, t_exec))) = |
| 324 | (regular(ours.as_ref()), regular(theirs_op.as_ref())) |
| 325 | else { |
| 326 | continue; |
| 327 | }; |
| 328 | let base_regular = regular(base.as_ref()); |
| 329 | let base_bytes = match base_regular { |
| 330 | Some((b, _)) => read_blob(objects, b)?, |
| 331 | None => Vec::new(), |
| 332 | }; |
| 333 | let braid_engine::MergeResult::Clean(merged) = braid_engine::merge3( |
| 334 | &base_bytes, |
| 335 | &read_blob(objects, o)?, |
| 336 | &read_blob(objects, t)?, |
| 337 | ) else { |
| 338 | continue; |
| 339 | }; |
| 340 | let executable = match base_regular { |
| 341 | _ if o_exec == t_exec => o_exec, |
| 342 | Some((_, b_exec)) if b_exec == o_exec => t_exec, |
| 343 | _ => o_exec, |
| 344 | }; |
| 345 | let op = put_file(objects, &merged, executable)?; |
| 346 | if Some(&op) != ours.as_ref() { |
| 347 | writes.push(Change { |
| 348 | path: item.path.clone(), |
| 349 | op, |
| 350 | }); |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | let mut recorded = Vec::new(); |
| 355 | for conflict in conflicts { |
| 356 | let mut markers_written = false; |
| 357 | if let braid_engine::ConflictKind::Content { .. } = conflict.kind { |
| 358 | let ours = conflict.ours.as_ref().and_then(ChangeOp::from_entry); |
| 359 | let theirs_op = conflict.theirs.as_ref().and_then(ChangeOp::from_entry); |
| 360 | let base = conflict.base.as_ref().and_then(ChangeOp::from_entry); |
| 361 | if let (Some((o, o_exec)), Some((t, _))) = |
| 362 | (regular(ours.as_ref()), regular(theirs_op.as_ref())) |
| 363 | { |
| 364 | let base_bytes = match regular(base.as_ref()) { |
| 365 | Some((b, _)) => read_blob(objects, b)?, |
| 366 | None => Vec::new(), |
| 367 | }; |
| 368 | let rendered = markers::render( |
| 369 | &base_bytes, |
| 370 | &read_blob(objects, o)?, |
| 371 | &read_blob(objects, t)?, |
| 372 | labels.0, |
| 373 | labels.1, |
| 374 | ); |
| 375 | if let Some(content) = rendered { |
| 376 | writes.push(Change { |
| 377 | path: conflict.path.clone(), |
| 378 | op: put_file(objects, &content, o_exec)?, |
| 379 | }); |
| 380 | markers_written = true; |
| 381 | } |
| 382 | } |
| 383 | } |
| 384 | if !recorded |
| 385 | .iter() |
| 386 | .any(|r: &RecordedConflict| r.path == conflict.path && r.code == conflict.kind.code()) |
| 387 | { |
| 388 | recorded.push(RecordedConflict { |
| 389 | path: conflict.path.clone(), |
| 390 | code: conflict.kind.code().to_owned(), |
| 391 | markers: markers_written, |
| 392 | resolved: false, |
| 393 | }); |
| 394 | } |
| 395 | } |
| 396 | writes.sort_by(|a, b| a.path.cmp(&b.path)); |
| 397 | writes.dedup_by(|a, b| a.path == b.path); |
| 398 | let tree = braid_engine::apply(objects, onto_root, &writes)?; |
| 399 | Ok((tree, recorded)) |
| 400 | } |
| 401 | |
| 402 | fn put_file<O: Objects>(objects: &O, content: &[u8], executable: bool) -> Result<ChangeOp, Error> { |
| 403 | let blob = objects.put(Kind::Blob, content).map_err(store_error)?; |
| 404 | let size = content.len() as u64; |
| 405 | Ok(if executable { |
| 406 | ChangeOp::Executable { blob, size } |
| 407 | } else { |
| 408 | ChangeOp::File { blob, size } |
| 409 | }) |
| 410 | } |
| 411 | |
| 412 | /// The extra fields of a changeset: the agent that makes it. |
| 413 | pub(crate) fn agent_extras(agent: &str) -> Vec<(Vec<u8>, Vec<u8>)> { |
| 414 | vec![(AGENT.to_vec(), agent.as_bytes().to_vec())] |
| 415 | } |
| 416 | |
| 417 | /// The extra fields of the changeset that finishes a rebase of `change`, |
| 418 | /// whose own are `original`: the same, as landing keeps them, with |
| 419 | /// [`REBASED_FROM`] naming `change`. The original's [`AGENT`] stays; a change |
| 420 | /// without one gets `agent`, who resolved it. |
| 421 | pub(crate) fn rebased_extras( |
| 422 | original: &[(Vec<u8>, Vec<u8>)], |
| 423 | change: ObjectId, |
| 424 | agent: &str, |
| 425 | ) -> Vec<(Vec<u8>, Vec<u8>)> { |
| 426 | let mut extras: Vec<(Vec<u8>, Vec<u8>)> = original |
| 427 | .iter() |
| 428 | .filter(|(key, _)| key.as_slice() != REBASED_FROM) |
| 429 | .cloned() |
| 430 | .collect(); |
| 431 | if !extras.iter().any(|(key, _)| key.as_slice() == AGENT) { |
| 432 | extras.splice(0..0, agent_extras(agent)); |
| 433 | } |
| 434 | extras.push((REBASED_FROM.to_vec(), change.to_hex().into_bytes())); |
| 435 | extras |
| 436 | } |