Elffuss BraidHub

utopia-ia/elffuss-braid public

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