Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 9.7 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Putting every branch and tag of a repository on the hub, for `braid hub
5//! publish`: everything their changesets reach goes up, less what the hub
6//! has, then each ref is landed fast-forward-only: its head alone, which
7//! creates a ref the hub does not have, or, for a branch the hub has
8//! further down its first-parent chain, the changesets above the hub's
9//! head. A tag the hub has elsewhere is left alone: tags never move.
10//!
11//! The protocol lands changesets only. A ref that names anything else,
12//! such as an annotated tag imported from git (a blob holding the tag's
13//! bytes), cannot be created on the hub: it is skipped and reported.
14
15use anyhow::Result;
16use braid_engine::{Reach, read_changeset};
17use braid_format::{Kind, ObjectId, Objects};
18use braid_hubproto::api::{LandMode, LandRequest};
19use braid_repo::Repo;
20
21use super::fetch::{is_carried, is_tag};
22use super::land::{OffBranch, land};
23use super::remote::Remote;
24use super::transfer::{Sent, upload};
25
26/// Why a ref that names no changeset is not published.
27pub(crate) const NOT_A_CHANGESET: &str = "it names an object that is not a changeset, such as an annotated tag, which the hub protocol cannot create";
28
29/// Why a git ref that is neither a branch nor a tag is not published.
30pub(crate) const NOT_A_BRANCH: &str = "a git ref that is neither a branch nor a tag";
31
32/// A ref put on the hub, and how its landing went.
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub(crate) struct PublishedRef {
35 /// The ref.
36 pub(crate) name: String,
37 /// Its head here.
38 pub(crate) id: ObjectId,
39 /// The landing's outcome: `fast-forward` (created or moved forward),
40 /// `already-applied`, or `refused` when the hub's ref is not on this
41 /// one's first-parent chain (for a tag: anywhere else).
42 pub(crate) outcome: String,
43 /// The hub's head of the ref before: `None` when the landing made it.
44 pub(crate) head_before: Option<ObjectId>,
45 /// The hub's head of the ref afterwards.
46 pub(crate) head: Option<ObjectId>,
47}
48
49/// What publishing did.
50#[derive(Clone, Debug, Default)]
51pub(crate) struct Published {
52 /// What was uploaded.
53 pub(crate) sent: Sent,
54 /// The refs landed, branches first.
55 pub(crate) refs: Vec<PublishedRef>,
56 /// The refs left out, with why.
57 pub(crate) skipped: Vec<(String, &'static str)>,
58}
59
60/// Uploads every branch and tag of `repo` to the hub and lands each one.
61pub(crate) fn publish_refs(repo: &Repo, remote: &impl Remote, agent: &str) -> Result<Published> {
62 let store = repo.store();
63 let mut published = Published::default();
64 let mut branches = Vec::new();
65 let mut tags = Vec::new();
66 for (name, id) in store.refs()?.iter() {
67 if name.starts_with("braid/") || name.starts_with("remote/") {
68 continue;
69 }
70 if !is_carried(name) {
71 published.skipped.push((name.to_owned(), NOT_A_BRANCH));
72 } else if !matches!(store.stat(&id)?, Some((Kind::Changeset, _))) {
73 published.skipped.push((name.to_owned(), NOT_A_CHANGESET));
74 } else if is_tag(name) {
75 tags.push((name.to_owned(), id));
76 } else {
77 branches.push((name.to_owned(), id));
78 }
79 }
80 let mut heads: Vec<ObjectId> = branches.iter().chain(&tags).map(|(_, id)| *id).collect();
81 heads.sort();
82 heads.dedup();
83 published.sent = upload(
84 store,
85 remote,
86 &Reach {
87 want: &heads,
88 ..Reach::default()
89 },
90 )?;
91 let hub_refs = remote.refs()?.refs;
92 let mut history = repo.history();
93 for (name, id) in branches.into_iter().chain(tags) {
94 let on_hub = hub_refs.get(&name).copied();
95 let changes = match on_hub {
96 None => vec![id],
97 Some(head)
98 if head != id
99 && !is_tag(&name)
100 && history.first_parent_chain_contains(id, head, usize::MAX)? =>
101 {
102 above(store, id, head)?
103 }
104 // There already, or somewhere it cannot be moved forward from.
105 Some(head) => {
106 published.refs.push(PublishedRef {
107 name,
108 id,
109 outcome: if head == id {
110 "already-applied"
111 } else {
112 "refused"
113 }
114 .to_owned(),
115 head_before: Some(head),
116 head: Some(head),
117 });
118 continue;
119 }
120 };
121 // In stacks no longer than the hub takes, each a fast-forward of
122 // the one before. A fast-forward-only landing is refused, never off
123 // the branch.
124 let request = |part: &[ObjectId]| LandRequest {
125 reference: name.clone(),
126 changes: part.to_vec(),
127 mode: LandMode::FfOnly,
128 agent: Some(agent.to_owned()),
129 };
130 let mut parts = changes.chunks(remote.max_ids().max(1));
131 let first = parts.next().unwrap_or_default();
132 let mut response = land(store, remote, &request(first), OffBranch::Stack)?;
133 let head_before = response.head_before;
134 for part in parts {
135 if response.outcome != "fast-forward" {
136 break;
137 }
138 response = land(store, remote, &request(part), OffBranch::Stack)?;
139 }
140 published.refs.push(PublishedRef {
141 name,
142 id,
143 outcome: response.outcome,
144 head_before,
145 head: response.head,
146 });
147 }
148 history.flush()?;
149 Ok(published)
150}
151
152/// The changesets from `base` (excluded) up to `head` along first parents,
153/// oldest first; `base` must be on the chain.
154fn above(objects: &impl Objects, head: ObjectId, base: ObjectId) -> Result<Vec<ObjectId>> {
155 let mut stack = Vec::new();
156 let mut current = head;
157 while current != base {
158 stack.push(current);
159 current = read_changeset(objects, current)?
160 .parents
161 .first()
162 .copied()
163 .ok_or_else(|| anyhow::anyhow!("{base} is not below {head}"))?;
164 }
165 stack.reverse();
166 Ok(stack)
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172 use crate::hub::testing::{FakeHub, Fixture, ada_change, set_ref};
173 use braid_engine::reachable;
174
175 #[test]
176 fn every_branch_and_tag_goes_up() {
177 let local = Fixture::new();
178 let root = ada_change(&local.repo, None, &[("a.txt", "a\n")]);
179 let two = ada_change(&local.repo, Some(root), &[("dir/b.txt", "b\n")]);
180 let side = ada_change(&local.repo, Some(root), &[("side.txt", "s\n")]);
181 set_ref(&local.repo, "main", two);
182 set_ref(&local.repo, "feature", side);
183 set_ref(&local.repo, "tags/v1", root);
184 let blob = local.repo.store().put(Kind::Blob, b"tag bytes").unwrap();
185 local.repo.store().sync().unwrap();
186 set_ref(&local.repo, "tags/annotated", blob);
187 set_ref(&local.repo, "git/refs/notes/commits", root);
188 set_ref(&local.repo, "remote/origin-0123456789ab/main", root);
189
190 let hub = FakeHub::new();
191 let published = publish_refs(&local.repo, &hub, "agent-1").unwrap();
192 let names: Vec<&str> = published.refs.iter().map(|r| r.name.as_str()).collect();
193 assert_eq!(names, ["feature", "main", "tags/v1"]);
194 assert!(published.refs.iter().all(|r| r.outcome == "fast-forward"));
195 let skipped: Vec<&str> = published.skipped.iter().map(|(n, _)| n.as_str()).collect();
196 assert_eq!(skipped, ["git/refs/notes/commits", "tags/annotated"]);
197
198 let refs = hub.repo.store().refs().unwrap();
199 assert_eq!(refs.get("main"), Some(two));
200 assert_eq!(refs.get("feature"), Some(side));
201 assert_eq!(refs.get("tags/v1"), Some(root));
202 assert_eq!(refs.get("tags/annotated"), None);
203 // The hub holds the whole history, and was sent each object once.
204 let all = reachable(
205 local.repo.store(),
206 &Reach {
207 want: &[two, side],
208 ..Reach::default()
209 },
210 )
211 .unwrap();
212 for object in &all {
213 assert!(hub.repo.store().contains(&object.id).unwrap());
214 }
215 assert_eq!(published.sent.objects, all.len() as u64);
216
217 // Publishing again sends nothing and lands nothing new.
218 let lands = hub.called("land");
219 let again = publish_refs(&local.repo, &hub, "agent-1").unwrap();
220 assert_eq!(again.sent.objects, 0);
221 assert!(again.refs.iter().all(|r| r.outcome == "already-applied"));
222 assert_eq!(hub.called("land"), lands);
223
224 // A branch that moved on by several changesets goes up as a
225 // fast-forward of all of them; one that went elsewhere, and a tag
226 // moved here, are refused.
227 let three = ada_change(&local.repo, Some(two), &[("c.txt", "c\n")]);
228 let four = ada_change(&local.repo, Some(three), &[("d.txt", "d\n")]);
229 set_ref(&local.repo, "main", four);
230 let elsewhere = ada_change(&local.repo, Some(root), &[("e.txt", "e\n")]);
231 set_ref(&local.repo, "feature", elsewhere);
232 set_ref(&local.repo, "tags/v1", two);
233 let moved = publish_refs(&local.repo, &hub, "agent-1").unwrap();
234 let outcome = |name: &str| {
235 moved
236 .refs
237 .iter()
238 .find(|r| r.name == name)
239 .map(|r| r.outcome.clone())
240 .unwrap()
241 };
242 assert_eq!(outcome("main"), "fast-forward");
243 assert_eq!(outcome("feature"), "refused");
244 assert_eq!(outcome("tags/v1"), "refused");
245 let refs = hub.repo.store().refs().unwrap();
246 assert_eq!(refs.get("main"), Some(four));
247 assert_eq!(refs.get("feature"), Some(side));
248 assert_eq!(refs.get("tags/v1"), Some(root));
249 }
250}