Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 29.1 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Landing in a linked repository: the stack goes to the hub, which lands
5//! it with the others, and the workspace then moves onto the head that
6//! holds it, as after a local landing.
7//!
8//! 1. Fetch, so that the local branch is the hub's. A workspace that
9//! cannot land (uncommitted changes, a rebase in progress) says so
10//! first, as a local landing does, before anything goes to the hub.
11//! 2. [`Workspace::stack`]: the workspace's changesets the branch lacks,
12//! after any changesets of the local branch below them that the hub's
13//! branch lacks, such as those landed here with `--local`.
14//! 3. Upload what the hub lacks of them: the objects the stack reaches
15//! beyond its base and the hub's head, less what `lacks` says it holds.
16//! 4. `POST land`, in `rebase` mode, naming the agent.
17//! 5. Fetch again, and [`Workspace::adopt`] the new head, when the branch
18//! moved or already had the changes, and the head holds the stack.
19//!
20//! A failure at any step leaves the local branches where the hub has them
21//! and the workspace as it was, and says what to run next: running the
22//! same landing again finishes the job, since the hub answers
23//! `already-applied` to a stack it has landed.
24
25use anyhow::{Context, Result, bail};
26use braid_engine::{Reach, read_changeset};
27use braid_format::ObjectId;
28use braid_hubproto::api::{LandMode, LandRequest, LandResponse};
29use braid_repo::Repo;
30use braid_store::Store;
31use braid_wc::{Stack, Workspace};
32
33use super::fetch::{Fetched, fetch, holds};
34use super::link::Link;
35use super::remote::{HubError, Remote};
36use super::transfer::{upload, upload_missing};
37
38/// How many times a landing is sent when the hub answers that objects are
39/// missing: once, and again after each upload of what it named.
40const ATTEMPTS: usize = 3;
41
42/// A workspace's landing on the hub.
43#[derive(Debug)]
44pub(crate) struct HubLanding {
45 /// The branch.
46 pub(crate) branch: String,
47 /// The hub's answer, or `None` when there was nothing to land.
48 pub(crate) response: Option<LandResponse>,
49 /// The hub's head of the branch when the landing started.
50 pub(crate) head: Option<ObjectId>,
51 /// The workspace's base afterwards.
52 pub(crate) base: Option<ObjectId>,
53 /// The paths of the working copy written or removed.
54 pub(crate) updated_paths: Vec<Vec<u8>>,
55}
56
57/// Lands the workspace's changesets on `onto` (by default its branch) on
58/// the hub, and moves the workspace onto the head that holds them.
59pub(crate) fn land_workspace(
60 repo: &Repo,
61 workspace: &Workspace<'_>,
62 remote: &impl Remote,
63 link: &Link,
64 onto: Option<&str>,
65 agent: &str,
66) -> Result<HubLanding> {
67 workspace.stack(onto)?;
68 let fetched = fetch(repo, remote, link, agent, None).context(
69 "cannot fetch from the hub, so nothing was landed: run `braid land` again once it answers, or `braid land --local` to land in this repository instead",
70 )?;
71 let stack = workspace.stack(onto)?;
72 let head = fetched.hub_head(&stack.branch);
73 let changes = hub_stack(repo, &stack, head, &fetched)?;
74 let Some(&last) = changes.last() else {
75 // A workspace at the hub's head, as after a landing whose answer
76 // was lost, takes it as where its own changesets start, as a
77 // landing would have made it.
78 if let Some(head) = head
79 && stack.base == Some(head)
80 {
81 workspace.adopt(stack.base, head)?;
82 }
83 return Ok(HubLanding {
84 branch: stack.branch,
85 response: None,
86 head,
87 base: stack.base,
88 updated_paths: Vec::new(),
89 });
90 };
91 let most = remote.max_ids();
92 if changes.len() > most {
93 bail!(
94 "this landing is a stack of {} changesets, more than the {most} the hub takes in one landing, so nothing was sent: `braid land --local` lands them here, and `braid hub publish` then sends them to the hub in parts, as fast-forwards",
95 changes.len()
96 );
97 }
98 // Changesets below the workspace's own that the hub's branch had once,
99 // and no longer has, were taken off it on purpose: they go back only
100 // when asked.
101 if changes.len() > stack.changes.len()
102 && let Some(seen) = once_on_hub(repo, &stack.branch, changes[0])?
103 {
104 let now = match head {
105 Some(head) => format!("is at {} now", head.short()),
106 None => "is gone now".to_owned(),
107 };
108 bail!(
109 "the hub's {} no longer has {} of the changesets below this workspace's own: it was at {} when this repository saw it, and {now}, so someone took them off, and landing would put them back; nothing was sent. To put them back on purpose, `braid land --local` lands here and `braid hub publish` sends the branch as it is here; to leave them out, ask whoever took them off",
110 stack.branch,
111 crate::work::count(changes.len() - stack.changes.len(), "changeset"),
112 seen.short()
113 );
114 }
115 let store = repo.store();
116 let base = read_changeset(store, changes[0])?.parents.first().copied();
117 let have: Vec<ObjectId> = base.into_iter().chain(head).collect();
118 send_stack(store, remote, link, last, &have, changes.len()).context(
119 "cannot upload the changesets to the hub, so nothing was landed: run `braid land` again, which sends only what the hub still lacks",
120 )?;
121 let request = LandRequest {
122 reference: stack.branch.clone(),
123 changes: changes.clone(),
124 mode: LandMode::Rebase,
125 agent: Some(agent.to_owned()),
126 };
127 let response = land(store, remote, &request, OffBranch::Stack)
128 .map_err(|err| not_landed(err, &format!("its {}", stack.branch), "braid land"))?;
129 let (base, updated_paths) = match response.outcome.as_str() {
130 "fast-forward" | "rebased" | "already-applied" => {
131 let new_head = response.head.with_context(|| {
132 format!(
133 "the hub answered {} without a head: nothing moved here; run `braid land` again",
134 response.outcome
135 )
136 })?;
137 fetch(repo, remote, link, agent, Some((&stack.branch, &changes))).map_err(|err| {
138 let next = if refused_credentials(&err) {
139 "once signed in again, run `braid land`"
140 } else {
141 "run `braid land` again"
142 };
143 err.context(format!(
144 "{} landed on the hub's {} as {}, but fetching it failed: {next} to bring it here and move the workspace onto it",
145 last.short(),
146 stack.branch,
147 new_head.short()
148 ))
149 })?;
150 // The hub's answer must hold what was sent before the workspace
151 // takes it: a stale or confused answer would lose the stack.
152 if !holds(store, new_head, &changes)? {
153 bail!(
154 "the hub answered {} with {} as the head of its {}, which does not hold {}: nothing moved here; run `braid land` again, and if the hub answers the same, its operator should look at it",
155 response.outcome,
156 new_head.short(),
157 stack.branch,
158 last.short()
159 );
160 }
161 let updated = workspace.adopt(stack.base, new_head).map_err(|err| {
162 anyhow::Error::new(err).context(format!(
163 "{} landed on the hub's {} as {}, but the workspace could not be moved onto it; once that is fixed, run `braid land` again",
164 last.short(),
165 stack.branch,
166 new_head.short()
167 ))
168 })?;
169 (Some(new_head), updated)
170 }
171 "conflicts" => (stack.base, Vec::new()),
172 other => bail!(
173 "the hub answered `{other}` to the landing on its {}: {} did not land, and nothing moved here",
174 stack.branch,
175 last.short()
176 ),
177 };
178 Ok(HubLanding {
179 branch: stack.branch,
180 response: Some(response),
181 head,
182 base,
183 updated_paths,
184 })
185}
186
187/// Lands one changeset, made without a working copy, on `branch` of the
188/// hub, then fetches. Every error names the changeset, and whether it
189/// landed; when the answer was lost, it says to run `again`, the command
190/// that made the changeset, once more.
191pub(crate) fn land_change(
192 repo: &Repo,
193 remote: &impl Remote,
194 link: &Link,
195 branch: &str,
196 change: ObjectId,
197 agent: &str,
198 again: &str,
199) -> Result<LandResponse> {
200 let store = repo.store();
201 let base = read_changeset(store, change)?.parents.first().copied();
202 let have: Vec<ObjectId> = base.into_iter().collect();
203 send_stack(store, remote, link, change, &have, 1).with_context(|| {
204 format!("cannot upload changeset {change} to the hub, so it did not land on {branch}")
205 })?;
206 let request = LandRequest {
207 reference: branch.to_owned(),
208 changes: vec![change],
209 mode: LandMode::Rebase,
210 agent: Some(agent.to_owned()),
211 };
212 let response = land(store, remote, &request, OffBranch::Change { base })
213 .map_err(|err| not_landed(err, &format!("its {branch} (changeset {change})"), again))?;
214 let landed = match response.outcome.as_str() {
215 "fast-forward" | "rebased" | "already-applied" => true,
216 "conflicts" => false,
217 other => bail!(
218 "the hub answered `{other}` to the landing of changeset {change} on its {branch}: it did not land"
219 ),
220 };
221 fetch(repo, remote, link, agent, None).with_context(|| {
222 if landed {
223 format!(
224 "changeset {change} landed on the hub's {branch} as {}, but fetching it failed: `braid hub fetch` brings it in",
225 crate::work::short(response.head)
226 )
227 } else {
228 format!(
229 "changeset {change} did not land on the hub's {branch}, and fetching what is there failed: `braid hub fetch` brings it in"
230 )
231 }
232 })?;
233 Ok(response)
234}
235
236/// What a landing whose request failed says, on top of why: when the
237/// answer was lost, that the hub may have landed the stack, and that the
238/// same command again lands it or finds it landed (`already-applied`);
239/// otherwise that nothing landed. The errors of a local landing, which a
240/// refusal such as `not_on_branch` becomes, stay as they are.
241fn not_landed(err: anyhow::Error, on: &str, again: &str) -> anyhow::Error {
242 if err.downcast_ref::<braid_wc::Error>().is_some() {
243 return err;
244 }
245 match err.downcast_ref::<HubError>() {
246 Some(hub) if hub.may_have_happened() => err.context(format!(
247 "cannot tell whether the hub landed this on {on}, since its answer was lost: run `{again}` again, which lands it or finds it landed already"
248 )),
249 Some(hub) if hub.unauthorized() || hub.rate_limited() => err.context(
250 format!("nothing was landed on {on}: run `{again}` again once that is settled"),
251 ),
252 _ => err.context(format!("nothing was landed on {on}")),
253 }
254}
255
256/// Whether `err` comes from a hub that refused the credentials.
257fn refused_credentials(err: &anyhow::Error) -> bool {
258 err.chain().any(|cause| {
259 cause
260 .downcast_ref::<HubError>()
261 .is_some_and(HubError::unauthorized)
262 })
263}
264
265/// The changesets to land on the hub: the workspace's own, after those of
266/// the local branch below them that the hub's branch does not have yet,
267/// such as changesets landed here with `--local`, so that the hub can
268/// take them in order. When the hub has no such branch, the walk down
269/// stops at the first changeset on any of its branches.
270pub(crate) fn hub_stack(
271 repo: &Repo,
272 stack: &Stack,
273 head: Option<ObjectId>,
274 fetched: &Fetched,
275) -> Result<Vec<ObjectId>> {
276 let Some(base) = stack.base else {
277 return Ok(Vec::new());
278 };
279 let store = repo.store();
280 let heads = match head {
281 Some(head) => vec![head],
282 None => fetched.hub_branch_heads(),
283 };
284 let mut below = match stack.changes.first() {
285 Some(first) => read_changeset(store, *first)?.parents.first().copied(),
286 None => Some(base),
287 };
288 let mut history = repo.history();
289 let mut extra = Vec::new();
290 while let Some(id) = below {
291 let mut on_hub = false;
292 for head in &heads {
293 if history.first_parent_chain_contains(*head, id, usize::MAX)? {
294 on_hub = true;
295 break;
296 }
297 }
298 if on_hub {
299 break;
300 }
301 extra.push(id);
302 below = read_changeset(store, id)?.parents.first().copied();
303 }
304 history.flush()?;
305 extra.reverse();
306 extra.extend(&stack.changes);
307 Ok(extra)
308}
309
310/// How far back the op log is read for where the hub's branches were seen.
311const SEEN_OPERATIONS: usize = 100_000;
312
313/// Where the hub's `branch` was seen, by a fetch that then saw it elsewhere
314/// (`remote/hub/<branch>` before it moved or went, as the op log keeps it),
315/// when that head had `oldest` on its first-parent chain: the hub had the
316/// changeset there once.
317pub(crate) fn once_on_hub(repo: &Repo, branch: &str, oldest: ObjectId) -> Result<Option<ObjectId>> {
318 let seen_ref = super::fetch::remote_ref(branch);
319 let mut heads = Vec::new();
320 let mut listed = std::collections::HashSet::new();
321 for operation in repo.store().log(SEEN_OPERATIONS)? {
322 for update in &operation.updates {
323 if update.name == seen_ref
324 && let Some(old) = update.old
325 && listed.insert(old)
326 {
327 heads.push(old);
328 }
329 }
330 }
331 let mut history = repo.history();
332 let mut found = None;
333 for head in heads {
334 if head == oldest || history.first_parent_chain_contains(head, oldest, usize::MAX)? {
335 found = Some(head);
336 break;
337 }
338 }
339 history.flush()?;
340 Ok(found)
341}
342
343/// Uploads what the hub lacks of a stack of `len` changesets ending at
344/// `last`, beyond what `have` reaches. A sparse clone holds only part of
345/// each tree, so it walks its paths instead, and the hub's `lacks` sorts
346/// out what it has.
347pub(crate) fn send_stack(
348 store: &Store,
349 remote: &impl Remote,
350 link: &Link,
351 last: ObjectId,
352 have: &[ObjectId],
353 len: usize,
354) -> Result<()> {
355 let prefixes = link.prefixes();
356 let want = [last];
357 let reach = Reach {
358 want: &want,
359 have: if prefixes.is_some() { &[] } else { have },
360 history: Some(u32::try_from(len.saturating_sub(1)).unwrap_or(u32::MAX)),
361 paths: prefixes.as_deref(),
362 max_objects: None,
363 };
364 upload(store, remote, &reach)?;
365 Ok(())
366}
367
368/// What landed, for the error a refusal with `not_on_branch` becomes: the
369/// one the same landing gives in a local repository.
370#[derive(Clone, Copy, Debug)]
371pub(crate) enum OffBranch {
372 /// A workspace's stack, as `braid land` lands it.
373 Stack,
374 /// One changeset made without a working copy, on `base`, as `braid
375 /// change create --land` lands it.
376 Change {
377 /// The changeset's first parent.
378 base: Option<ObjectId>,
379 },
380}
381
382/// Sends a landing, uploading what the hub says is missing and sending it
383/// again; `not_on_branch` is the error a local landing gives.
384pub(crate) fn land(
385 store: &Store,
386 remote: &impl Remote,
387 request: &LandRequest,
388 off_branch: OffBranch,
389) -> Result<LandResponse> {
390 let mut attempt = 1;
391 loop {
392 match remote.land(request) {
393 Ok(response) => return Ok(response),
394 Err(err) if err.code() == Some("missing") && attempt < ATTEMPTS => {
395 let ids = err.missing_ids().to_vec();
396 if ids.is_empty() {
397 return Err(err.into());
398 }
399 upload_missing(store, remote, &ids)?;
400 attempt += 1;
401 }
402 Err(err) if err.code() == Some("not_on_branch") => {
403 let branch = request.reference.clone();
404 return Err(match off_branch {
405 OffBranch::Stack => braid_wc::Error::NotOnBranch { branch },
406 OffBranch::Change { base } => {
407 // The local error names the head, which the
408 // refusal gives; a hub that leaves it out is asked.
409 let given = match &err {
410 HubError::Api { body, .. } => {
411 body.head.as_deref().and_then(|head| head.parse().ok())
412 }
413 _ => None,
414 };
415 let head = given.or_else(|| {
416 remote
417 .refs()
418 .ok()
419 .and_then(|refs| refs.refs.get(&branch).copied())
420 });
421 braid_wc::Error::from(braid_engine::Error::BaseNotOnBranch { base, head })
422 }
423 }
424 .into());
425 }
426 Err(err) => return Err(err.into()),
427 }
428 }
429}
430
431#[cfg(test)]
432mod tests {
433 use super::*;
434 use crate::hub::fetch::fetch;
435 use crate::hub::testing::{FakeHub, Fixture, ada, ada_change, set_ref};
436 use braid_wc::CommitRequest;
437 use std::fs;
438
439 /// A linked repository holding the hub's `main`, with a workspace on it.
440 struct Setup {
441 hub: FakeHub,
442 local: Fixture,
443 }
444
445 impl Setup {
446 fn new() -> Setup {
447 let hub = FakeHub::new();
448 let root = ada_change(
449 &hub.repo,
450 None,
451 &[("a.txt", "one\ntwo\nthree\n"), ("b.txt", "b\n")],
452 );
453 set_ref(&hub.repo, "main", root);
454 let local = Fixture::linked(&hub);
455 fetch(&local.repo, &hub, &local.link, "tester", None).unwrap();
456 Setup { hub, local }
457 }
458
459 fn workspace(&self, name: &str) -> Workspace<'_> {
460 let repo = &self.local.repo;
461 let head = repo.store().refs().unwrap().get("main");
462 let dir = Workspace::default_dir(repo, name);
463 Workspace::create(repo, name, &dir, head, "main").unwrap().0
464 }
465
466 fn hub_main(&self) -> Option<ObjectId> {
467 self.hub.repo.store().refs().unwrap().get("main")
468 }
469
470 fn local_main(&self) -> Option<ObjectId> {
471 self.local.repo.store().refs().unwrap().get("main")
472 }
473
474 fn land(&self, ws: &Workspace<'_>) -> Result<HubLanding> {
475 land_workspace(
476 &self.local.repo,
477 ws,
478 &self.hub,
479 &self.local.link,
480 None,
481 "agent-1",
482 )
483 }
484 }
485
486 fn edit_and_commit(ws: &Workspace<'_>, path: &str, content: &str) -> ObjectId {
487 fs::write(ws.dir().join(path), content).unwrap();
488 ws.commit(&CommitRequest {
489 message: Some(format!("edit {path}").into_bytes()),
490 paths: Vec::new(),
491 author: None,
492 committer: ada(),
493 agent: "agent-1".to_owned(),
494 force: false,
495 })
496 .unwrap()
497 .changeset
498 .unwrap()
499 }
500
501 #[test]
502 fn a_fast_forward_moves_the_hub_the_branch_and_the_workspace() {
503 let s = Setup::new();
504 let ws = s.workspace("w1");
505 let mine = edit_and_commit(&ws, "c.txt", "c\n");
506 let landing = s.land(&ws).unwrap();
507 let response = landing.response.as_ref().unwrap();
508 assert_eq!(response.outcome, "fast-forward");
509 assert_eq!(response.head, Some(mine));
510 assert_eq!(s.hub_main(), Some(mine));
511 assert_eq!(s.local_main(), Some(mine));
512 assert_eq!(landing.base, Some(mine));
513 assert_eq!(ws.state().unwrap().base, Some(mine));
514 assert_eq!(ws.state().unwrap().upstream, Some(mine));
515 // The agent label reached the hub's op log.
516 assert_eq!(s.hub.repo.store().log(1).unwrap()[0].agent, "agent-1");
517 // Landing again finds nothing to land, and asks the hub nothing.
518 let lands = s.hub.called("land");
519 let again = s.land(&ws).unwrap();
520 assert!(again.response.is_none());
521 assert_eq!(again.head, Some(mine));
522 assert_eq!(s.hub.called("land"), lands);
523 }
524
525 #[test]
526 fn a_landing_reports_what_the_hub_says_of_the_branch() {
527 let s = Setup::new();
528 let ws = s.workspace("w1");
529 let mine = edit_and_commit(&ws, "c.txt", "c\n");
530 s.hub.verify.borrow_mut().landing = Some(braid_hubproto::verify::LandVerify {
531 state: braid_hubproto::verify::STATE_RED.to_owned(),
532 green: None,
533 red: Some(mine),
534 culprit: Some(mine),
535 reverted: Vec::new(),
536 });
537 let landing = s.land(&ws).unwrap();
538 let report = crate::work::Report::hub(landing.response.as_ref().unwrap());
539 let json = report.json();
540 assert_eq!(json["hub_verify"]["state"], "red");
541 assert_eq!(json["hub_verify"]["culprit"], mine.to_hex());
542 assert_eq!(json["hub_verify"]["reverted"], serde_json::json!([]));
543 // A hub that says nothing of the branch: null.
544 s.hub.verify.borrow_mut().landing = None;
545 let two = edit_and_commit(&ws, "d.txt", "d\n");
546 let landing = s.land(&ws).unwrap();
547 let report = crate::work::Report::hub(landing.response.as_ref().unwrap());
548 assert_eq!(report.head, Some(two));
549 assert_eq!(report.json()["hub_verify"], serde_json::Value::Null);
550 }
551
552 #[test]
553 fn a_rebase_on_the_hub_brings_the_others_work_into_the_workspace() {
554 let s = Setup::new();
555 let ws = s.workspace("w1");
556 let mine = edit_and_commit(&ws, "c.txt", "c\n");
557 // Someone else lands first, on the hub.
558 let before = s.hub_main().unwrap();
559 let theirs = ada_change(&s.hub.repo, Some(before), &[("d.txt", "theirs\n")]);
560 set_ref(&s.hub.repo, "main", theirs);
561
562 let landing = s.land(&ws).unwrap();
563 let response = landing.response.as_ref().unwrap();
564 assert_eq!(response.outcome, "rebased");
565 assert_eq!(response.head_before, Some(theirs));
566 let head = response.head.unwrap();
567 assert_ne!(head, mine);
568 assert_eq!(response.landed[0].from, mine);
569 assert_eq!(response.landed[0].to, Some(head));
570 assert_eq!(s.hub_main(), Some(head));
571 assert_eq!(s.local_main(), Some(head));
572 assert_eq!(ws.state().unwrap().base, Some(head));
573 assert_eq!(landing.updated_paths, [b"d.txt".to_vec()]);
574 assert_eq!(
575 fs::read_to_string(ws.dir().join("d.txt")).unwrap(),
576 "theirs\n"
577 );
578 assert_eq!(fs::read_to_string(ws.dir().join("c.txt")).unwrap(), "c\n");
579 }
580
581 #[test]
582 fn conflicts_leave_everything_where_it_was() {
583 let s = Setup::new();
584 let ws = s.workspace("w1");
585 let mine = edit_and_commit(&ws, "a.txt", "one\nmine\nthree\n");
586 let before = s.hub_main().unwrap();
587 let theirs = ada_change(
588 &s.hub.repo,
589 Some(before),
590 &[("a.txt", "one\ntheirs\nthree\n")],
591 );
592 set_ref(&s.hub.repo, "main", theirs);
593
594 let landing = s.land(&ws).unwrap();
595 let response = landing.response.as_ref().unwrap();
596 assert_eq!(response.outcome, "conflicts");
597 assert_eq!(response.change, Some(mine));
598 assert_eq!(response.conflicts.len(), 1);
599 assert_eq!(response.conflicts[0]["path"], "a.txt");
600 assert_eq!(response.conflicts[0]["kind"], "CONTENT");
601 assert_eq!(s.hub_main(), Some(theirs));
602 assert_eq!(landing.base, Some(mine));
603 assert!(landing.updated_paths.is_empty());
604 assert_eq!(ws.state().unwrap().base, Some(mine));
605 // The fetch before the landing brought the hub's head in.
606 assert_eq!(s.local_main(), Some(theirs));
607 }
608
609 #[test]
610 fn what_the_hub_finds_missing_is_sent_and_the_landing_sent_again() {
611 let s = Setup::new();
612 let ws = s.workspace("w1");
613 let mine = edit_and_commit(&ws, "c.txt", "c\n");
614 s.hub.forgetful.set(true);
615 let landing = s.land(&ws).unwrap();
616 assert_eq!(landing.response.unwrap().outcome, "fast-forward");
617 assert_eq!(s.hub.called("land"), 2);
618 assert_eq!(s.hub_main(), Some(mine));
619 }
620
621 #[test]
622 fn a_workspace_that_cannot_land_says_so_before_asking_the_hub() {
623 let s = Setup::new();
624 let ws = s.workspace("w1");
625 fs::write(ws.dir().join("c.txt"), "not committed\n").unwrap();
626 let calls = s.hub.calls.borrow().len();
627 let err = s.land(&ws).unwrap_err().to_string();
628 assert!(err.contains("uncommitted changes"), "{err}");
629 assert_eq!(s.hub.calls.borrow().len(), calls);
630 }
631
632 #[test]
633 fn not_on_branch_is_the_local_error() {
634 let s = Setup::new();
635 let ws = s.workspace("w1");
636 edit_and_commit(&ws, "c.txt", "c\n");
637 s.hub.off_branch.set(true);
638 let err = s.land(&ws).unwrap_err();
639 let local = braid_wc::Error::NotOnBranch {
640 branch: "main".to_owned(),
641 };
642 assert_eq!(err.to_string(), local.to_string());
643 assert!(matches!(
644 err.downcast_ref::<braid_wc::Error>(),
645 Some(braid_wc::Error::NotOnBranch { .. })
646 ));
647 }
648
649 #[test]
650 fn changesets_landed_here_with_local_go_up_first() {
651 let s = Setup::new();
652 // One workspace lands locally, as --local does.
653 let w1 = s.workspace("w1");
654 let local_only = edit_and_commit(&w1, "local.txt", "l\n");
655 let report = w1.land(None, "agent-1", &ada()).unwrap();
656 assert_eq!(report.head(), Some(local_only));
657 // Another workspace, on top of it, lands on the hub.
658 let w2 = s.workspace("w2");
659 let mine = edit_and_commit(&w2, "c.txt", "c\n");
660 let landing = s.land(&w2).unwrap();
661 let response = landing.response.unwrap();
662 assert_eq!(response.outcome, "fast-forward");
663 let froms: Vec<ObjectId> = response.landed.iter().map(|p| p.from).collect();
664 assert_eq!(froms, [local_only, mine]);
665 assert_eq!(s.hub_main(), Some(mine));
666 assert_eq!(s.local_main(), Some(mine));
667 }
668
669 #[test]
670 fn a_change_off_the_branch_gives_the_local_error() {
671 let s = Setup::new();
672 let base = s.local_main().unwrap();
673 let change = ada_change(&s.local.repo, Some(base), &[("new.txt", "n\n")]);
674 s.hub.off_branch.set(true);
675 let err = land_change(
676 &s.local.repo,
677 &s.hub,
678 &s.local.link,
679 "main",
680 change,
681 "agent-1",
682 "braid change create",
683 )
684 .unwrap_err();
685 let local = braid_engine::Error::BaseNotOnBranch {
686 base: Some(base),
687 head: s.hub_main(),
688 };
689 assert_eq!(err.to_string(), local.to_string());
690 }
691
692 #[test]
693 fn a_change_lands_as_a_stack_of_one() {
694 let s = Setup::new();
695 let base = s.local_main().unwrap();
696 let change = ada_change(&s.local.repo, Some(base), &[("new.txt", "n\n")]);
697 let response = land_change(
698 &s.local.repo,
699 &s.hub,
700 &s.local.link,
701 "main",
702 change,
703 "agent-1",
704 "braid change create",
705 )
706 .unwrap();
707 assert_eq!(response.outcome, "fast-forward");
708 assert_eq!(s.hub_main(), Some(change));
709 assert_eq!(s.local_main(), Some(change));
710 }
711
712 #[test]
713 fn a_revert_lands_on_the_hub_rebased_over_later_work() {
714 let s = Setup::new();
715 let base = s.local_main().unwrap();
716 let culprit = ada_change(&s.local.repo, Some(base), &[("b.txt", "bad\n")]);
717 let later = ada_change(&s.local.repo, Some(culprit), &[("c.txt", "c\n")]);
718 for change in [culprit, later] {
719 let response = land_change(
720 &s.local.repo,
721 &s.hub,
722 &s.local.link,
723 "main",
724 change,
725 "agent-1",
726 "braid change create",
727 )
728 .unwrap();
729 assert_eq!(response.outcome, "fast-forward");
730 }
731 let revert = braid_wc::create_revert(
732 s.local.repo.store(),
733 &braid_wc::RevertRequest {
734 culprit,
735 mainline: false,
736 author: ada(),
737 agent: "verifier".to_owned(),
738 },
739 )
740 .unwrap();
741 let response = land_change(
742 &s.local.repo,
743 &s.hub,
744 &s.local.link,
745 "main",
746 revert,
747 "verifier",
748 "braid revert",
749 )
750 .unwrap();
751 assert_eq!(response.outcome, "rebased");
752 let head = s.hub_main().unwrap();
753 assert_eq!(s.local_main(), Some(head));
754 let store = s.local.repo.store();
755 let root = braid_engine::read_changeset(store, head).unwrap().root;
756 let file = |path: &str| match braid_engine::entry_at(store, root, path.as_bytes()) {
757 Ok(Some(braid_format::EntryKind::File { blob, .. })) => {
758 braid_engine::read_blob(store, blob).unwrap()
759 }
760 other => panic!("{path}: {other:?}"),
761 };
762 assert_eq!(file("b.txt"), b"b\n");
763 assert_eq!(file("c.txt"), b"c\n");
764 }
765}