| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Bringing a hub's branches and tags in: `braid hub fetch`, `braid hub |
| 5 | //! clone`, and the fetch that landing and updating start with in a linked |
| 6 | //! repository. |
| 7 | //! |
| 8 | //! The objects come as `/missing` streams: what the hub's heads need, less |
| 9 | //! what the local heads reach. Then one op log operation moves the refs: |
| 10 | //! each local branch moves to the hub's head when it does not exist, or |
| 11 | //! when its head is on the first-parent chain of the hub's; a branch with |
| 12 | //! changesets the hub does not have stays where it is, and is reported. A |
| 13 | //! tag is created, and never moved. `remote/hub/<ref>` records where each |
| 14 | //! of the hub's refs was seen, so that a branch kept back still has a name |
| 15 | //! for the hub's head. |
| 16 | |
| 17 | use std::cell::RefCell; |
| 18 | use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; |
| 19 | |
| 20 | use anyhow::{Result, anyhow, bail}; |
| 21 | use braid_engine::{LandOutcome, REBASED_FROM, read_changeset}; |
| 22 | use braid_format::changeset::Changes; |
| 23 | use braid_format::tree::{EntryKind, Node}; |
| 24 | use braid_format::{Kind, ObjectId, Objects, Signature}; |
| 25 | use braid_hubproto::api::MissingRequest; |
| 26 | use braid_repo::{Repo, RepoHistory}; |
| 27 | use braid_store::{RefUpdate, Refs, Store, TransactError}; |
| 28 | |
| 29 | use super::link::Link; |
| 30 | use super::remote::{HubError, Remote}; |
| 31 | use super::transfer::{Received, store_stream}; |
| 32 | |
| 33 | /// The prefix of the refs that record where the hub's refs were seen. A |
| 34 | /// `git sync` label always ends with a hash, so it is never `hub`. |
| 35 | pub(crate) const REMOTE_PREFIX: &str = "remote/hub/"; |
| 36 | |
| 37 | /// Where the hub's ref `name` was seen. |
| 38 | pub(crate) fn remote_ref(name: &str) -> String { |
| 39 | format!("{REMOTE_PREFIX}{name}") |
| 40 | } |
| 41 | |
| 42 | /// Whether a ref is a tag. |
| 43 | pub(crate) fn is_tag(name: &str) -> bool { |
| 44 | name.starts_with("tags/") |
| 45 | } |
| 46 | |
| 47 | /// Whether a hub ref is brought in: a branch or a tag. |
| 48 | pub(crate) fn is_carried(name: &str) -> bool { |
| 49 | braid_repo::is_branch(name) || is_tag(name) |
| 50 | } |
| 51 | |
| 52 | /// What became of a local ref. |
| 53 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 54 | pub(crate) enum Outcome { |
| 55 | /// It did not exist: it was created at the hub's head. |
| 56 | Created, |
| 57 | /// It moved forward to the hub's head. |
| 58 | Moved, |
| 59 | /// It was at the hub's head already. |
| 60 | Same, |
| 61 | /// It has changesets the hub lacks, on top of the hub's head: kept. |
| 62 | Ahead, |
| 63 | /// It and the hub each have changesets the other lacks: kept. |
| 64 | Diverged, |
| 65 | /// The hub's ref could not be brought in, for the reason given. |
| 66 | Skipped(&'static str), |
| 67 | } |
| 68 | |
| 69 | impl Outcome { |
| 70 | /// How JSON output names it. |
| 71 | pub(crate) fn code(self) -> &'static str { |
| 72 | match self { |
| 73 | Outcome::Created => "created", |
| 74 | Outcome::Moved => "moved", |
| 75 | Outcome::Same => "same", |
| 76 | Outcome::Ahead => "ahead", |
| 77 | Outcome::Diverged => "diverged", |
| 78 | Outcome::Skipped(_) => "skipped", |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | /// One of the hub's refs, and what became of the local ref of that name. |
| 84 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 85 | pub(crate) struct RefFetched { |
| 86 | /// The ref. |
| 87 | pub(crate) name: String, |
| 88 | /// The hub's head. |
| 89 | pub(crate) hub: ObjectId, |
| 90 | /// The local ref before. |
| 91 | pub(crate) before: Option<ObjectId>, |
| 92 | /// The local ref after. |
| 93 | pub(crate) after: Option<ObjectId>, |
| 94 | /// What happened. |
| 95 | pub(crate) outcome: Outcome, |
| 96 | } |
| 97 | |
| 98 | /// What a fetch did. |
| 99 | #[derive(Clone, Debug)] |
| 100 | pub(crate) struct Fetched { |
| 101 | /// The hub's op log sequence number when its refs were read. |
| 102 | pub(crate) seq: u64, |
| 103 | /// Every ref of the hub, as read. |
| 104 | pub(crate) hub_refs: BTreeMap<String, ObjectId>, |
| 105 | /// Objects stored. |
| 106 | pub(crate) objects: u64, |
| 107 | /// The hub's branches and tags, by name. |
| 108 | pub(crate) refs: Vec<RefFetched>, |
| 109 | /// The local op log operation that moved refs, if any did. |
| 110 | pub(crate) operation: Option<u64>, |
| 111 | } |
| 112 | |
| 113 | impl Fetched { |
| 114 | /// The hub's head of `branch`, if it has the branch. |
| 115 | pub(crate) fn hub_head(&self, branch: &str) -> Option<ObjectId> { |
| 116 | self.hub_refs.get(branch).copied() |
| 117 | } |
| 118 | |
| 119 | /// The heads of the hub's branches. |
| 120 | pub(crate) fn hub_branch_heads(&self) -> Vec<ObjectId> { |
| 121 | self.hub_refs |
| 122 | .iter() |
| 123 | .filter(|(name, _)| braid_repo::is_branch(name)) |
| 124 | .map(|(_, id)| *id) |
| 125 | .collect() |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | /// Whether the store holds `id` as a changeset. |
| 130 | fn holds_changeset(store: &Store, id: &ObjectId) -> Result<bool> { |
| 131 | Ok(matches!(store.stat(id)?, Some((Kind::Changeset, _)))) |
| 132 | } |
| 133 | |
| 134 | /// Whether `head` holds every changeset of `stack`, a stack as a landing |
| 135 | /// sends it, oldest first: its last changeset, or one rebased from it, is |
| 136 | /// on `head`'s first-parent chain, as after a fast-forward or a rebase; or |
| 137 | /// `head` has what each of them changes already, which is what a landing |
| 138 | /// that finds them there answers. `false` when the store does not hold |
| 139 | /// `head`. Nothing is written to the store. |
| 140 | pub(crate) fn holds(store: &Store, head: ObjectId, stack: &[ObjectId]) -> Result<bool> { |
| 141 | if !holds_changeset(store, &head)? { |
| 142 | return Ok(false); |
| 143 | } |
| 144 | let Some(&last) = stack.last() else { |
| 145 | return Ok(true); |
| 146 | }; |
| 147 | if landed_on(store, head, last)? { |
| 148 | return Ok(true); |
| 149 | } |
| 150 | let scratch = Scratch { |
| 151 | store, |
| 152 | written: RefCell::new(HashMap::new()), |
| 153 | }; |
| 154 | let checker = Signature { |
| 155 | name: b"braid".to_vec(), |
| 156 | email: b"braid@example.org".to_vec(), |
| 157 | seconds: 0, |
| 158 | offset_minutes: 0, |
| 159 | }; |
| 160 | for change in stack { |
| 161 | if !holds_changeset(store, change)? { |
| 162 | return Ok(false); |
| 163 | } |
| 164 | match braid_engine::land(&scratch, Some(head), *change, checker.clone()) { |
| 165 | Ok(LandOutcome::AlreadyApplied) => {} |
| 166 | Ok(_) => return Ok(false), |
| 167 | Err(err) if err.is_store_failure() => return Err(err.into()), |
| 168 | Err(_) => return Ok(false), |
| 169 | } |
| 170 | } |
| 171 | Ok(true) |
| 172 | } |
| 173 | |
| 174 | /// Whether `change`, or a changeset rebased from it, is on the first-parent |
| 175 | /// chain of `head`, above `change`'s own first parent. |
| 176 | fn landed_on(store: &Store, head: ObjectId, change: ObjectId) -> Result<bool> { |
| 177 | let base = read_changeset(store, change)?.parents.first().copied(); |
| 178 | let origin = change.to_hex().into_bytes(); |
| 179 | let mut current = Some(head); |
| 180 | while let Some(id) = current { |
| 181 | if id == change { |
| 182 | return Ok(true); |
| 183 | } |
| 184 | if Some(id) == base { |
| 185 | return Ok(false); |
| 186 | } |
| 187 | let changeset = read_changeset(store, id)?; |
| 188 | if changeset |
| 189 | .extras |
| 190 | .iter() |
| 191 | .any(|(key, value)| key.as_slice() == REBASED_FROM && *value == origin) |
| 192 | { |
| 193 | return Ok(true); |
| 194 | } |
| 195 | current = changeset.parents.first().copied(); |
| 196 | } |
| 197 | Ok(false) |
| 198 | } |
| 199 | |
| 200 | /// The store, with what is written kept in memory instead: for checks that |
| 201 | /// run the engine, and must leave the store as it was. |
| 202 | struct Scratch<'s> { |
| 203 | store: &'s Store, |
| 204 | written: RefCell<HashMap<ObjectId, (Kind, Vec<u8>)>>, |
| 205 | } |
| 206 | |
| 207 | impl Objects for Scratch<'_> { |
| 208 | type Error = <Store as Objects>::Error; |
| 209 | |
| 210 | fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Self::Error> { |
| 211 | if let Some((kind, payload)) = self.written.borrow().get(id) { |
| 212 | return Ok(Some((*kind, payload.clone()))); |
| 213 | } |
| 214 | self.store.get(id) |
| 215 | } |
| 216 | |
| 217 | fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Self::Error> { |
| 218 | let id = ObjectId::hash(kind, payload); |
| 219 | self.written |
| 220 | .borrow_mut() |
| 221 | .entry(id) |
| 222 | .or_insert_with(|| (kind, payload.to_vec())); |
| 223 | Ok(id) |
| 224 | } |
| 225 | |
| 226 | fn contains(&self, id: &ObjectId) -> Result<bool, Self::Error> { |
| 227 | Ok(self.written.borrow().contains_key(id) || self.store.contains(id)?) |
| 228 | } |
| 229 | |
| 230 | fn stat(&self, id: &ObjectId) -> Result<Option<(Kind, u64)>, Self::Error> { |
| 231 | if let Some((kind, payload)) = self.written.borrow().get(id) { |
| 232 | return Ok(Some((*kind, payload.len() as u64))); |
| 233 | } |
| 234 | self.store.stat(id) |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | /// What the store holds with everything it reaches: the heads of local |
| 239 | /// branches and of `remote/hub/` refs, and `extra`. |
| 240 | pub(crate) fn haves(store: &Store, refs: &Refs, extra: &[ObjectId]) -> Result<Vec<ObjectId>> { |
| 241 | let mut found = BTreeSet::new(); |
| 242 | for (name, id) in refs.iter() { |
| 243 | if (braid_repo::is_branch(name) || name.starts_with(REMOTE_PREFIX)) |
| 244 | && holds_changeset(store, &id)? |
| 245 | { |
| 246 | found.insert(id); |
| 247 | } |
| 248 | } |
| 249 | found.extend(extra); |
| 250 | Ok(found.into_iter().collect()) |
| 251 | } |
| 252 | |
| 253 | /// Brings in what holding `want` takes, through `/missing` streams whose |
| 254 | /// lists hold no more ids than the hub takes in one: `want` goes in parts, |
| 255 | /// and `have`, which only saves sending what is here already, is cut short. |
| 256 | fn bring( |
| 257 | store: &Store, |
| 258 | remote: &impl Remote, |
| 259 | link: &Link, |
| 260 | want: Vec<ObjectId>, |
| 261 | mut have: Vec<ObjectId>, |
| 262 | ) -> Result<u64> { |
| 263 | if want.is_empty() { |
| 264 | return Ok(0); |
| 265 | } |
| 266 | let most = if want.len() > 1 || have.len() > 1 { |
| 267 | remote.max_ids().max(1) |
| 268 | } else { |
| 269 | 1 |
| 270 | }; |
| 271 | have.truncate(most); |
| 272 | let mut objects = 0; |
| 273 | for part in want.chunks(most) { |
| 274 | let request = MissingRequest { |
| 275 | want: part.to_vec(), |
| 276 | have: have.clone(), |
| 277 | history: None, |
| 278 | paths: link.paths.clone(), |
| 279 | limit: None, |
| 280 | after: None, |
| 281 | }; |
| 282 | let body = remote.missing(&request)?; |
| 283 | let received = store_stream(store, body)?; |
| 284 | for id in &request.want { |
| 285 | if !holds_changeset(store, id)? { |
| 286 | bail!("the hub's object stream did not hold changeset {id}, which was asked for"); |
| 287 | } |
| 288 | } |
| 289 | whole(store, &received, link.prefixes().as_deref())?; |
| 290 | objects += received.objects; |
| 291 | } |
| 292 | Ok(objects) |
| 293 | } |
| 294 | |
| 295 | /// Checks that what a stream brought is whole, before any ref moves to it: |
| 296 | /// each changeset's change list and git origin are stored, and so is |
| 297 | /// everything each tree node it brought names, along the paths of a sparse |
| 298 | /// repository. A node the store held already came whole before. |
| 299 | pub(crate) fn whole(store: &Store, received: &Received, paths: Option<&[Vec<u8>]>) -> Result<()> { |
| 300 | let brought: HashSet<ObjectId> = received.trees.iter().copied().collect(); |
| 301 | let need = |id: ObjectId, what: &str, by: ObjectId| -> Result<()> { |
| 302 | if store.contains(&id)? { |
| 303 | Ok(()) |
| 304 | } else { |
| 305 | bail!( |
| 306 | "the hub's object stream did not hold {what} {id}, which {by} needs: nothing moved here; run the command again" |
| 307 | ) |
| 308 | } |
| 309 | }; |
| 310 | let mut walked = HashSet::new(); |
| 311 | for &id in &received.changesets { |
| 312 | let changeset = read_changeset(store, id)?; |
| 313 | if let Changes::External { list, .. } = &changeset.changes { |
| 314 | need(*list, "the change list", id)?; |
| 315 | } |
| 316 | if let Some(origin) = changeset.git_origin { |
| 317 | need(origin, "the git origin", id)?; |
| 318 | } |
| 319 | let mut pending = vec![(changeset.root, Vec::new())]; |
| 320 | while let Some((node, dir)) = pending.pop() { |
| 321 | if node == braid_engine::EMPTY_TREE |
| 322 | || !brought.contains(&node) |
| 323 | || !walked.insert((node, dir.clone())) |
| 324 | { |
| 325 | continue; |
| 326 | } |
| 327 | let Some((_, bytes)) = store.get(&node)? else { |
| 328 | bail!("tree {node} went missing from the store"); |
| 329 | }; |
| 330 | match Node::decode(&bytes).map_err(|err| anyhow!("tree {node}: {err}"))? { |
| 331 | Node::Flat(entries) | Node::Leaf(entries) => { |
| 332 | for entry in entries { |
| 333 | let path = if dir.is_empty() { |
| 334 | entry.name.clone() |
| 335 | } else { |
| 336 | [&dir[..], b"/", &entry.name].concat() |
| 337 | }; |
| 338 | if !wanted(paths, &path) { |
| 339 | continue; |
| 340 | } |
| 341 | match entry.kind { |
| 342 | EntryKind::File { blob, .. } |
| 343 | | EntryKind::Executable { blob, .. } |
| 344 | | EntryKind::Symlink { blob, .. } => need(blob, "blob", node)?, |
| 345 | EntryKind::Tree { tree } => { |
| 346 | need(tree, "tree", node)?; |
| 347 | pending.push((tree, path)); |
| 348 | } |
| 349 | EntryKind::Gitlink { .. } => {} |
| 350 | } |
| 351 | } |
| 352 | } |
| 353 | Node::Internal { children, .. } => { |
| 354 | for child in children { |
| 355 | need(child.node, "tree", node)?; |
| 356 | pending.push((child.node, dir.clone())); |
| 357 | } |
| 358 | } |
| 359 | } |
| 360 | } |
| 361 | } |
| 362 | Ok(()) |
| 363 | } |
| 364 | |
| 365 | /// Whether a sparse repository holds what is at `path`: it is on the way to |
| 366 | /// one of `paths`, or under one. Everything, without `paths`. |
| 367 | fn wanted(paths: Option<&[Vec<u8>]>, path: &[u8]) -> bool { |
| 368 | let Some(prefixes) = paths else { |
| 369 | return true; |
| 370 | }; |
| 371 | prefixes.iter().any(|prefix| { |
| 372 | let on_the_way = prefix.starts_with(path) |
| 373 | && (prefix.len() == path.len() || path.is_empty() || prefix[path.len()] == b'/'); |
| 374 | let under = path.starts_with(prefix) |
| 375 | && (path.len() == prefix.len() || prefix.is_empty() || path[prefix.len()] == b'/'); |
| 376 | on_the_way || under |
| 377 | }) |
| 378 | } |
| 379 | |
| 380 | /// Whether the hub refused to send what was asked: an id it does not hold |
| 381 | /// (404), or holds as another kind (400). |
| 382 | fn refused(err: &anyhow::Error) -> bool { |
| 383 | matches!( |
| 384 | err.downcast_ref::<HubError>(), |
| 385 | Some(HubError::Api { |
| 386 | status: 400 | 404, |
| 387 | .. |
| 388 | }) |
| 389 | ) |
| 390 | } |
| 391 | |
| 392 | /// A branch, and the stack a landing just put on it on the hub. |
| 393 | pub(crate) type Landed<'a> = (&'a str, &'a [ObjectId]); |
| 394 | |
| 395 | /// Fetches from the hub into `repo`, recording the operation as `agent`. |
| 396 | /// |
| 397 | /// `landed` names a branch and the stack a landing just put on it: when |
| 398 | /// the local branch's head is one of those changesets, it moves to the |
| 399 | /// hub's head even if that is not a fast-forward, once that head holds its |
| 400 | /// changes, rebased. |
| 401 | pub(crate) fn fetch( |
| 402 | repo: &Repo, |
| 403 | remote: &impl Remote, |
| 404 | link: &Link, |
| 405 | agent: &str, |
| 406 | landed: Option<Landed<'_>>, |
| 407 | ) -> Result<Fetched> { |
| 408 | let hub = remote.refs()?; |
| 409 | let store = repo.store(); |
| 410 | let local = store.refs()?; |
| 411 | let carried: Vec<(String, ObjectId)> = hub |
| 412 | .refs |
| 413 | .iter() |
| 414 | .filter(|(name, _)| is_carried(name)) |
| 415 | .map(|(name, id)| (name.clone(), *id)) |
| 416 | .collect(); |
| 417 | |
| 418 | // What a local ref points at is whole, and so is the stack a landing |
| 419 | // just sent, which this repository made. Anything else the hub's refs |
| 420 | // name is asked for, even when the store holds it: a stream that broke |
| 421 | // half way may have left it there without all it needs. The hub sends |
| 422 | // nothing that the `have` changesets reach. |
| 423 | let sent: &[ObjectId] = landed.map_or(&[], |(_, stack)| stack); |
| 424 | let pointed: HashSet<ObjectId> = local |
| 425 | .iter() |
| 426 | .map(|(_, id)| id) |
| 427 | .chain(sent.iter().copied()) |
| 428 | .collect(); |
| 429 | |
| 430 | // Branches first: their heads are changesets. |
| 431 | let mut branch_heads = BTreeSet::new(); |
| 432 | for (name, id) in &carried { |
| 433 | if !is_tag(name) && !pointed.contains(id) { |
| 434 | branch_heads.insert(*id); |
| 435 | } |
| 436 | } |
| 437 | let branch_heads: Vec<ObjectId> = branch_heads.into_iter().collect(); |
| 438 | let mut objects = bring( |
| 439 | store, |
| 440 | remote, |
| 441 | link, |
| 442 | branch_heads.clone(), |
| 443 | haves(store, &local, sent)?, |
| 444 | )?; |
| 445 | |
| 446 | // Then tags, which may name anything: most name a changeset that came |
| 447 | // with the branches; the hub is asked about the others. A tag whose |
| 448 | // target the hub gives no valid kind or stream for is skipped, saying |
| 449 | // why: one odd tag never stops a fetch. |
| 450 | let mut skipped: HashMap<String, &'static str> = HashMap::new(); |
| 451 | let mut tag_targets: BTreeMap<ObjectId, Vec<String>> = BTreeMap::new(); |
| 452 | for (name, id) in carried.iter().filter(|(name, _)| is_tag(name)) { |
| 453 | let kind = match store.stat(id)? { |
| 454 | Some((kind, _)) => Some(kind), |
| 455 | None => match remote.kind(id) { |
| 456 | Ok(kind) => kind, |
| 457 | Err(HubError::Protocol(_)) => { |
| 458 | skipped.insert( |
| 459 | name.clone(), |
| 460 | "the hub gives no valid kind for the object it names", |
| 461 | ); |
| 462 | continue; |
| 463 | } |
| 464 | Err(err) => return Err(err.into()), |
| 465 | }, |
| 466 | }; |
| 467 | match kind { |
| 468 | Some(Kind::Changeset) => { |
| 469 | if !pointed.contains(id) { |
| 470 | tag_targets.entry(*id).or_default().push(name.clone()); |
| 471 | } |
| 472 | } |
| 473 | Some(_) => { |
| 474 | skipped.insert( |
| 475 | name.clone(), |
| 476 | "it names an object that is not a changeset, such as an annotated tag, which the hub protocol cannot carry", |
| 477 | ); |
| 478 | } |
| 479 | None => { |
| 480 | skipped.insert(name.clone(), "the hub does not hold what it names"); |
| 481 | } |
| 482 | } |
| 483 | } |
| 484 | let have = haves(store, &local, &[&branch_heads[..], sent].concat())?; |
| 485 | let targets: Vec<ObjectId> = tag_targets.keys().copied().collect(); |
| 486 | match bring(store, remote, link, targets.clone(), have.clone()) { |
| 487 | Ok(brought) => objects += brought, |
| 488 | // One at a time, then, leaving out what the hub will not send. |
| 489 | Err(err) if refused(&err) => { |
| 490 | for target in targets { |
| 491 | match bring(store, remote, link, vec![target], have.clone()) { |
| 492 | Ok(brought) => objects += brought, |
| 493 | Err(err) if refused(&err) => { |
| 494 | for name in &tag_targets[&target] { |
| 495 | skipped.insert( |
| 496 | name.clone(), |
| 497 | "the hub does not send the changeset it names", |
| 498 | ); |
| 499 | } |
| 500 | } |
| 501 | Err(err) => return Err(err), |
| 502 | } |
| 503 | } |
| 504 | } |
| 505 | Err(err) => return Err(err), |
| 506 | } |
| 507 | |
| 508 | let mut history = repo.history(); |
| 509 | let mut decided = Vec::new(); |
| 510 | let description = format!("hub fetch {} from {}", link.repo, link.url); |
| 511 | let result = store.transact_with(agent, |current| -> Result<_, Option<anyhow::Error>> { |
| 512 | let mut updates = Vec::new(); |
| 513 | for (name, hub_head) in &carried { |
| 514 | let before = current.get(name); |
| 515 | let outcome = match skipped.get(name) { |
| 516 | Some(reason) => Outcome::Skipped(reason), |
| 517 | None => { |
| 518 | let seen = remote_ref(name); |
| 519 | if current.get(&seen) != Some(*hub_head) { |
| 520 | updates.push(RefUpdate::new( |
| 521 | seen.clone(), |
| 522 | current.get(&seen), |
| 523 | Some(*hub_head), |
| 524 | )); |
| 525 | } |
| 526 | decide(&mut history, store, name, before, *hub_head, landed).map_err(Some)? |
| 527 | } |
| 528 | }; |
| 529 | let after = match outcome { |
| 530 | Outcome::Created | Outcome::Moved => { |
| 531 | updates.push(RefUpdate::new(name.clone(), before, Some(*hub_head))); |
| 532 | Some(*hub_head) |
| 533 | } |
| 534 | _ => before, |
| 535 | }; |
| 536 | decided.push(RefFetched { |
| 537 | name: name.clone(), |
| 538 | hub: *hub_head, |
| 539 | before, |
| 540 | after, |
| 541 | outcome, |
| 542 | }); |
| 543 | } |
| 544 | // A ref the hub no longer has, or that cannot be carried, has no |
| 545 | // place where it was seen. |
| 546 | for (name, id) in current.iter() { |
| 547 | if let Some(rest) = name.strip_prefix(REMOTE_PREFIX) |
| 548 | && (!carried.iter().any(|(carried, _)| carried == rest) |
| 549 | || skipped.contains_key(rest)) |
| 550 | { |
| 551 | updates.push(RefUpdate::new(name, Some(id), None)); |
| 552 | } |
| 553 | } |
| 554 | if updates.is_empty() { |
| 555 | return Err(None); |
| 556 | } |
| 557 | Ok((updates, description)) |
| 558 | }); |
| 559 | let operation = match result { |
| 560 | Ok(op) => Some(op.seq), |
| 561 | Err(TransactError::Aborted(None)) => None, |
| 562 | Err(TransactError::Aborted(Some(err))) => return Err(err), |
| 563 | Err(TransactError::Store(err)) => return Err(err.into()), |
| 564 | }; |
| 565 | history.flush()?; |
| 566 | Ok(Fetched { |
| 567 | seq: hub.seq, |
| 568 | hub_refs: hub.refs, |
| 569 | objects, |
| 570 | refs: decided, |
| 571 | operation, |
| 572 | }) |
| 573 | } |
| 574 | |
| 575 | /// What becomes of the local ref `name`, at `before`, given the hub's head. |
| 576 | fn decide( |
| 577 | history: &mut RepoHistory<'_>, |
| 578 | store: &Store, |
| 579 | name: &str, |
| 580 | before: Option<ObjectId>, |
| 581 | hub: ObjectId, |
| 582 | landed: Option<Landed<'_>>, |
| 583 | ) -> Result<Outcome> { |
| 584 | let Some(local) = before else { |
| 585 | return Ok(Outcome::Created); |
| 586 | }; |
| 587 | if local == hub { |
| 588 | return Ok(Outcome::Same); |
| 589 | } |
| 590 | // A tag never moves, and a ref that names no changeset is no branch to |
| 591 | // move forward. |
| 592 | if is_tag(name) || !holds_changeset(store, &local)? { |
| 593 | return Ok(Outcome::Diverged); |
| 594 | } |
| 595 | let on_chain = |history: &mut RepoHistory<'_>, head: ObjectId, base: ObjectId| { |
| 596 | history |
| 597 | .first_parent_chain_contains(head, base, usize::MAX) |
| 598 | .map_err(|err| anyhow!(err)) |
| 599 | }; |
| 600 | // The branch follows a landing that rebased its head only when the |
| 601 | // hub's head holds what the branch has of the stack: never back. |
| 602 | let rebased_here = match landed { |
| 603 | Some((branch, stack)) if branch == name => match stack.iter().position(|id| *id == local) { |
| 604 | Some(at) => holds(store, hub, &stack[..=at])?, |
| 605 | None => false, |
| 606 | }, |
| 607 | _ => false, |
| 608 | }; |
| 609 | if rebased_here || on_chain(history, hub, local)? { |
| 610 | Ok(Outcome::Moved) |
| 611 | } else if on_chain(history, local, hub)? { |
| 612 | Ok(Outcome::Ahead) |
| 613 | } else { |
| 614 | Ok(Outcome::Diverged) |
| 615 | } |
| 616 | } |
| 617 | |
| 618 | #[cfg(test)] |
| 619 | mod tests { |
| 620 | use super::*; |
| 621 | use crate::hub::testing::{FakeHub, Fixture, ada_change, set_ref}; |
| 622 | |
| 623 | fn outcome(fetched: &Fetched, name: &str) -> Outcome { |
| 624 | fetched |
| 625 | .refs |
| 626 | .iter() |
| 627 | .find(|r| r.name == name) |
| 628 | .unwrap_or_else(|| panic!("no {name} in {:?}", fetched.refs)) |
| 629 | .outcome |
| 630 | } |
| 631 | |
| 632 | #[test] |
| 633 | fn branches_move_forward_only() { |
| 634 | let hub = FakeHub::new(); |
| 635 | let local = Fixture::linked(&hub); |
| 636 | let root = ada_change(&hub.repo, None, &[("a.txt", "a\n")]); |
| 637 | let two = ada_change(&hub.repo, Some(root), &[("b.txt", "b\n")]); |
| 638 | set_ref(&hub.repo, "main", two); |
| 639 | set_ref(&hub.repo, "behind", two); |
| 640 | set_ref(&hub.repo, "ahead", root); |
| 641 | set_ref(&hub.repo, "diverged", two); |
| 642 | set_ref(&hub.repo, "tags/v1", root); |
| 643 | set_ref(&hub.repo, "braid/internal", root); |
| 644 | |
| 645 | // The first fetch creates everything it carries. |
| 646 | let first = fetch(&local.repo, &hub, &local.link, "tester", None).unwrap(); |
| 647 | assert!(first.objects > 0); |
| 648 | for name in ["main", "behind", "ahead", "diverged", "tags/v1"] { |
| 649 | assert_eq!(outcome(&first, name), Outcome::Created, "{name}"); |
| 650 | } |
| 651 | let refs = local.repo.store().refs().unwrap(); |
| 652 | assert_eq!(refs.get("main"), Some(two)); |
| 653 | assert_eq!(refs.get("tags/v1"), Some(root)); |
| 654 | assert_eq!(refs.get("remote/hub/main"), Some(two)); |
| 655 | assert_eq!(refs.get("braid/internal"), None, "internal refs stay"); |
| 656 | assert!(first.refs.iter().all(|r| r.name != "braid/internal")); |
| 657 | |
| 658 | // Local work and hub work. |
| 659 | let three = ada_change(&hub.repo, Some(two), &[("c.txt", "c\n")]); |
| 660 | set_ref(&hub.repo, "behind", three); |
| 661 | set_ref(&hub.repo, "diverged", three); |
| 662 | let mine = ada_change(&local.repo, Some(root), &[("mine.txt", "m\n")]); |
| 663 | set_ref(&local.repo, "ahead", mine); |
| 664 | let other = ada_change(&local.repo, Some(two), &[("other.txt", "o\n")]); |
| 665 | set_ref(&local.repo, "diverged", other); |
| 666 | set_ref(&local.repo, "tags/v1", two); |
| 667 | |
| 668 | let second = fetch(&local.repo, &hub, &local.link, "tester", None).unwrap(); |
| 669 | assert_eq!(outcome(&second, "main"), Outcome::Same); |
| 670 | assert_eq!(outcome(&second, "behind"), Outcome::Moved); |
| 671 | assert_eq!(outcome(&second, "ahead"), Outcome::Ahead); |
| 672 | assert_eq!(outcome(&second, "diverged"), Outcome::Diverged); |
| 673 | assert_eq!( |
| 674 | outcome(&second, "tags/v1"), |
| 675 | Outcome::Diverged, |
| 676 | "tags never move" |
| 677 | ); |
| 678 | let refs = local.repo.store().refs().unwrap(); |
| 679 | assert_eq!(refs.get("behind"), Some(three)); |
| 680 | assert_eq!(refs.get("ahead"), Some(mine)); |
| 681 | assert_eq!(refs.get("diverged"), Some(other)); |
| 682 | // The hub's head has a name even where the branch was kept. |
| 683 | assert_eq!(refs.get("remote/hub/diverged"), Some(three)); |
| 684 | assert!(local.repo.store().contains(&three).unwrap()); |
| 685 | |
| 686 | // Nothing new: no operation. |
| 687 | let third = fetch(&local.repo, &hub, &local.link, "tester", None).unwrap(); |
| 688 | assert_eq!(third.objects, 0); |
| 689 | assert_eq!(third.operation, None); |
| 690 | |
| 691 | // A landing that rebased a local branch's head lets that branch, and |
| 692 | // no other, follow: the hub's head holds the changeset, rebased. |
| 693 | set_ref(&local.repo, "behind", other); |
| 694 | crate::hub::transfer::upload( |
| 695 | local.repo.store(), |
| 696 | &hub, |
| 697 | &braid_engine::Reach { |
| 698 | want: &[other], |
| 699 | ..braid_engine::Reach::default() |
| 700 | }, |
| 701 | ) |
| 702 | .unwrap(); |
| 703 | let signature = Signature { |
| 704 | name: b"BraidHub".to_vec(), |
| 705 | email: b"hub@example.org".to_vec(), |
| 706 | seconds: 1_700_000_000, |
| 707 | offset_minutes: 0, |
| 708 | }; |
| 709 | let Ok(LandOutcome::Rebased { changeset, .. }) = |
| 710 | braid_engine::land(hub.repo.store(), Some(three), other, signature) |
| 711 | else { |
| 712 | panic!("other rebases onto three"); |
| 713 | }; |
| 714 | hub.repo.store().sync().unwrap(); |
| 715 | set_ref(&hub.repo, "diverged", changeset); |
| 716 | let landed: &[ObjectId] = &[other]; |
| 717 | let fourth = fetch( |
| 718 | &local.repo, |
| 719 | &hub, |
| 720 | &local.link, |
| 721 | "tester", |
| 722 | Some(("diverged", landed)), |
| 723 | ) |
| 724 | .unwrap(); |
| 725 | assert_eq!(outcome(&fourth, "diverged"), Outcome::Moved); |
| 726 | assert_eq!(outcome(&fourth, "behind"), Outcome::Diverged); |
| 727 | } |
| 728 | |
| 729 | #[test] |
| 730 | fn tags_that_name_no_changeset_are_skipped() { |
| 731 | let hub = FakeHub::new(); |
| 732 | let local = Fixture::linked(&hub); |
| 733 | let root = ada_change(&hub.repo, None, &[("a.txt", "a\n")]); |
| 734 | let side = ada_change(&hub.repo, Some(root), &[("side.txt", "s\n")]); |
| 735 | set_ref(&hub.repo, "main", root); |
| 736 | // A tag on a changeset no branch has, and one on a blob. |
| 737 | set_ref(&hub.repo, "tags/side", side); |
| 738 | let blob = hub |
| 739 | .repo |
| 740 | .store() |
| 741 | .put(Kind::Blob, b"object 1234\ntype commit\n") |
| 742 | .unwrap(); |
| 743 | hub.repo.store().sync().unwrap(); |
| 744 | set_ref(&hub.repo, "tags/annotated", blob); |
| 745 | let fetched = fetch(&local.repo, &hub, &local.link, "tester", None).unwrap(); |
| 746 | assert_eq!(outcome(&fetched, "tags/side"), Outcome::Created); |
| 747 | assert!(matches!( |
| 748 | outcome(&fetched, "tags/annotated"), |
| 749 | Outcome::Skipped(_) |
| 750 | )); |
| 751 | let refs = local.repo.store().refs().unwrap(); |
| 752 | assert_eq!(refs.get("tags/side"), Some(side)); |
| 753 | assert_eq!(refs.get("tags/annotated"), None); |
| 754 | assert_eq!(refs.get("remote/hub/tags/annotated"), None); |
| 755 | } |
| 756 | |
| 757 | #[test] |
| 758 | fn a_sparse_link_brings_only_its_paths() { |
| 759 | let hub = FakeHub::new(); |
| 760 | let root = ada_change( |
| 761 | &hub.repo, |
| 762 | None, |
| 763 | &[("src/net/tcp.rs", "tcp\n"), ("docs/big.md", "docs\n")], |
| 764 | ); |
| 765 | set_ref(&hub.repo, "main", root); |
| 766 | let mut local = Fixture::linked(&hub); |
| 767 | local.link.paths = Some(vec!["src/net".to_owned()]); |
| 768 | fetch(&local.repo, &hub, &local.link, "tester", None).unwrap(); |
| 769 | let store = local.repo.store(); |
| 770 | assert!(store.contains(&root).unwrap()); |
| 771 | let tcp = ObjectId::hash(Kind::Blob, b"tcp\n"); |
| 772 | let docs = ObjectId::hash(Kind::Blob, b"docs\n"); |
| 773 | assert!(store.contains(&tcp).unwrap()); |
| 774 | assert!(!store.contains(&docs).unwrap()); |
| 775 | } |
| 776 | } |