Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 62.8 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! A workspace: a working copy on a branch, sharing the repository's store
5//! with every other workspace.
6//!
7//! Every operation that changes a workspace holds its lock from start to
8//! end, and reads the state only once it holds it, so two processes never
9//! change one workspace at once. Workspaces never wait for each other,
10//! except for the short op log transaction in which a landing moves a
11//! branch.
12
13use std::collections::{HashMap, HashSet};
14use std::fs;
15use std::io::{self, Read};
16use std::path::{Path, PathBuf};
17
18use braid_engine::{
19 Conflict, EMPTY_TREE, first_parent_chain_contains, read_changes, read_changeset,
20};
21use braid_format::{Change, ChangeOp, Kind, ObjectId, Objects, Signature};
22use braid_repo::{DIR, Repo, WORK_DIR, WORKSPACES_DIR, WorkspaceLink};
23use braid_store::{RefUpdate, Store, TransactError};
24
25use crate::blocker::{Blocker, blockers};
26use crate::cache::{self, Cache};
27use crate::checkout::{self, Mode, Plan};
28use crate::error::Error;
29use crate::fsprobe::FileSystem;
30use crate::identity::Identity;
31use crate::markers::has_markers;
32use crate::paths::{is_within, os_name, split_last};
33use crate::rebase::{First, Replayed, agent_extras, conflict_tree, rebased_extras, replay};
34use crate::safe::{Found, Root, Stat, StatKind, open_file, read_link};
35use crate::scan::{self, Delta, Scan};
36use crate::state::{Checkout, Lock, Rebase, RecordedConflict, State};
37use crate::status::{self, Status};
38use crate::tree::root_of;
39
40/// A workspace of a repository.
41#[derive(Debug)]
42pub struct Workspace<'r> {
43 repo: &'r Repo,
44 name: String,
45 dir: PathBuf,
46 state_dir: PathBuf,
47}
48
49/// How far `status` walks the branch's history to count how far ahead of
50/// the workspace it is.
51pub const BEHIND_LIMIT: usize = 5000;
52
53/// What `status` reports.
54#[derive(Clone, Debug)]
55pub struct StatusReport {
56 /// The workspace's state.
57 pub state: State,
58 /// How the working copy differs from the base.
59 pub status: Status,
60 /// The head of the workspace's branch, if the branch exists.
61 pub head: Option<ObjectId>,
62 /// The workspace's own changesets that the branch does not have yet,
63 /// oldest first. While a rebase is in progress they include the
64 /// changeset being rebased and those waiting after it, by the ids they
65 /// had before the rebase: none of them has landed.
66 pub unlanded: Vec<ObjectId>,
67 /// How many changesets the branch's head is ahead of the workspace:
68 /// those from the head down to the changeset the workspace's own start
69 /// from, along first parents. `None` when there are more than
70 /// [`BEHIND_LIMIT`].
71 pub behind_by: Option<usize>,
72 /// For a rebase in progress: the conflicts, each with whether conflict
73 /// markers remain in its file.
74 pub conflicts: Vec<(RecordedConflict, bool)>,
75 /// What stops [`Workspace::commit`] from recording the working copy as
76 /// it is: the reasons it refuses with.
77 pub blocking: Vec<Blocker>,
78}
79
80impl StatusReport {
81 /// Whether the branch has changesets that the workspace does not.
82 pub fn behind(&self) -> bool {
83 self.behind_by != Some(0)
84 }
85
86 /// Whether [`Workspace::commit`] would record a changeset now: there is
87 /// something to commit, or a rebase to finish, and nothing blocks it.
88 pub fn ready_to_commit(&self) -> bool {
89 self.blocking.is_empty() && (!self.status.is_clean() || self.state.rebase.is_some())
90 }
91}
92
93/// What `commit` asks for.
94#[derive(Clone, Debug)]
95pub struct CommitRequest {
96 /// The message; while a rebase is in progress, the rebased changeset's
97 /// message is used if there is none.
98 pub message: Option<Vec<u8>>,
99 /// Commit only what lies at or below these paths; everything if empty.
100 pub paths: Vec<Vec<u8>>,
101 /// The author, if given; otherwise the rebased changeset's author while
102 /// a rebase is in progress, and the committer otherwise.
103 pub author: Option<Identity>,
104 /// Who records the changeset.
105 pub committer: Identity,
106 /// The label of the agent making it, recorded as its
107 /// [`AGENT`](braid_engine::AGENT) field. While a rebase is in progress,
108 /// the rebased changeset's own agent stays, if it names one.
109 pub agent: String,
110 /// Commit even if conflict markers remain or conflicts are not marked
111 /// resolved; new files waiting for `braid track` stay out.
112 pub force: bool,
113}
114
115/// Where a rebase stands after a commit or an update.
116#[derive(Clone, Debug, PartialEq, Eq)]
117pub enum RebaseProgress {
118 /// No rebase was in progress.
119 None,
120 /// The rebase is finished: the workspace is at `tip`.
121 Finished {
122 /// The last rebased changeset.
123 tip: ObjectId,
124 },
125 /// The next changeset conflicts too: resolve and commit again.
126 Stopped {
127 /// The changeset that conflicts.
128 change: ObjectId,
129 /// Its conflicts.
130 conflicts: Vec<Conflict>,
131 },
132}
133
134/// What `commit` did.
135#[derive(Clone, Debug)]
136pub struct CommitOutcome {
137 /// The new changeset; `None` when a rebase finished with nothing left to
138 /// record.
139 pub changeset: Option<ObjectId>,
140 /// How many paths it changed.
141 pub changes: usize,
142 /// Whether it finished a rebase with the message given instead of the
143 /// rebased changeset's own.
144 pub message_replaced: bool,
145 /// Where the rebase in progress, if any, stands now.
146 pub rebase: RebaseProgress,
147}
148
149/// How a landing ended.
150#[derive(Clone, Debug, PartialEq, Eq)]
151pub enum Landed {
152 /// Nothing to land: the branch has the workspace's base already.
153 Nothing,
154 /// The branch moved to the change itself.
155 FastForward(ObjectId),
156 /// The change was rebased onto the head; the branch moved to the result.
157 Rebased(ObjectId),
158 /// The branch already had everything the change does; it did not move.
159 AlreadyApplied,
160 /// The change conflicts with the head; the branch did not move.
161 Conflicts {
162 /// The changeset that conflicts.
163 change: ObjectId,
164 /// The conflicts.
165 conflicts: Vec<Conflict>,
166 },
167 /// A fast-forward-only landing found the stack not built on the head;
168 /// the branch did not move. Only [`land_stack`](crate::land_stack)
169 /// refuses.
170 Refused,
171}
172
173/// One changeset of a workspace, and the changeset that holds it now.
174#[derive(Clone, Copy, Debug, PartialEq, Eq)]
175pub struct Placed {
176 /// The changeset as the workspace had it.
177 pub from: ObjectId,
178 /// What holds it now: the same changeset after a fast-forward, the
179 /// rebased one after a rebase, or `None` when it did not go anywhere:
180 /// the branch had its changes already, or a conflict stopped it or one
181 /// before it.
182 pub to: Option<ObjectId>,
183}
184
185/// What a landing did.
186#[derive(Clone, Debug, PartialEq, Eq)]
187pub struct LandReport {
188 /// The branch.
189 pub branch: String,
190 /// Its head before the landing.
191 pub head_before: Option<ObjectId>,
192 /// How it ended.
193 pub landed: Landed,
194 /// The op log operation that moved the branch, if it moved.
195 pub operation: Option<u64>,
196 /// Where each changeset of the stack went, oldest first; when the
197 /// branch did not move, none went anywhere.
198 pub placed: Vec<Placed>,
199 /// The paths both sides changed, merged line by line or by kind, over
200 /// the whole stack, sorted.
201 pub merged_paths: Vec<Vec<u8>>,
202 /// The paths of the working copy that the landing then wrote or
203 /// removed, sorted; none for [`land_change`](crate::land_change).
204 pub updated_paths: Vec<Vec<u8>>,
205}
206
207impl LandReport {
208 /// The branch's head after the landing.
209 pub fn head(&self) -> Option<ObjectId> {
210 match &self.landed {
211 Landed::FastForward(id) | Landed::Rebased(id) => Some(*id),
212 _ => self.head_before,
213 }
214 }
215}
216
217/// What `update` did, with the outcome in [`UpdateReport::updated`].
218#[derive(Clone, Debug, PartialEq, Eq)]
219pub struct UpdateReport {
220 /// The branch the workspace updates from.
221 pub branch: String,
222 /// Its head, which an update reads and never moves; `None` when the
223 /// branch does not exist.
224 pub head: Option<ObjectId>,
225 /// How the update ended.
226 pub updated: Updated,
227 /// The workspace's base before the update.
228 pub base_before: Option<ObjectId>,
229 /// Its base after it.
230 pub base: Option<ObjectId>,
231 /// Where each of the workspace's own changesets went, oldest first: the
232 /// rebased changeset on top of the head, or `None` from the one that
233 /// conflicts on.
234 pub placed: Vec<Placed>,
235 /// The paths both sides changed, merged line by line or by kind, over
236 /// the changesets rebased, sorted.
237 pub merged_paths: Vec<Vec<u8>>,
238 /// The paths of the working copy that the update wrote or removed,
239 /// sorted.
240 pub updated_paths: Vec<Vec<u8>>,
241}
242
243/// What a workspace would land, from [`Workspace::stack`].
244#[derive(Clone, Debug, PartialEq, Eq)]
245pub struct Stack {
246 /// The branch it would land on.
247 pub branch: String,
248 /// The branch's head in this repository, if the branch exists.
249 pub head: Option<ObjectId>,
250 /// The workspace's base: the last of `changes`, or where it stands
251 /// when it has none.
252 pub base: Option<ObjectId>,
253 /// The workspace's own changesets that the head does not have, oldest
254 /// first.
255 pub changes: Vec<ObjectId>,
256}
257
258/// What `update` did.
259#[derive(Clone, Debug, PartialEq, Eq)]
260pub enum Updated {
261 /// The workspace was on the head already, or the branch does not exist.
262 UpToDate,
263 /// The workspace moved to the head.
264 Moved {
265 /// The head.
266 head: ObjectId,
267 },
268 /// The workspace's own changesets were rebased onto the head.
269 Rebased {
270 /// The head.
271 head: ObjectId,
272 /// The last rebased changeset, now the workspace's base.
273 tip: ObjectId,
274 },
275 /// A changeset conflicts with the head: the working copy holds the
276 /// head's tree with the change's clean paths and conflict markers, and
277 /// a rebase is in progress.
278 Conflicts {
279 /// The head.
280 head: ObjectId,
281 /// The changeset that conflicts.
282 change: ObjectId,
283 /// Its conflicts.
284 conflicts: Vec<Conflict>,
285 },
286}
287
288/// Why a landing transaction stops without moving the branch.
289enum Abort {
290 Stop,
291 Failed(Error),
292}
293
294impl From<Error> for Abort {
295 fn from(error: Error) -> Self {
296 Abort::Failed(error)
297 }
298}
299
300/// What a landing decided inside its transaction.
301enum Decision {
302 Nothing,
303 AlreadyApplied {
304 head: ObjectId,
305 placed: Vec<Placed>,
306 },
307 Moved {
308 tip: ObjectId,
309 rebased: bool,
310 tip_root: ObjectId,
311 plan: Plan,
312 placed: Vec<Placed>,
313 merged_paths: Vec<Vec<u8>>,
314 },
315 Conflicts {
316 change: ObjectId,
317 conflicts: Vec<Conflict>,
318 stack: Vec<ObjectId>,
319 },
320}
321
322/// How many changesets an op log description names, at most.
323const DESCRIBED: usize = 8;
324
325/// What the op log says a landing did, after `prefix`: how it went, each
326/// changeset and the one it became (short ids), and how many paths were
327/// merged, as in `rebased c57e1007e4f3 -> 3afaed346293 (1 path merged)`.
328pub(crate) fn describe_landing(
329 prefix: &str,
330 outcome: &str,
331 placed: &[Placed],
332 merged_paths: usize,
333) -> String {
334 let mut moves: Vec<String> = placed
335 .iter()
336 .take(DESCRIBED)
337 .map(|placed| match placed.to {
338 Some(to) => format!("{} -> {}", placed.from.short(), to.short()),
339 None => format!("{} already applied", placed.from.short()),
340 })
341 .collect();
342 if placed.len() > DESCRIBED {
343 moves.push(format!("and {} more", placed.len() - DESCRIBED));
344 }
345 let moves = match placed.len() {
346 1 => moves.concat(),
347 n => format!("{n} changesets: {}", moves.join(", ")),
348 };
349 let merged = match merged_paths {
350 1 => "1 path".to_owned(),
351 n => format!("{n} paths"),
352 };
353 format!("{prefix}: {outcome} {moves} ({merged} merged)")
354}
355
356/// The file every workspace holds so that git refuses to work in it.
357pub const GIT_GUARD: &str = ".git";
358
359/// What it says. Git reads the line as the path of a repository, finds
360/// none, and stops with "not a git repository: " and that path, so the text
361/// is written to read well there.
362pub const GIT_GUARD_TEXT: &str =
363 "gitdir: this is a braid workspace, not a git checkout: use braid here\n";
364
365impl<'r> Workspace<'r> {
366 /// The directory that holds every workspace's state.
367 pub fn states_dir(repo: &Repo) -> PathBuf {
368 repo.root().join(DIR).join(WORKSPACES_DIR)
369 }
370
371 /// Where the workspace named `name` goes unless told otherwise:
372 /// `.braid/work/<name>` in the repository's root.
373 pub fn default_dir(repo: &Repo, name: &str) -> PathBuf {
374 repo.root().join(DIR).join(WORK_DIR).join(name)
375 }
376
377 /// Creates a workspace named `name` in `dir`, which must not exist or be
378 /// empty, at the changeset `at` (`None` for the empty tree), tracking
379 /// `branch`. Writes the `.braid` file that names the workspace, the
380 /// [`GIT_GUARD`] file, and the whole tree. Returns the workspace and how
381 /// many files of the tree it wrote. On failure, nothing is left behind.
382 pub fn create(
383 repo: &'r Repo,
384 name: &str,
385 dir: &Path,
386 at: Option<ObjectId>,
387 branch: &str,
388 ) -> Result<(Workspace<'r>, usize), Error> {
389 if !WorkspaceLink::is_valid_name(name) {
390 return Err(Error::InvalidName(name.to_owned()));
391 }
392 let states = Self::states_dir(repo);
393 fs::create_dir_all(&states).map_err(Error::io("create", &states))?;
394 let state_dir = states.join(name);
395 match fs::create_dir(&state_dir) {
396 Ok(()) => {}
397 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {
398 return Err(Error::WorkspaceExists(name.to_owned()));
399 }
400 Err(err) => return Err(Error::io("create", &state_dir)(err)),
401 }
402 let mut prepared = None;
403 let made = Self::populate(repo, name, dir, &state_dir, at, branch, &mut prepared);
404 if made.is_err() {
405 match prepared {
406 Some(Prepared::Created) => {
407 let _ = fs::remove_dir_all(dir);
408 }
409 // It was empty: everything in it now is this workspace's.
410 Some(Prepared::WasEmpty) => clear(dir),
411 None => {}
412 }
413 let _ = fs::remove_dir_all(&state_dir);
414 }
415 made
416 }
417
418 fn populate(
419 repo: &'r Repo,
420 name: &str,
421 dir: &Path,
422 state_dir: &Path,
423 at: Option<ObjectId>,
424 branch: &str,
425 prepared: &mut Option<Prepared>,
426 ) -> Result<(Workspace<'r>, usize), Error> {
427 let _lock = Lock::acquire(state_dir)?;
428 match fs::read_dir(dir) {
429 Ok(mut entries) => {
430 if entries.next().is_some() {
431 return Err(Error::DirectoryNotEmpty(dir.to_path_buf()));
432 }
433 *prepared = Some(Prepared::WasEmpty);
434 }
435 Err(err) if err.kind() == io::ErrorKind::NotFound => {
436 fs::create_dir_all(dir).map_err(Error::io("create", dir))?;
437 *prepared = Some(Prepared::Created);
438 }
439 Err(err) => return Err(Error::io("read", dir)(err)),
440 }
441 let dir = fs::canonicalize(dir).map_err(Error::io("open", dir))?;
442 let repository = fs::canonicalize(repo.root()).map_err(Error::io("open", repo.root()))?;
443 let link = WorkspaceLink {
444 repository,
445 name: name.to_owned(),
446 };
447 let link_path = dir.join(DIR);
448 fs::File::create_new(&link_path)
449 .and_then(|mut file| io::Write::write_all(&mut file, &link.encode()))
450 .map_err(Error::io("write", &link_path))?;
451 // Without it, git run in the workspace finds the repository of a
452 // checkout around it, often the shared one the workspace sits in,
453 // and stashes, resets or commits there. The walk skips `.git`.
454 let guard = dir.join(GIT_GUARD);
455 fs::File::create_new(&guard)
456 .and_then(|mut file| io::Write::write_all(&mut file, GIT_GUARD_TEXT.as_bytes()))
457 .map_err(Error::io("write", &guard))?;
458
459 let workspace = Workspace {
460 repo,
461 name: name.to_owned(),
462 dir: dir.clone(),
463 state_dir: state_dir.to_path_buf(),
464 };
465 let root = Root::open(&dir)?;
466 let fs = FileSystem::probe(root.dir());
467 let store = repo.store();
468 let to = root_of(store, at)?;
469 let plan = checkout::plan(store, &root, fs, EMPTY_TREE, to, Mode::Checked)?;
470 let mut state = State {
471 path: dir,
472 branch: branch.to_owned(),
473 base: at,
474 upstream: at,
475 fs,
476 checkout: None,
477 tracked: Vec::new(),
478 rebase: None,
479 };
480 let written = workspace.write(&root, &mut state, &plan, EMPTY_TREE, to)?;
481 Ok((workspace, written.len()))
482 }
483
484 /// Opens the workspace named `name`, at the directory its state
485 /// records.
486 pub fn open(repo: &'r Repo, name: &str) -> Result<Workspace<'r>, Error> {
487 if !WorkspaceLink::is_valid_name(name) {
488 return Err(Error::InvalidName(name.to_owned()));
489 }
490 let state_dir = Self::states_dir(repo).join(name);
491 if !state_dir.join(crate::state::FILE).is_file() {
492 return Err(Error::NoSuchWorkspace(name.to_owned()));
493 }
494 let state = State::load(&state_dir)?;
495 Ok(Workspace {
496 repo,
497 name: name.to_owned(),
498 dir: state.path,
499 state_dir,
500 })
501 }
502
503 /// Opens the workspace named `name` at `dir`, where its `.braid` file
504 /// was found. If the directory moved, the state follows it the next
505 /// time the workspace changes.
506 pub fn at(repo: &'r Repo, name: &str, dir: &Path) -> Result<Workspace<'r>, Error> {
507 let mut workspace = Self::open(repo, name)?;
508 workspace.dir = dir.to_path_buf();
509 Ok(workspace)
510 }
511
512 /// Every workspace of `repo`, by name, with its state.
513 pub fn list(repo: &Repo) -> Result<Vec<(String, State)>, Error> {
514 let states = Self::states_dir(repo);
515 let entries = match fs::read_dir(&states) {
516 Ok(entries) => entries,
517 Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
518 Err(err) => return Err(Error::io("read", &states)(err)),
519 };
520 let mut found = Vec::new();
521 for entry in entries {
522 let entry = entry.map_err(Error::io("read", &states))?;
523 let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
524 continue;
525 };
526 if !WorkspaceLink::is_valid_name(&name)
527 || !entry.path().join(crate::state::FILE).is_file()
528 {
529 continue;
530 }
531 found.push((name, State::load(&entry.path())?));
532 }
533 found.sort_by(|a, b| a.0.cmp(&b.0));
534 Ok(found)
535 }
536
537 /// Removes the workspace named `name`: its directory and its state.
538 /// Refused while it has uncommitted changes ([`Error::Uncommitted`]),
539 /// new files the secrets guard holds back ([`Error::HeldBack`]),
540 /// changesets the branch does not have, or a rebase in progress, unless
541 /// `force`. The directory is removed only if its `.braid` file still
542 /// names this workspace of this repository.
543 pub fn remove(repo: &Repo, name: &str, force: bool) -> Result<(), Error> {
544 let workspace = Workspace::open(repo, name)?;
545 let lock = Lock::acquire(&workspace.state_dir)?;
546 let state = State::load(&workspace.state_dir)?;
547 let owned = workspace.owns_directory(&state.path);
548 if !force {
549 if state.rebase.is_some() {
550 return Err(Error::RebaseInProgress);
551 }
552 if owned {
553 let root = Root::open(&state.path)?;
554 let status = workspace.scan_status(&root, &state)?;
555 if let Some(first) = status.changes.first() {
556 return Err(Error::Uncommitted {
557 count: status.changes.len(),
558 first: first.path.clone(),
559 });
560 }
561 // Files the guard holds back are not changes to commit:
562 // any of them may be a secret.
563 if let Some(first) = status.needs_track.first() {
564 return Err(Error::HeldBack {
565 count: status.needs_track.len(),
566 first: first.clone(),
567 });
568 }
569 }
570 let store = repo.store();
571 let head = store.refs()?.get(&state.branch);
572 let unlanded = find_stack(store, head, state.base, state.upstream)?;
573 if !unlanded.is_empty() {
574 return Err(Error::Unlanded {
575 count: unlanded.len(),
576 branch: state.branch.clone(),
577 });
578 }
579 }
580 if owned {
581 fs::remove_dir_all(&state.path).map_err(Error::io("remove", &state.path))?;
582 }
583 drop(lock);
584 fs::remove_dir_all(&workspace.state_dir).map_err(Error::io("remove", &workspace.state_dir))
585 }
586
587 /// Whether `dir` holds a `.braid` file naming this workspace.
588 fn owns_directory(&self, dir: &Path) -> bool {
589 let Ok(link) = WorkspaceLink::read(&dir.join(DIR)) else {
590 return false;
591 };
592 let same_repo = match (
593 fs::canonicalize(&link.repository),
594 fs::canonicalize(self.repo.root()),
595 ) {
596 (Ok(a), Ok(b)) => a == b,
597 _ => false,
598 };
599 link.name == self.name && same_repo
600 }
601
602 /// The workspace's name.
603 pub fn name(&self) -> &str {
604 &self.name
605 }
606
607 /// The workspace directory.
608 pub fn dir(&self) -> &Path {
609 &self.dir
610 }
611
612 /// The repository.
613 pub fn repo(&self) -> &'r Repo {
614 self.repo
615 }
616
617 /// The workspace's state as last saved, read without the lock.
618 pub fn state(&self) -> Result<State, Error> {
619 State::load(&self.state_dir)
620 }
621
622 /// Takes the lock, reads the state, opens the working copy, and
623 /// finishes a checkout that an earlier command left unfinished.
624 fn begin(&self) -> Result<(Lock, State, Root), Error> {
625 let lock = Lock::acquire(&self.state_dir)?;
626 let mut state = State::load(&self.state_dir)?;
627 let root = Root::open(&self.dir)?;
628 if state.path != self.dir {
629 state.path = self.dir.clone();
630 state.save(&self.state_dir)?;
631 }
632 if let Some(Checkout { from, to }) = state.checkout {
633 let plan = checkout::plan(self.store(), &root, state.fs, from, to, Mode::Forced)?;
634 checkout::apply(self.store(), &root, &plan)?;
635 state.checkout = None;
636 state.save(&self.state_dir)?;
637 }
638 Ok((lock, state, root))
639 }
640
641 fn store(&self) -> &'r Store {
642 self.repo.store()
643 }
644
645 /// Writes a planned checkout from tree `from` to tree `to` and saves
646 /// `state`. The state is saved first with the checkout marked as
647 /// unfinished, so that a command interrupted half way through is
648 /// finished by the next one. Returns the paths written or removed.
649 fn write(
650 &self,
651 root: &Root,
652 state: &mut State,
653 plan: &Plan,
654 from: ObjectId,
655 to: ObjectId,
656 ) -> Result<Vec<Vec<u8>>, Error> {
657 if plan.len() == 0 {
658 state.save(&self.state_dir)?;
659 return Ok(Vec::new());
660 }
661 state.checkout = Some(Checkout { from, to });
662 state.save(&self.state_dir)?;
663 checkout::apply(self.store(), root, plan)?;
664 state.checkout = None;
665 state.save(&self.state_dir)?;
666 Ok(plan.paths())
667 }
668
669 /// Scans the working copy, or only what lies at or below the paths of
670 /// `scope`, and returns where it differs from the base. A scan of the
671 /// whole working copy saves the stat cache, if it changed.
672 fn scan(&self, root: &Root, state: &State, scope: &[Vec<u8>]) -> Result<Vec<Delta>, Error> {
673 let store = self.store();
674 let base = root_of(store, state.base)?;
675 let cache = Cache::load(&self.state_dir);
676 let Scan {
677 deltas,
678 cache: next,
679 ..
680 } = scan::scan(root, store, base, &cache, state.fs, scope)?;
681 if let Some(next) = next.filter(|next| next.changed) {
682 cache::save(&self.state_dir, next.time, &next.records)?;
683 }
684 Ok(deltas)
685 }
686
687 /// Scans the whole working copy and compares it with the base.
688 fn scan_status(&self, root: &Root, state: &State) -> Result<Status, Error> {
689 let deltas = self.scan(root, state, &[])?;
690 Ok(status::compare(&deltas, &state.tracked))
691 }
692
693 /// Fails if the working copy has uncommitted changes.
694 fn require_clean(&self, root: &Root, state: &State) -> Result<(), Error> {
695 let status = self.scan_status(root, state)?;
696 match status.changes.first() {
697 Some(first) => Err(Error::Uncommitted {
698 count: status.changes.len(),
699 first: first.path.clone(),
700 }),
701 None => Ok(()),
702 }
703 }
704
705 /// How the working copy differs from the base, and where the workspace
706 /// stands against its branch.
707 pub fn status(&self) -> Result<StatusReport, Error> {
708 let (_lock, state, root) = self.begin()?;
709 let status = self.scan_status(&root, &state)?;
710 let store = self.store();
711 let head = store.refs()?.get(&state.branch);
712 let mut unlanded = find_stack(store, head, state.base, state.upstream)?;
713 // The changeset the workspace's own start from.
714 let fork = match unlanded.first() {
715 Some(&oldest) => read_changeset(store, oldest)?.parents.first().copied(),
716 None => state.base,
717 };
718 let behind_by = distance(store, head, fork, BEHIND_LIMIT)?;
719 if let Some(rebase) = &state.rebase {
720 unlanded.push(rebase.change);
721 unlanded.extend(&rebase.pending);
722 }
723 let conflicts = conflict_states(&root, state.rebase.as_ref())?;
724 let blocking = blockers(&conflicts, &status.needs_track, |_| true);
725 Ok(StatusReport {
726 state,
727 status,
728 head,
729 unlanded,
730 behind_by,
731 conflicts,
732 blocking,
733 })
734 }
735
736 /// Records the working copy as a changeset on the base, and makes it
737 /// the new base. There is no staging area: every change counts, or
738 /// every change at or below `paths`.
739 ///
740 /// It is refused with [`Error::Blocked`], which lists every reason as
741 /// [`StatusReport::blocking`] does, while new files at or below `paths`
742 /// wait for `braid track`, and, during a rebase, while conflict markers
743 /// remain in files with content conflicts or other conflicts are not
744 /// marked resolved. With `force` it goes ahead, and the files waiting
745 /// for `braid track` stay out.
746 ///
747 /// While a rebase is in progress the changeset is the resolution: it
748 /// takes no paths, keeps the rebased changeset's author, extra fields
749 /// and message unless one is given, and once it is made, the
750 /// changesets that were waiting are rebased onto it.
751 pub fn commit(&self, request: &CommitRequest) -> Result<CommitOutcome, Error> {
752 let (_lock, mut state, root) = self.begin()?;
753 if state.rebase.is_some() && !request.paths.is_empty() {
754 return Err(Error::PathsDuringRebase);
755 }
756 let store = self.store();
757 let base = root_of(store, state.base)?;
758 let cache = Cache::load(&self.state_dir);
759 // With paths, only what lies at or below them is read.
760 let Scan {
761 deltas,
762 cache: next,
763 ..
764 } = scan::scan(&root, store, base, &cache, state.fs, &request.paths)?;
765 let committed = self.commit_scanned(&root, &mut state, request, &deltas);
766 // The scan's records serve the next scan. When the commit moved the
767 // base and nothing else, they are brought onto it first, so that
768 // the next scan finds the committed directories as this one left
769 // them. The cache is only a cache: failing to write it fails
770 // nothing.
771 if let Some(next) = next {
772 let records = match &committed {
773 Ok((outcome, paths)) if outcome.rebase == RebaseProgress::None => {
774 outcome.changeset.and_then(|id| {
775 let root = root_of(store, Some(id)).ok()?;
776 scan::follow(store, next.records, root, paths).ok()
777 })
778 }
779 _ => next.changed.then_some(next.records),
780 };
781 if let Some(records) = records {
782 let _ = cache::save(&self.state_dir, next.time, &records);
783 }
784 }
785 committed.map(|(outcome, _)| outcome)
786 }
787
788 /// The rest of [`Self::commit`], once the working copy is scanned and
789 /// found to differ from the base by `deltas`. Also returns the paths
790 /// the changeset changed.
791 fn commit_scanned(
792 &self,
793 root: &Root,
794 state: &mut State,
795 request: &CommitRequest,
796 deltas: &[Delta],
797 ) -> Result<(CommitOutcome, Vec<Vec<u8>>), Error> {
798 let store = self.store();
799 let status = status::compare(deltas, &state.tracked);
800 let in_scope = |path: &[u8]| {
801 request.paths.is_empty() || request.paths.iter().any(|p| is_within(path, p))
802 };
803 if !request.force {
804 let conflicts = conflict_states(root, state.rebase.as_ref())?;
805 let blocking = blockers(&conflicts, &status.needs_track, in_scope);
806 if !blocking.is_empty() {
807 return Err(Error::Blocked(blocking));
808 }
809 }
810 let original = match &state.rebase {
811 Some(rebase) => Some(read_changeset(store, rebase.change)?),
812 None => None,
813 };
814 let selected: Vec<&status::PathChange> = status
815 .changes
816 .iter()
817 .filter(|change| in_scope(&change.path))
818 .collect();
819
820 if selected.is_empty() {
821 let Some(rebase) = state.rebase.take() else {
822 return Err(Error::NothingToCommit);
823 };
824 // The resolution is the tree the rebase went onto: nothing of
825 // this changeset is left to record.
826 let progress = self.continue_rebase(
827 root,
828 state,
829 rebase.pending,
830 rebase.onto,
831 &request.committer.now(),
832 )?;
833 state.save(&self.state_dir)?;
834 let outcome = CommitOutcome {
835 changeset: None,
836 changes: 0,
837 message_replaced: false,
838 rebase: progress,
839 };
840 return Ok((outcome, Vec::new()));
841 }
842
843 let message = match (&request.message, &original) {
844 (Some(message), _) => message.clone(),
845 (None, Some(original)) => original.message.clone(),
846 (None, None) => return Err(Error::NoMessage),
847 };
848 let message_replaced = request.message.is_some() && original.is_some();
849 let olds: HashMap<&[u8], &ChangeOp> = deltas
850 .iter()
851 .filter_map(|delta| Some((delta.path.as_slice(), delta.old.as_ref()?)))
852 .collect();
853 let mut changes = Vec::with_capacity(selected.len());
854 for change in &selected {
855 let op = match &change.op {
856 ChangeOp::Delete | ChangeOp::Gitlink { .. } => change.op.clone(),
857 _ => {
858 // The base's file at the same path: what the store may
859 // keep the new content as a delta against.
860 let similar = match olds.get(change.path.as_slice()) {
861 Some(
862 ChangeOp::File { blob, .. }
863 | ChangeOp::Executable { blob, .. }
864 | ChangeOp::Symlink { blob, .. },
865 ) => Some(*blob),
866 _ => None,
867 };
868 self.store_file(root, &change.path, similar)?
869 }
870 };
871 changes.push(Change {
872 path: change.path.clone(),
873 op,
874 });
875 }
876 let committer = request.committer.now();
877 let author = match (&request.author, &original) {
878 (Some(author), _) => author.now(),
879 (None, Some(original)) => original.author.clone(),
880 (None, None) => committer.clone(),
881 };
882 let extras = match (&state.rebase, &original) {
883 (Some(rebase), Some(original)) => {
884 rebased_extras(&original.extras, rebase.change, &request.agent)
885 }
886 _ => agent_extras(&request.agent),
887 };
888 let parents: Vec<ObjectId> = state.base.into_iter().collect();
889 let count = changes.len();
890 let id = braid_engine::commit(
891 store,
892 parents,
893 changes,
894 author,
895 committer.clone(),
896 message,
897 extras,
898 )?;
899 store.sync()?;
900
901 // Marks for files that are now in the base have done their job.
902 let committed: HashSet<&[u8]> = selected
903 .iter()
904 .map(|change| change.path.as_slice())
905 .collect();
906 state
907 .tracked
908 .retain(|mark| !committed.contains(mark.as_slice()));
909 state.base = Some(id);
910 let progress = match state.rebase.take() {
911 None => RebaseProgress::None,
912 Some(rebase) => self.continue_rebase(root, state, rebase.pending, id, &committer)?,
913 };
914 state.save(&self.state_dir)?;
915 let paths = selected.iter().map(|change| change.path.clone()).collect();
916 let outcome = CommitOutcome {
917 changeset: Some(id),
918 changes: count,
919 message_replaced,
920 rebase: progress,
921 };
922 Ok((outcome, paths))
923 }
924
925 /// Reads a changed file again and stores it as a blob: the content
926 /// committed is the content read now. `similar` is the blob the base
927 /// has at the same path, a hint for the store. A large file is streamed
928 /// into the store in chunks, never held in memory whole.
929 fn store_file(
930 &self,
931 root: &Root,
932 path: &[u8],
933 similar: Option<ObjectId>,
934 ) -> Result<ChangeOp, Error> {
935 let (parent, name) = split_last(path);
936 let gone = || Error::Io {
937 action: "read",
938 path: root.path().join(crate::paths::show(path).as_ref()),
939 source: io::Error::new(
940 io::ErrorKind::NotFound,
941 "the file changed while it was committed; try again",
942 ),
943 };
944 let Found::Here(dir) = root.open_dir(parent)? else {
945 return Err(gone());
946 };
947 let os = os_name(name).ok_or_else(gone)?;
948 let meta = dir.symlink_metadata(os).map_err(|_| gone())?;
949 let stat = Stat::of(&meta);
950 let store = self.store();
951 match stat.kind {
952 StatKind::Symlink => {
953 let target = read_link(&dir, os).map_err(|err| root.error("read", path, err))?;
954 let blob = store.put(Kind::Blob, &target)?;
955 Ok(ChangeOp::Symlink {
956 blob,
957 size: target.len() as u64,
958 })
959 }
960 StatKind::File => {
961 let mut file = open_file(&dir, os).map_err(|err| root.error("read", path, err))?;
962 let executable = Stat::of(
963 &file
964 .metadata()
965 .map_err(|err| root.error("read", path, err))?,
966 )
967 .executable;
968 let (blob, size) = if meta.len() >= braid_store::CHUNKED_MIN {
969 store
970 .put_blob_from(&mut file, Some(meta.len()))
971 .map_err(|err| match err {
972 braid_store::Error::Stream { source, .. } => {
973 root.error("read", path, source)
974 }
975 other => other.into(),
976 })?
977 } else {
978 let mut content = Vec::new();
979 file.read_to_end(&mut content)
980 .map_err(|err| root.error("read", path, err))?;
981 let blob = match &similar {
982 Some(similar) => store.put_similar(Kind::Blob, &content, similar)?,
983 None => store.put(Kind::Blob, &content)?,
984 };
985 (blob, content.len() as u64)
986 };
987 Ok(if executable {
988 ChangeOp::Executable { blob, size }
989 } else {
990 ChangeOp::File { blob, size }
991 })
992 }
993 StatKind::Dir | StatKind::Other => Err(gone()),
994 }
995 }
996
997 /// Rebases the changesets that waited behind a resolved conflict onto
998 /// `tip`, the resolution, and brings the working copy along.
999 fn continue_rebase(
1000 &self,
1001 root: &Root,
1002 state: &mut State,
1003 pending: Vec<ObjectId>,
1004 tip: ObjectId,
1005 committer: &Signature,
1006 ) -> Result<RebaseProgress, Error> {
1007 state.base = Some(tip);
1008 if pending.is_empty() {
1009 return Ok(RebaseProgress::Finished { tip });
1010 }
1011 let store = self.store();
1012 let from = root_of(store, Some(tip))?;
1013 match replay(
1014 store,
1015 &state.branch,
1016 Some(tip),
1017 &pending,
1018 committer,
1019 First::Pick,
1020 )? {
1021 Replayed::Done { tip: last, .. } => {
1022 let to = root_of(store, Some(last))?;
1023 let plan = checkout::plan(store, root, state.fs, from, to, Mode::Checked)?;
1024 state.base = Some(last);
1025 self.write(root, state, &plan, from, to)?;
1026 Ok(RebaseProgress::Finished { tip: last })
1027 }
1028 Replayed::Stopped {
1029 index,
1030 onto,
1031 conflicts,
1032 ..
1033 } => {
1034 let change = pending[index];
1035 self.stop_on_conflicts(
1036 root,
1037 state,
1038 from,
1039 onto,
1040 change,
1041 &pending[index + 1..],
1042 &conflicts,
1043 )?;
1044 Ok(RebaseProgress::Stopped { change, conflicts })
1045 }
1046 }
1047 }
1048
1049 /// Writes the working copy for a rebase stopped by conflicts and
1050 /// records the rebase: `onto`'s tree, with `change`'s clean paths and
1051 /// conflict markers, as the base `onto`. Returns the paths written or
1052 /// removed.
1053 #[allow(clippy::too_many_arguments)]
1054 fn stop_on_conflicts(
1055 &self,
1056 root: &Root,
1057 state: &mut State,
1058 from: ObjectId,
1059 onto: ObjectId,
1060 change: ObjectId,
1061 pending: &[ObjectId],
1062 conflicts: &[Conflict],
1063 ) -> Result<Vec<Vec<u8>>, Error> {
1064 let store = self.store();
1065 let changeset = read_changeset(store, change)?;
1066 let subject = subject(&changeset.message);
1067 let ours = format!("{} ({})", state.branch, onto.short());
1068 let theirs = format!("{} ({subject})", change.short());
1069 let (tree, recorded) = conflict_tree(store, onto, change, conflicts, (&ours, &theirs))?;
1070 let plan = checkout::plan(store, root, state.fs, from, tree, Mode::Checked)?;
1071 // The files the change sets were committed once already, those the
1072 // secrets guard holds back too, after `braid track`: they stay
1073 // tracked through the resolution, rather than waiting to be
1074 // tracked again or dropped from it.
1075 for item in read_changes(store, change, &changeset)?.iter() {
1076 let size = match &item.op {
1077 ChangeOp::File { size, .. }
1078 | ChangeOp::Executable { size, .. }
1079 | ChangeOp::Symlink { size, .. } => *size,
1080 ChangeOp::Gitlink { .. } | ChangeOp::Delete => continue,
1081 };
1082 if status::is_guarded(&item.path, size) && !state.tracked.contains(&item.path) {
1083 state.tracked.push(item.path.clone());
1084 }
1085 }
1086 state.tracked.sort();
1087 state.base = Some(onto);
1088 state.rebase = Some(Rebase {
1089 change,
1090 onto,
1091 pending: pending.to_vec(),
1092 conflicts: recorded,
1093 });
1094 self.write(root, state, &plan, from, tree)
1095 }
1096
1097 /// Lands the workspace's own changesets on `onto` (by default the
1098 /// branch it tracks), in one op log transaction: the head is read, the
1099 /// changesets are landed on it with the engine (fast-forward or
1100 /// rebase), and the branch moves with a compare-and-swap. The operation
1101 /// says how it went, which changeset became which, and how many paths
1102 /// were merged (see [`LandReport`]). With conflicts the branch does not
1103 /// move and nothing in the workspace changes. Once the branch has
1104 /// moved, the working copy is brought from the base's tree to the
1105 /// landed tree, writing only the difference, and the landed changeset
1106 /// becomes the base. Refused with uncommitted changes or a rebase in
1107 /// progress.
1108 pub fn land(
1109 &self,
1110 onto: Option<&str>,
1111 agent: &str,
1112 committer: &Identity,
1113 ) -> Result<LandReport, Error> {
1114 let (_lock, mut state, root) = self.begin()?;
1115 if state.rebase.is_some() {
1116 return Err(Error::RebaseInProgress);
1117 }
1118 self.require_clean(&root, &state)?;
1119 let branch = onto.unwrap_or(&state.branch).to_owned();
1120 let store = self.store();
1121 let base_root = root_of(store, state.base)?;
1122 let signature = committer.now();
1123 let mut head_before = None;
1124 let mut decision = None;
1125 let prefix = format!("land workspace {} on {branch}", self.name);
1126 let result = store.transact_with(agent, |refs| -> Result<_, Abort> {
1127 let head = refs.get(&branch);
1128 head_before = head;
1129 let stack = find_stack(store, head, state.base, state.upstream)?;
1130 if stack.is_empty() {
1131 decision = Some(Decision::Nothing);
1132 return Err(Abort::Stop);
1133 }
1134 match replay(
1135 store,
1136 &branch,
1137 head,
1138 &stack,
1139 &signature,
1140 First::MustBeOnBranch,
1141 )? {
1142 Replayed::Done { tip, placed, .. } if Some(tip) == head => {
1143 decision = Some(Decision::AlreadyApplied { head: tip, placed });
1144 Err(Abort::Stop)
1145 }
1146 Replayed::Done {
1147 tip,
1148 rebased,
1149 placed,
1150 merged_paths,
1151 } => {
1152 // Check the working copy can follow before the branch
1153 // moves.
1154 let tip_root = root_of(store, Some(tip))?;
1155 let plan =
1156 checkout::plan(store, &root, state.fs, base_root, tip_root, Mode::Checked)?;
1157 let outcome = if rebased { "rebased" } else { "fast-forward" };
1158 let description =
1159 describe_landing(&prefix, outcome, &placed, merged_paths.len());
1160 decision = Some(Decision::Moved {
1161 tip,
1162 rebased,
1163 tip_root,
1164 plan,
1165 placed,
1166 merged_paths,
1167 });
1168 let updates = vec![RefUpdate::new(branch.clone(), head, Some(tip))];
1169 Ok((updates, description))
1170 }
1171 Replayed::Stopped {
1172 index, conflicts, ..
1173 } => {
1174 decision = Some(Decision::Conflicts {
1175 change: stack[index],
1176 conflicts,
1177 stack,
1178 });
1179 Err(Abort::Stop)
1180 }
1181 }
1182 });
1183 let operation = match result {
1184 Ok(op) => Some(op.seq),
1185 Err(TransactError::Aborted(Abort::Stop)) => None,
1186 Err(TransactError::Aborted(Abort::Failed(err))) => return Err(err),
1187 Err(TransactError::Store(err)) => return Err(err.into()),
1188 };
1189 let mut report = LandReport {
1190 branch,
1191 head_before,
1192 landed: Landed::Nothing,
1193 operation,
1194 placed: Vec::new(),
1195 merged_paths: Vec::new(),
1196 updated_paths: Vec::new(),
1197 };
1198 match decision {
1199 Some(Decision::Moved {
1200 tip,
1201 rebased,
1202 tip_root,
1203 plan,
1204 placed,
1205 merged_paths,
1206 }) => {
1207 state.base = Some(tip);
1208 state.upstream = Some(tip);
1209 report.updated_paths = self.write(&root, &mut state, &plan, base_root, tip_root)?;
1210 report.landed = if rebased {
1211 Landed::Rebased(tip)
1212 } else {
1213 Landed::FastForward(tip)
1214 };
1215 report.placed = placed;
1216 report.merged_paths = merged_paths;
1217 }
1218 Some(Decision::AlreadyApplied { head, placed }) => {
1219 // The branch has it all: the workspace moves to the head.
1220 report.updated_paths = self.move_to(&root, &mut state, base_root, head)?;
1221 report.landed = Landed::AlreadyApplied;
1222 report.placed = placed;
1223 }
1224 Some(Decision::Conflicts {
1225 change,
1226 conflicts,
1227 stack,
1228 }) => {
1229 report.landed = Landed::Conflicts { change, conflicts };
1230 report.placed = unplaced(&stack);
1231 }
1232 Some(Decision::Nothing) | None => {}
1233 }
1234 Ok(report)
1235 }
1236
1237 /// Brings the working copy from tree `from` to `head`'s tree and makes
1238 /// `head` the base and the upstream. Returns the paths written or
1239 /// removed.
1240 fn move_to(
1241 &self,
1242 root: &Root,
1243 state: &mut State,
1244 from: ObjectId,
1245 head: ObjectId,
1246 ) -> Result<Vec<Vec<u8>>, Error> {
1247 let store = self.store();
1248 let to = root_of(store, Some(head))?;
1249 let plan = checkout::plan(store, root, state.fs, from, to, Mode::Checked)?;
1250 state.base = Some(head);
1251 state.upstream = Some(head);
1252 self.write(root, state, &plan, from, to)
1253 }
1254
1255 /// What [`Workspace::land`] would land on `onto` (the workspace's
1256 /// branch by default), without landing it: the workspace's own
1257 /// changesets that the branch's head does not have. Refused, as a
1258 /// landing is, with uncommitted changes or a rebase in progress. A
1259 /// repository linked to a hub lands these there, then calls
1260 /// [`Workspace::adopt`].
1261 pub fn stack(&self, onto: Option<&str>) -> Result<Stack, Error> {
1262 let (_lock, state, root) = self.begin()?;
1263 if state.rebase.is_some() {
1264 return Err(Error::RebaseInProgress);
1265 }
1266 self.require_clean(&root, &state)?;
1267 let branch = onto.unwrap_or(&state.branch).to_owned();
1268 let store = self.store();
1269 let head = store.refs()?.get(&branch);
1270 let changes = find_stack(store, head, state.base, state.upstream)?;
1271 Ok(Stack {
1272 branch,
1273 head,
1274 base: state.base,
1275 changes,
1276 })
1277 }
1278
1279 /// Moves the workspace onto `head` once its changesets have landed
1280 /// somewhere else, such as on a hub, and `head` holds them: the working
1281 /// copy goes from the base's tree to `head`'s, writing only the
1282 /// difference, and `head` becomes the base and the upstream, as after a
1283 /// local landing. `base` is the base [`Workspace::stack`] reported:
1284 /// when the workspace has moved since, nothing changes and the answer
1285 /// is [`Error::BaseMoved`]. Refused with a rebase in progress, and with
1286 /// uncommitted changes unless the workspace is at `head` already (a
1287 /// fast-forward), where no file is written. Returns the paths written
1288 /// or removed.
1289 pub fn adopt(&self, base: Option<ObjectId>, head: ObjectId) -> Result<Vec<Vec<u8>>, Error> {
1290 let (_lock, mut state, root) = self.begin()?;
1291 if state.rebase.is_some() {
1292 return Err(Error::RebaseInProgress);
1293 }
1294 if state.base != base {
1295 return Err(Error::BaseMoved {
1296 expected: base,
1297 found: state.base,
1298 });
1299 }
1300 if state.base == Some(head) {
1301 if state.upstream != Some(head) {
1302 state.upstream = Some(head);
1303 state.save(&self.state_dir)?;
1304 }
1305 return Ok(Vec::new());
1306 }
1307 self.require_clean(&root, &state)?;
1308 let base_root = root_of(self.store(), state.base)?;
1309 self.move_to(&root, &mut state, base_root, head)
1310 }
1311
1312 /// Brings the workspace onto the current head of its branch. Without
1313 /// changesets of its own, it moves to the head. With some, they are
1314 /// rebased onto the head with the engine, without moving the branch;
1315 /// cleanly, the workspace moves onto the rebased changesets. With
1316 /// conflicts, the working copy becomes the head's tree with the
1317 /// change's clean paths and, for content conflicts, files with conflict
1318 /// markers; other conflicts keep the head's version and are reported. A
1319 /// rebase is then in progress until `braid commit`. Refused with
1320 /// uncommitted changes or a rebase in progress.
1321 pub fn update(&self, committer: &Identity) -> Result<UpdateReport, Error> {
1322 let (_lock, mut state, root) = self.begin()?;
1323 if state.rebase.is_some() {
1324 return Err(Error::RebaseInProgress);
1325 }
1326 self.require_clean(&root, &state)?;
1327 let store = self.store();
1328 let mut report = UpdateReport {
1329 branch: state.branch.clone(),
1330 head: None,
1331 updated: Updated::UpToDate,
1332 base_before: state.base,
1333 base: state.base,
1334 placed: Vec::new(),
1335 merged_paths: Vec::new(),
1336 updated_paths: Vec::new(),
1337 };
1338 let Some(head) = store.refs()?.get(&state.branch) else {
1339 return Ok(report);
1340 };
1341 report.head = Some(head);
1342 let base_root = root_of(store, state.base)?;
1343 let stack = find_stack(store, Some(head), state.base, state.upstream)?;
1344 if stack.is_empty() {
1345 if state.base == Some(head) {
1346 if state.upstream != Some(head) {
1347 state.upstream = Some(head);
1348 state.save(&self.state_dir)?;
1349 }
1350 return Ok(report);
1351 }
1352 report.updated_paths = self.move_to(&root, &mut state, base_root, head)?;
1353 report.updated = Updated::Moved { head };
1354 report.base = state.base;
1355 return Ok(report);
1356 }
1357 let signature = committer.now();
1358 match replay(
1359 store,
1360 &state.branch,
1361 Some(head),
1362 &stack,
1363 &signature,
1364 First::Anywhere,
1365 )? {
1366 Replayed::Done { tip, placed, .. } if tip == head => {
1367 report.updated_paths = self.move_to(&root, &mut state, base_root, head)?;
1368 report.updated = Updated::Moved { head };
1369 report.placed = placed;
1370 }
1371 Replayed::Done {
1372 tip,
1373 placed,
1374 merged_paths,
1375 ..
1376 } => {
1377 let to = root_of(store, Some(tip))?;
1378 let plan = checkout::plan(store, &root, state.fs, base_root, to, Mode::Checked)?;
1379 state.base = Some(tip);
1380 state.upstream = Some(head);
1381 report.updated_paths = self.write(&root, &mut state, &plan, base_root, to)?;
1382 report.updated = Updated::Rebased { head, tip };
1383 report.placed = placed;
1384 report.merged_paths = merged_paths;
1385 }
1386 Replayed::Stopped {
1387 index,
1388 onto,
1389 conflicts,
1390 mut placed,
1391 } => {
1392 let change = stack[index];
1393 state.upstream = Some(head);
1394 report.updated_paths = self.stop_on_conflicts(
1395 &root,
1396 &mut state,
1397 base_root,
1398 onto,
1399 change,
1400 &stack[index + 1..],
1401 &conflicts,
1402 )?;
1403 placed.extend(unplaced(&stack[index..]));
1404 report.updated = Updated::Conflicts {
1405 head,
1406 change,
1407 conflicts,
1408 };
1409 report.placed = placed;
1410 }
1411 }
1412 report.base = state.base;
1413 Ok(report)
1414 }
1415
1416 /// Marks conflicts of the rebase in progress resolved: those at each of
1417 /// `paths`, which must not be content conflicts with markers (those are
1418 /// resolved by editing the markers out). Returns the conflicts still
1419 /// unresolved.
1420 pub fn resolve(&self, paths: &[Vec<u8>]) -> Result<Vec<RecordedConflict>, Error> {
1421 let (_lock, mut state, _root) = self.begin()?;
1422 let rebase = state.rebase.as_mut().ok_or(Error::NoRebase)?;
1423 for path in paths {
1424 let mut found = false;
1425 for conflict in rebase.conflicts.iter_mut().filter(|c| &c.path == path) {
1426 if conflict.markers {
1427 return Err(Error::NotResolvable {
1428 path: path.clone(),
1429 reason: "a content conflict: edit the conflict markers out instead",
1430 });
1431 }
1432 conflict.resolved = true;
1433 found = true;
1434 }
1435 if !found {
1436 return Err(Error::NotResolvable {
1437 path: path.clone(),
1438 reason: "no conflict at this path",
1439 });
1440 }
1441 }
1442 let remaining = rebase
1443 .conflicts
1444 .iter()
1445 .filter(|c| !c.markers && !c.resolved)
1446 .cloned()
1447 .collect();
1448 state.save(&self.state_dir)?;
1449 Ok(remaining)
1450 }
1451
1452 /// Marks paths so that the secrets guard lets the new files at or below
1453 /// them be committed. Returns every mark.
1454 pub fn track(&self, paths: &[Vec<u8>]) -> Result<Vec<Vec<u8>>, Error> {
1455 let (_lock, mut state, _root) = self.begin()?;
1456 for path in paths {
1457 if !state.tracked.contains(path) {
1458 state.tracked.push(path.clone());
1459 }
1460 }
1461 state.tracked.sort();
1462 state.save(&self.state_dir)?;
1463 Ok(state.tracked)
1464 }
1465}
1466
1467/// What `create` did to the workspace's directory before filling it.
1468#[derive(Clone, Copy, Debug)]
1469enum Prepared {
1470 Created,
1471 WasEmpty,
1472}
1473
1474/// Removes everything inside `dir`, best effort, leaving it empty.
1475fn clear(dir: &Path) {
1476 let Ok(entries) = fs::read_dir(dir) else {
1477 return;
1478 };
1479 for entry in entries.flatten() {
1480 let path = entry.path();
1481 let _ = match entry.file_type() {
1482 Ok(kind) if kind.is_dir() => fs::remove_dir_all(&path),
1483 _ => fs::remove_file(&path),
1484 };
1485 }
1486}
1487
1488/// The conflicts of the rebase in progress, if any, each with whether
1489/// conflict markers remain in its file.
1490fn conflict_states(
1491 root: &Root,
1492 rebase: Option<&Rebase>,
1493) -> Result<Vec<(RecordedConflict, bool)>, Error> {
1494 let mut states = Vec::new();
1495 for conflict in rebase.map_or(&[][..], |rebase| &rebase.conflicts) {
1496 let remain = conflict.markers && markers_remain(root, &conflict.path)?;
1497 states.push((conflict.clone(), remain));
1498 }
1499 Ok(states)
1500}
1501
1502/// How many changesets lie on the first-parent chain of `head` above
1503/// `fork`: 0 when they are the same, the whole chain when `fork` is not on
1504/// it, and `None` past `limit`.
1505fn distance<O: Objects>(
1506 objects: &O,
1507 head: Option<ObjectId>,
1508 fork: Option<ObjectId>,
1509 limit: usize,
1510) -> Result<Option<usize>, Error> {
1511 let mut count = 0;
1512 let mut current = head;
1513 while current != fork {
1514 let Some(id) = current else {
1515 break;
1516 };
1517 if count == limit {
1518 return Ok(None);
1519 }
1520 count += 1;
1521 current = read_changeset(objects, id)?.parents.first().copied();
1522 }
1523 Ok(Some(count))
1524}
1525
1526/// Whether the regular file at `path` still holds conflict markers. A file
1527/// that is gone, or is not a regular file any more, holds none.
1528fn markers_remain(root: &Root, path: &[u8]) -> Result<bool, Error> {
1529 let (parent, name) = split_last(path);
1530 let Found::Here(dir) = root.open_dir(parent)? else {
1531 return Ok(false);
1532 };
1533 let Some(os) = os_name(name) else {
1534 return Ok(false);
1535 };
1536 let mut file = match open_file(&dir, os) {
1537 Ok(file) => file,
1538 Err(_) => return Ok(false),
1539 };
1540 let mut content = Vec::new();
1541 file.read_to_end(&mut content)
1542 .map_err(|err| root.error("read", path, err))?;
1543 Ok(has_markers(&content))
1544}
1545
1546/// Changesets that went nowhere.
1547pub(crate) fn unplaced(stack: &[ObjectId]) -> Vec<Placed> {
1548 stack
1549 .iter()
1550 .map(|&from| Placed { from, to: None })
1551 .collect()
1552}
1553
1554/// The first non-empty line of a message.
1555fn subject(message: &[u8]) -> String {
1556 String::from_utf8_lossy(message)
1557 .lines()
1558 .find(|line| !line.trim().is_empty())
1559 .unwrap_or("")
1560 .trim()
1561 .to_owned()
1562}
1563
1564/// The workspace's own changesets that `head` does not have, oldest first:
1565/// `base` and its first parents, back to the first one on `head`'s
1566/// first-parent chain. `hint` is where the last walk ended; when it is on
1567/// the chain, the walk stops there without reading the head's history.
1568pub(crate) fn find_stack<O: Objects>(
1569 objects: &O,
1570 head: Option<ObjectId>,
1571 base: Option<ObjectId>,
1572 hint: Option<ObjectId>,
1573) -> Result<Vec<ObjectId>, Error> {
1574 let Some(base) = base else {
1575 return Ok(Vec::new());
1576 };
1577 let parent = |id: ObjectId| -> Result<Option<ObjectId>, Error> {
1578 Ok(read_changeset(objects, id)?.parents.first().copied())
1579 };
1580 let Some(head) = head else {
1581 // A branch that does not exist has none of them.
1582 let mut stack = Vec::new();
1583 let mut current = Some(base);
1584 while let Some(id) = current {
1585 stack.push(id);
1586 current = parent(id)?;
1587 }
1588 stack.reverse();
1589 return Ok(stack);
1590 };
1591 if base == head {
1592 return Ok(Vec::new());
1593 }
1594 if let Some(hint) = hint
1595 && first_parent_chain_contains(objects, head, hint, usize::MAX)?
1596 {
1597 let mut stack = Vec::new();
1598 let mut current = Some(base);
1599 while let Some(id) = current {
1600 if id == hint {
1601 stack.reverse();
1602 return Ok(stack);
1603 }
1604 stack.push(id);
1605 current = parent(id)?;
1606 }
1607 }
1608 let mut on_branch = HashSet::new();
1609 let mut current = Some(head);
1610 while let Some(id) = current {
1611 on_branch.insert(id);
1612 current = parent(id)?;
1613 }
1614 let mut stack = Vec::new();
1615 let mut current = Some(base);
1616 while let Some(id) = current {
1617 if on_branch.contains(&id) {
1618 break;
1619 }
1620 stack.push(id);
1621 current = parent(id)?;
1622 }
1623 stack.reverse();
1624 Ok(stack)
1625}
1626
1627#[cfg(test)]
1628mod tests {
1629 use super::*;
1630 use braid_format::{Kind, MemoryObjects};
1631
1632 fn id(n: u8) -> ObjectId {
1633 ObjectId::hash(Kind::Changeset, &[n])
1634 }
1635
1636 #[test]
1637 fn distances_along_first_parents() {
1638 let objects = MemoryObjects::new();
1639 let signature = Signature {
1640 name: b"Ada".to_vec(),
1641 email: b"ada@example.org".to_vec(),
1642 seconds: 1_700_000_000,
1643 offset_minutes: 0,
1644 };
1645 let mut chain = Vec::new();
1646 for n in 0..10u8 {
1647 let blob = objects.put(Kind::Blob, &[n]).unwrap();
1648 let change = Change {
1649 path: b"f".to_vec(),
1650 op: ChangeOp::File { blob, size: 1 },
1651 };
1652 let id = braid_engine::commit(
1653 &objects,
1654 chain.last().copied().into_iter().collect(),
1655 vec![change],
1656 signature.clone(),
1657 signature.clone(),
1658 vec![n],
1659 Vec::new(),
1660 )
1661 .unwrap();
1662 chain.push(id);
1663 }
1664 let head = Some(chain[9]);
1665 let walk = |fork, limit| distance(&objects, head, fork, limit).unwrap();
1666 assert_eq!(walk(Some(chain[9]), 100), Some(0));
1667 assert_eq!(walk(Some(chain[6]), 100), Some(3));
1668 // Without a fork, or with one off the chain, the whole chain counts.
1669 assert_eq!(walk(None, 100), Some(10));
1670 assert_eq!(walk(Some(id(0)), 100), Some(10));
1671 // The walk stops at the limit.
1672 assert_eq!(walk(Some(chain[6]), 3), Some(3));
1673 assert_eq!(walk(Some(chain[6]), 2), None);
1674 // A branch that does not exist is not ahead of anything.
1675 assert_eq!(
1676 distance(&objects, None, Some(chain[0]), 5).unwrap(),
1677 Some(0)
1678 );
1679 }
1680
1681 #[test]
1682 fn landing_descriptions() {
1683 let one = [Placed {
1684 from: id(1),
1685 to: Some(id(2)),
1686 }];
1687 assert_eq!(
1688 describe_landing("land workspace b on main", "rebased", &one, 1),
1689 format!(
1690 "land workspace b on main: rebased {} -> {} (1 path merged)",
1691 id(1).short(),
1692 id(2).short()
1693 )
1694 );
1695 let two = [
1696 Placed {
1697 from: id(1),
1698 to: None,
1699 },
1700 Placed {
1701 from: id(3),
1702 to: Some(id(4)),
1703 },
1704 ];
1705 assert_eq!(
1706 describe_landing("land", "rebased", &two, 0),
1707 format!(
1708 "land: rebased 2 changesets: {} already applied, {} -> {} (0 paths merged)",
1709 id(1).short(),
1710 id(3).short(),
1711 id(4).short()
1712 )
1713 );
1714 let many: Vec<Placed> = (0..20)
1715 .map(|n| Placed {
1716 from: id(n),
1717 to: Some(id(n)),
1718 })
1719 .collect();
1720 let text = describe_landing("land", "fast-forward", &many, 2);
1721 assert!(
1722 text.starts_with("land: fast-forward 20 changesets: "),
1723 "{text}"
1724 );
1725 assert!(text.ends_with(", and 12 more (2 paths merged)"), "{text}");
1726 }
1727}