Elffuss BraidHub

utopia-ia/elffuss-braid public

2da7deeea818 · 5.6 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! How each branch of a linked repository compares with the hub's, for
5//! `braid hub status`.
6
7use std::collections::{BTreeMap, BTreeSet};
8
9use anyhow::Result;
10use braid_format::{Kind, ObjectId, Objects};
11use braid_repo::Repo;
12
13use super::fetch::remote_ref;
14
15/// How a branch compares with the hub's.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub(crate) enum State {
18 /// Both at the same changeset.
19 Same,
20 /// The hub's has changesets this one lacks, on top of it; or only the
21 /// hub has the branch. `braid hub fetch` brings them in.
22 Behind,
23 /// This one has changesets the hub lacks, on top of the hub's; or only
24 /// this repository has the branch.
25 Ahead,
26 /// Each has changesets the other lacks.
27 Diverged,
28}
29
30impl State {
31 /// How output names it.
32 pub(crate) fn code(self) -> &'static str {
33 match self {
34 State::Same => "same",
35 State::Behind => "behind",
36 State::Ahead => "ahead",
37 State::Diverged => "diverged",
38 }
39 }
40}
41
42/// One branch, here and on the hub.
43#[derive(Clone, Debug, PartialEq, Eq)]
44pub(crate) struct BranchState {
45 /// The branch.
46 pub(crate) name: String,
47 /// Its head here.
48 pub(crate) local: Option<ObjectId>,
49 /// Its head on the hub.
50 pub(crate) hub: Option<ObjectId>,
51 /// How they compare.
52 pub(crate) state: State,
53}
54
55/// Compares every branch of `repo` and of the hub, whose refs are `hub`.
56///
57/// When the hub's head is not in the store yet, the hub moved since the
58/// last fetch, and a hub's branch only ever moves forward: a branch at, or
59/// below, where the hub's was last seen (`remote/hub/<branch>`) is behind,
60/// and any other is diverged.
61pub(crate) fn compare(repo: &Repo, hub: &BTreeMap<String, ObjectId>) -> Result<Vec<BranchState>> {
62 let store = repo.store();
63 let local = store.refs()?;
64 let names: BTreeSet<&str> = local
65 .iter()
66 .map(|(name, _)| name)
67 .chain(hub.keys().map(String::as_str))
68 .filter(|name| braid_repo::is_branch(name))
69 .collect();
70 let holds = |id: &ObjectId| -> Result<bool> {
71 Ok(matches!(store.stat(id)?, Some((Kind::Changeset, _))))
72 };
73 let mut history = repo.history();
74 let mut on_chain = |head: ObjectId, base: ObjectId| -> Result<bool> {
75 Ok(history.first_parent_chain_contains(head, base, usize::MAX)?)
76 };
77 let mut states = Vec::new();
78 for name in names {
79 let (here, there) = (local.get(name), hub.get(name).copied());
80 let state = match (here, there) {
81 (Some(here), Some(there)) if here == there => State::Same,
82 (Some(here), Some(there)) if holds(&here)? && holds(&there)? => {
83 if on_chain(there, here)? {
84 State::Behind
85 } else if on_chain(here, there)? {
86 State::Ahead
87 } else {
88 State::Diverged
89 }
90 }
91 (Some(here), Some(there)) if holds(&here)? && !holds(&there)? => {
92 match local.get(&remote_ref(name)) {
93 Some(seen) if holds(&seen)? && (seen == here || on_chain(seen, here)?) => {
94 State::Behind
95 }
96 _ => State::Diverged,
97 }
98 }
99 (Some(_), Some(_)) => State::Diverged,
100 (None, _) => State::Behind,
101 (Some(_), None) => State::Ahead,
102 };
103 states.push(BranchState {
104 name: name.to_owned(),
105 local: here,
106 hub: there,
107 state,
108 });
109 }
110 history.flush()?;
111 Ok(states)
112}
113
114#[cfg(test)]
115mod tests {
116 use super::*;
117 use crate::hub::testing::{Fixture, ada_change, set_ref};
118
119 #[test]
120 fn each_branch_against_the_hub() {
121 let f = Fixture::new();
122 let root = ada_change(&f.repo, None, &[("a.txt", "a\n")]);
123 let two = ada_change(&f.repo, Some(root), &[("b.txt", "b\n")]);
124 let other = ada_change(&f.repo, Some(root), &[("c.txt", "c\n")]);
125 for name in ["same", "behind", "ahead", "diverged", "local-only"] {
126 set_ref(&f.repo, name, root);
127 }
128 set_ref(&f.repo, "ahead", two);
129 set_ref(&f.repo, "diverged", other);
130 set_ref(&f.repo, "tags/v1", root);
131 // The hub moved past what this repository holds, from where it was
132 // last seen.
133 let unknown = ObjectId::hash(Kind::Changeset, b"not fetched");
134 set_ref(&f.repo, "moved", root);
135 set_ref(&f.repo, "remote/hub/moved", root);
136 set_ref(&f.repo, "lost", two);
137 set_ref(&f.repo, "remote/hub/lost", other);
138
139 let hub: BTreeMap<String, ObjectId> = [
140 ("same", root),
141 ("behind", two),
142 ("ahead", root),
143 ("diverged", two),
144 ("hub-only", two),
145 ("moved", unknown),
146 ("lost", unknown),
147 ("tags/v1", two),
148 ]
149 .into_iter()
150 .map(|(name, id)| (name.to_owned(), id))
151 .collect();
152 let states = compare(&f.repo, &hub).unwrap();
153 let found: Vec<(&str, State)> = states.iter().map(|s| (s.name.as_str(), s.state)).collect();
154 assert_eq!(
155 found,
156 [
157 ("ahead", State::Ahead),
158 ("behind", State::Behind),
159 ("diverged", State::Diverged),
160 ("hub-only", State::Behind),
161 ("local-only", State::Ahead),
162 ("lost", State::Diverged),
163 ("moved", State::Behind),
164 ("same", State::Same),
165 ]
166 );
167 }
168}