Elffuss BraidHub

utopia-ia/elffuss-braid public

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