Elffuss BraidHub

utopia-ia/elffuss-braid public

Land and update: one report, and op log entries that say what happened

land and update now report the same fields, and so does the landing of
change create --land: branch, outcome, head_before, head, landed (one
{from, to} per changeset of the stack, from its id in the workspace to
the changeset that holds it now, or null when it did not move), the
paths merged, operation, the conflicts, the changeset that conflicts,
and next, the command to run on conflicts: braid update after land,
braid commit after update. For a workspace they also give its base and
updated_paths, the paths the following checkout wrote or removed.

Conflicts name their sides from the caller's point of view: base,
branch (what the branch has now) and workspace (your change), for the
entries and for the hunks. The long help of land, update and change
create lists every field, and says that hunk lines count from 0 with
the end excluded.

The op log entry of a landing is written once the outcome is known,
through Store::transact_with: "land workspace agent-b on main: rebased
c57e1007e4f3 -> 3afaed346293 (1 path merged)", with every changeset of
a stack, the first eight named. change create --land says "land
changeset on main: ..." the same way.

braid_wc: Workspace::update returns an UpdateReport, LandReport gains
placed, merged_paths and updated_paths, and previous is head_before.
Changeset99b22bdf8c6a66a462ef8562726ccbbbaed678f6d89150941f43ccaad026b30b
AuthorKikoCis <KikoCis@users.noreply.github.com> · 2026-10-15 23:49 +02:00
CommitterKikoCis <KikoCis@users.noreply.github.com> · 2026-10-15 23:49 +02:00
Parents3533fe68b314

Browse the files at this changeset

10 files changed

modified crates/cli/src/main.rs +2 −0
@@ -118,9 +118,11 @@
118118 Commit(work::CommitArgs),
119119 /// Land the workspace's changesets on its branch (exit status 2 on
120120 /// conflicts).
121+ #[command(long_about = work::LAND_HELP)]
121122 Land(work::LandArgs),
122123 /// Bring the workspace onto its branch's head, rebasing its own
123124 /// changesets (exit status 2 on conflicts).
125+ #[command(long_about = work::UPDATE_HELP)]
124126 Update(work::IdentityArgs),
125127 /// Mark conflicts of a rebase in progress resolved.
126128 Resolve {
modified crates/cli/src/work.rs +285 −132
@@ -17,8 +17,8 @@
1717 use braid_format::{ChangeOp, EntryKind, ObjectId};
1818 use braid_repo::{Location, Repo};
1919 use braid_wc::{
20- ChangeRequest, CommitRequest, Expect, Identity, LandReport, Landed, RebaseProgress, Updated,
21- Workspace,
20+ ChangeRequest, CommitRequest, Expect, Identity, LandReport, Landed, Placed, RebaseProgress,
21+ UpdateReport, Updated, Workspace,
2222 };
2323 use clap::{Args, Subcommand};
2424 use serde_json::{Value, json};
@@ -28,6 +28,80 @@
2828 /// Exit status of a command that stopped on conflicts.
2929 const CONFLICTS: u8 = 2;
3030
31+/// The fields of the report `land`, `update` and `change create --land`
32+/// print with `--json`, for their long help.
33+macro_rules! report_fields {
34+ () => {
35+ "With --json, land and update print one object with these fields;
36+change create --land prints it as \"land\", without base and updated_paths.
37+
38+ branch the branch landed on, or updated from
39+ outcome land: fast-forward, rebased, already-applied, nothing or
40+ conflicts; update: up-to-date, moved, rebased or conflicts
41+ head_before the branch's head before the command
42+ head the branch's head after it (update never moves it)
43+ base the workspace's base after the command
44+ landed one {from, to} per changeset of the workspace, oldest
45+ first: its id, and the id of the changeset that holds it
46+ now (itself after a fast-forward, the rebased one after a
47+ rebase), or null when it did not move: its changes were
48+ there already, or a conflict stopped it or one before it
49+ merged_paths paths both sides changed, merged line by line
50+ operation the op log operation that moved the branch, or null
51+ updated_paths paths of the working copy written or removed, sorted
52+ change the changeset that conflicts, or null
53+ conflicts one per conflict: path; kind, one of CONTENT,
54+ MODIFY_DELETE, MODE, DF, DIR_REMOVED and CASE; and what
55+ each side has at the path, null or an entry {kind, ...}:
56+ base (the common ancestor), branch (what the branch has
57+ now) and workspace (your change). A CONTENT conflict of
58+ text files has hunks: the regions in conflict, each with
59+ the same three sides as {start, end, text}, where start
60+ and end are line numbers counted from 0 and end is
61+ excluded (an empty range sits before line start)
62+ next on conflicts, what to run next: braid update after land;
63+ braid commit, once the files are fixed, after update; a
64+ new change create on the branch after change create;
65+ otherwise null
66+
67+Ids in JSON are full; text output shows their first 12 hex digits."
68+ };
69+}
70+
71+/// The long help of `land`.
72+pub(crate) const LAND_HELP: &str = concat!(
73+ "Land the workspace's changesets on its branch, in one step: a
74+fast-forward when they were built on the head, a rebase onto it otherwise.
75+The working copy then follows the landed tree. On conflicts the branch does
76+not move and the exit status is 2; `braid update` brings the conflicts into
77+the working copy.
78+
79+",
80+ report_fields!()
81+);
82+
83+/// The long help of `update`.
84+pub(crate) const UPDATE_HELP: &str = concat!(
85+ "Bring the workspace onto its branch's head, rebasing its own changesets
86+without moving the branch. On conflicts the exit status is 2: the working
87+copy gets the head's tree with the clean paths and conflict markers, and a
88+rebase is in progress until `braid commit`.
89+
90+",
91+ report_fields!()
92+);
93+
94+/// The long help of `change create`.
95+pub(crate) const CREATE_HELP: &str = concat!(
96+ "Make a changeset on a base without a working copy, and optionally land
97+it (exit status 2 on conflicts). Prints JSON whether or not --json is
98+given: change, the new changeset's id; base; and land, the report of the
99+landing, or null.
100+
101+",
102+ report_fields!()
103+);
104+
31105 #[derive(Debug, Subcommand)]
32106 pub(crate) enum WorkspaceAction {
33107 /// Create a workspace and write its files.
@@ -96,6 +170,7 @@
96170 pub(crate) enum ChangeAction {
97171 /// Make a changeset on a base without a working copy, and optionally
98172 /// land it (exit status 2 on conflicts). Prints the ids as JSON.
173+ #[command(long_about = CREATE_HELP)]
99174 Create(CreateArgs),
100175 }
101176
@@ -467,67 +542,175 @@
467542 })
468543 }
469544
470-/// Prints a landing's report and returns the exit status it calls for.
471-fn report_landing(cli: &Cli, report: &LandReport) -> Result<ExitCode> {
472- let (outcome, changeset) = match &report.landed {
473- Landed::Nothing => ("nothing", None),
474- Landed::FastForward(id) => ("fast-forward", Some(*id)),
475- Landed::Rebased(id) => ("rebased", Some(*id)),
476- Landed::AlreadyApplied => ("already-applied", None),
477- Landed::Conflicts { change, .. } => ("conflicts", Some(*change)),
478- };
479- let conflicts: &[Conflict] = match &report.landed {
480- Landed::Conflicts { conflicts, .. } => conflicts,
481- _ => &[],
482- };
483- if cli.json {
484- print_json(&json!({
485- "branch": report.branch,
486- "outcome": outcome,
487- "previous": hex(report.previous),
488- "head": hex(report.head()),
489- "changeset": hex(changeset),
490- "operation": report.operation,
491- "conflicts": conflicts.iter().map(conflict_json).collect::<Vec<_>>(),
492- }))?;
493- } else {
494- match &report.landed {
495- Landed::Nothing => println!("Nothing to land on {}", report.branch),
496- Landed::FastForward(id) => {
497- println!("Landed {} on {} (fast-forward)", id.short(), report.branch);
498- }
499- Landed::Rebased(id) => println!(
500- "Landed on {} as {}, rebased onto {}",
501- report.branch,
502- id.short(),
503- short(report.previous)
504- ),
505- Landed::AlreadyApplied => println!("{} already has these changes", report.branch),
506- Landed::Conflicts { change, conflicts } => {
507- println!(
508- "{} conflicts with {} at {}; {} did not move:",
509- change.short(),
510- report.branch,
511- short(report.previous),
512- report.branch
513- );
514- print_conflicts(conflicts);
515- }
545+/// What `land`, `update` and `change create --land` report, in one shape:
546+/// the fields their long help lists.
547+struct Report<'a> {
548+ branch: &'a str,
549+ outcome: &'static str,
550+ head_before: Option<ObjectId>,
551+ head: Option<ObjectId>,
552+ placed: &'a [Placed],
553+ merged_paths: &'a [Vec<u8>],
554+ operation: Option<u64>,
555+ change: Option<ObjectId>,
556+ conflicts: &'a [Conflict],
557+ next: Option<String>,
558+ /// For a workspace: its base afterwards, and the paths of its working
559+ /// copy written or removed.
560+ workspace: Option<(Option<ObjectId>, &'a [Vec<u8>])>,
561+}
562+
563+impl<'a> Report<'a> {
564+ fn landing(report: &'a LandReport) -> Report<'a> {
565+ let (outcome, change, conflicts): (_, _, &[Conflict]) = match &report.landed {
566+ Landed::Nothing => ("nothing", None, &[]),
567+ Landed::FastForward(_) => ("fast-forward", None, &[]),
568+ Landed::Rebased(_) => ("rebased", None, &[]),
569+ Landed::AlreadyApplied => ("already-applied", None, &[]),
570+ Landed::Conflicts { change, conflicts } => ("conflicts", Some(*change), conflicts),
571+ };
572+ Report {
573+ branch: &report.branch,
574+ outcome,
575+ head_before: report.head_before,
576+ head: report.head(),
577+ placed: &report.placed,
578+ merged_paths: &report.merged_paths,
579+ operation: report.operation,
580+ change,
581+ conflicts,
582+ next: None,
583+ workspace: None,
584+ }
585+ }
586+
587+ fn update(report: &'a UpdateReport) -> Report<'a> {
588+ let (outcome, change, conflicts): (_, _, &[Conflict]) = match &report.updated {
589+ Updated::UpToDate => ("up-to-date", None, &[]),
590+ Updated::Moved { .. } => ("moved", None, &[]),
591+ Updated::Rebased { .. } => ("rebased", None, &[]),
592+ Updated::Conflicts {
593+ change, conflicts, ..
594+ } => ("conflicts", Some(*change), conflicts),
595+ };
596+ Report {
597+ branch: &report.branch,
598+ outcome,
599+ // An update reads the head and never moves it.
600+ head_before: report.head,
601+ head: report.head,
602+ placed: &report.placed,
603+ merged_paths: &report.merged_paths,
604+ operation: None,
605+ change,
606+ conflicts,
607+ next: (!conflicts.is_empty()).then(|| "braid commit".to_owned()),
608+ workspace: Some((report.base, &report.updated_paths)),
609+ }
610+ }
611+
612+ fn json(&self) -> Value {
613+ let mut value = json!({
614+ "branch": self.branch,
615+ "outcome": self.outcome,
616+ "head_before": hex(self.head_before),
617+ "head": hex(self.head),
618+ "landed": self.placed.iter().map(|placed| json!({
619+ "from": placed.from.to_hex(),
620+ "to": hex(placed.to),
621+ })).collect::<Vec<_>>(),
622+ "merged_paths": self.merged_paths.iter().map(|p| show(p)).collect::<Vec<_>>(),
623+ "operation": self.operation,
624+ "change": hex(self.change),
625+ "conflicts": self.conflicts.iter().map(conflict_json).collect::<Vec<_>>(),
626+ "next": self.next,
627+ });
628+ if let Some((base, updated)) = self.workspace {
629+ value["base"] = hex(base);
630+ value["updated_paths"] = updated.iter().map(|p| Value::String(show(p))).collect();
631+ }
632+ value
633+ }
634+
635+ fn exit_code(&self) -> ExitCode {
636+ if self.conflicts.is_empty() {
637+ ExitCode::SUCCESS
638+ } else {
639+ ExitCode::from(CONFLICTS)
640+ }
641+ }
642+
643+ /// `, 1 path merged`, or nothing when none was.
644+ fn merged(&self) -> String {
645+ match self.merged_paths.len() {
646+ 0 => String::new(),
647+ n => format!(" ({} merged)", count(n, "path")),
648+ }
649+ }
650+
651+ /// Says how many paths of the working copy changed, if any did.
652+ fn print_updated(&self) {
653+ if let Some((_, updated)) = self.workspace
654+ && !updated.is_empty()
655+ {
656+ println!(
657+ "Updated {} in the working copy",
658+ count(updated.len(), "path")
659+ );
516660 }
517661 }
518- Ok(if conflicts.is_empty() {
519- ExitCode::SUCCESS
520- } else {
521- ExitCode::from(CONFLICTS)
522- })
523662 }
524663
525664 pub(crate) fn land(cli: &Cli, args: &LandArgs) -> Result<ExitCode> {
526665 let target = Target::find(cli)?;
527666 let workspace = target.open()?;
528667 let committer = identity(&args.identity, &target.repo)?;
529- let report = workspace.land(args.onto.as_deref(), &cli.agent, &committer)?;
530- report_landing(cli, &report)
668+ let landing = workspace.land(args.onto.as_deref(), &cli.agent, &committer)?;
669+ let mut report = Report::landing(&landing);
670+ report.workspace = Some((workspace.state()?.base, &landing.updated_paths));
671+ if !report.conflicts.is_empty() {
672+ report.next = Some("braid update".to_owned());
673+ }
674+ if cli.json {
675+ print_json(&report.json())?;
676+ return Ok(report.exit_code());
677+ }
678+ let branch = &landing.branch;
679+ let several = landing.placed.len() > 1;
680+ match &landing.landed {
681+ Landed::Nothing => println!("Nothing to land on {branch}"),
682+ Landed::FastForward(id) if several => println!(
683+ "Landed {} on {branch} (fast-forward), up to {}",
684+ count(landing.placed.len(), "changeset"),
685+ id.short()
686+ ),
687+ Landed::FastForward(id) => println!("Landed {} on {branch} (fast-forward)", id.short()),
688+ Landed::Rebased(id) if several => println!(
689+ "Landed {} on {branch}, rebased onto {}; the last is {}{}",
690+ count(landing.placed.len(), "changeset"),
691+ short(landing.head_before),
692+ id.short(),
693+ report.merged()
694+ ),
695+ Landed::Rebased(id) => println!(
696+ "Landed on {branch} as {}, rebased onto {}{}",
697+ id.short(),
698+ short(landing.head_before),
699+ report.merged()
700+ ),
701+ Landed::AlreadyApplied => println!("{branch} already has these changes"),
702+ Landed::Conflicts { change, conflicts } => {
703+ println!(
704+ "{} conflicts with {branch} at {}; {branch} did not move:",
705+ change.short(),
706+ short(landing.head_before),
707+ );
708+ print_conflicts(conflicts);
709+ println!("Run `braid update` to bring the conflicts into the working copy.");
710+ }
711+ }
712+ report.print_updated();
713+ Ok(report.exit_code())
531714 }
532715
533716 pub(crate) fn update(cli: &Cli, args: &IdentityArgs) -> Result<ExitCode> {
@@ -535,56 +718,38 @@
535718 let workspace = target.open()?;
536719 let committer = identity(args, &target.repo)?;
537720 let updated = workspace.update(&committer)?;
538- let (outcome, head, base, conflicts): (&str, Option<ObjectId>, Option<ObjectId>, &[Conflict]) =
539- match &updated {
540- Updated::UpToDate => ("up-to-date", None, None, &[]),
541- Updated::Moved { head } => ("moved", Some(*head), Some(*head), &[]),
542- Updated::Rebased { head, tip } => ("rebased", Some(*head), Some(*tip), &[]),
543- Updated::Conflicts {
544- head, conflicts, ..
545- } => ("conflicts", Some(*head), Some(*head), conflicts),
546- };
721+ let report = Report::update(&updated);
547722 if cli.json {
548- let change = match &updated {
549- Updated::Conflicts { change, .. } => Some(*change),
550- _ => None,
551- };
552- print_json(&json!({
553- "outcome": outcome,
554- "head": hex(head),
555- "base": hex(base.or(workspace.state()?.base)),
556- "change": hex(change),
557- "conflicts": conflicts.iter().map(conflict_json).collect::<Vec<_>>(),
558- }))?;
559- } else {
560- match &updated {
561- Updated::UpToDate => println!("Up to date"),
562- Updated::Moved { head } => println!("Moved to {}", head.short()),
563- Updated::Rebased { head, tip } => {
564- println!("Rebased onto {}; now at {}", head.short(), tip.short());
565- }
566- Updated::Conflicts {
567- head,
568- change,
569- conflicts,
570- } => {
571- println!(
572- "{} conflicts with {}; the working copy has the merge so far:",
573- change.short(),
574- head.short()
575- );
576- print_conflicts(conflicts);
577- println!(
578- "Fix the files, `braid resolve` the other conflicts, then `braid commit`."
579- );
580- }
723+ print_json(&report.json())?;
724+ return Ok(report.exit_code());
725+ }
726+ match &updated.updated {
727+ Updated::UpToDate => println!("Up to date"),
728+ Updated::Moved { head } => println!("Moved to {}", head.short()),
729+ Updated::Rebased { head, tip } => {
730+ println!(
731+ "Rebased onto {}; now at {}{}",
732+ head.short(),
733+ tip.short(),
734+ report.merged()
735+ );
736+ }
737+ Updated::Conflicts {
738+ head,
739+ change,
740+ conflicts,
741+ } => {
742+ println!(
743+ "{} conflicts with {}; the working copy has the merge so far:",
744+ change.short(),
745+ head.short()
746+ );
747+ print_conflicts(conflicts);
748+ println!("Fix the files, `braid resolve` the other conflicts, then `braid commit`.");
581749 }
582750 }
583- Ok(if conflicts.is_empty() {
584- ExitCode::SUCCESS
585- } else {
586- ExitCode::from(CONFLICTS)
587- })
751+ report.print_updated();
752+ Ok(report.exit_code())
588753 }
589754
590755 pub(crate) fn resolve(cli: &Cli, paths: &[PathBuf]) -> Result<ExitCode> {
@@ -724,7 +889,15 @@
724889 );
725890 // Always JSON: this command is for agents, which want the ids.
726891 let land = match &landing {
727- Some(report) => landing_json(report),
892+ Some(landing) => {
893+ let mut report = Report::landing(landing);
894+ if !report.conflicts.is_empty() {
895+ // The change was built on a base the branch has moved past:
896+ // it is made again on the new head.
897+ report.next = Some(format!("braid change create --base {}", landing.branch));
898+ }
899+ report.json()
900+ }
728901 None => Value::Null,
729902 };
730903 print_json(&json!({
@@ -739,28 +912,6 @@
739912 })
740913 }
741914
742-fn landing_json(report: &LandReport) -> Value {
743- let outcome = match &report.landed {
744- Landed::Nothing => "nothing",
745- Landed::FastForward(_) => "fast-forward",
746- Landed::Rebased(_) => "rebased",
747- Landed::AlreadyApplied => "already-applied",
748- Landed::Conflicts { .. } => "conflicts",
749- };
750- let conflicts: &[Conflict] = match &report.landed {
751- Landed::Conflicts { conflicts, .. } => conflicts,
752- _ => &[],
753- };
754- json!({
755- "branch": report.branch,
756- "outcome": outcome,
757- "previous": hex(report.previous),
758- "head": hex(report.head()),
759- "operation": report.operation,
760- "conflicts": conflicts.iter().map(conflict_json).collect::<Vec<_>>(),
761- })
762-}
763-
764915 fn entry_json(entry: &Option<EntryKind>) -> Value {
765916 match entry {
766917 None => Value::Null,
@@ -792,16 +943,18 @@
792943 })
793944 }
794945
795-/// A conflict as data: the path, the kind's code, the entries of the base,
796-/// ours (the branch head) and theirs (the change), and for content
797-/// conflicts the hunks.
946+/// A conflict as data, with its sides named from the caller's point of
947+/// view: the path, the kind's code, the entries of `base` (the common
948+/// ancestor), `branch` (what the branch has now) and `workspace` (the
949+/// change: the workspace's, or the one `change create` made), and for
950+/// content conflicts the hunks, with the same three sides.
798951 pub(crate) fn conflict_json(conflict: &Conflict) -> Value {
799952 let mut value = json!({
800953 "path": show(&conflict.path),
801954 "kind": conflict.kind.code(),
802955 "base": entry_json(&conflict.base),
803- "ours": entry_json(&conflict.ours),
804- "theirs": entry_json(&conflict.theirs),
956+ "branch": entry_json(&conflict.ours),
957+ "workspace": entry_json(&conflict.theirs),
805958 "hunks": [],
806959 });
807960 match &conflict.kind {
@@ -811,8 +964,8 @@
811964 .map(|hunk| {
812965 json!({
813966 "base": side_json(&hunk.base),
814- "ours": side_json(&hunk.ours),
815- "theirs": side_json(&hunk.theirs),
967+ "branch": side_json(&hunk.ours),
968+ "workspace": side_json(&hunk.theirs),
816969 })
817970 })
818971 .collect();
modified crates/cli/tests/workspaces.rs +144 −3
@@ -177,7 +177,7 @@
177177 assert_eq!(landed["outcome"], "fast-forward");
178178 let landed = json(second, &["land"]);
179179 assert_eq!(landed["outcome"], "rebased");
180- assert_eq!(landed["previous"], json(first, &["status"])["base"]);
180+ assert_eq!(landed["head_before"], json(first, &["status"])["base"]);
181181
182182 // Both changes are on main, once each, on a linear history.
183183 let log = history(&repo);
@@ -230,9 +230,12 @@
230230 let conflict = &landed["conflicts"][0];
231231 assert_eq!(conflict["path"], "shared.txt");
232232 assert_eq!(conflict["kind"], "CONTENT");
233- assert_eq!(conflict["hunks"][0]["ours"]["text"], "TWO from a\n");
234- assert_eq!(conflict["hunks"][0]["theirs"]["text"], "TWO from b\n");
233+ assert_eq!(conflict["hunks"][0]["branch"]["text"], "TWO from a\n");
234+ assert_eq!(conflict["hunks"][0]["workspace"]["text"], "TWO from b\n");
235235 assert_eq!(conflict["base"]["kind"], "file");
236+ assert_eq!(conflict["branch"]["kind"], "file");
237+ assert!(conflict.get("ours").is_none() && conflict.get("theirs").is_none());
238+ assert_eq!(landed["next"], "braid update");
236239 assert_eq!(repo.main(), main_before);
237240
238241 // Update writes the conflict with markers, and a rebase is in progress.
@@ -398,6 +401,21 @@
398401 );
399402 assert_eq!(made["land"]["outcome"], "fast-forward");
400403 assert_eq!(repo.main().as_deref(), made["change"].as_str());
404+ let change = made["change"].as_str().unwrap();
405+ assert_eq!(
406+ made["land"]["landed"],
407+ serde_json::json!([{ "from": change, "to": change }])
408+ );
409+ assert!(made["land"].get("updated_paths").is_none());
410+ let op = &json(&repo.root, &["op", "log", "-n", "1"])[0];
411+ assert_eq!(
412+ op["description"],
413+ format!(
414+ "land changeset on main: fast-forward {} -> {} (0 paths merged)",
415+ &change[..12],
416+ &change[..12]
417+ )
418+ );
401419
402420 // Another agent, still believing the old content, is stopped before
403421 // anything is made: its base holds another blob now.
@@ -464,6 +482,18 @@
464482 );
465483 assert_eq!(conflicted["land"]["outcome"], "conflicts");
466484 assert_eq!(conflicted["land"]["conflicts"][0]["kind"], "CONTENT");
485+ assert_eq!(
486+ conflicted["land"]["conflicts"][0]["workspace"]["size"],
487+ "a = 3\n".len()
488+ );
489+ assert_eq!(
490+ conflicted["land"]["next"],
491+ "braid change create --base main"
492+ );
493+ assert_eq!(
494+ conflicted["land"]["landed"],
495+ serde_json::json!([{ "from": conflicted["change"], "to": null }])
496+ );
467497 assert_eq!(repo.main().as_deref(), made["change"].as_str());
468498
469499 // Content from standard input.
@@ -670,6 +700,37 @@
670700 let landed = json(&ws, &["land"]);
671701 assert_eq!(landed["outcome"], "rebased");
672702 let log = history(&repo);
703+ // The report and the op log say where each went.
704+ let id = |c: &Value| c["changeset"].as_str().unwrap().to_owned();
705+ let moves: Vec<(String, String)> = landed["landed"]
706+ .as_array()
707+ .unwrap()
708+ .iter()
709+ .map(|m| {
710+ (
711+ m["from"].as_str().unwrap().to_owned(),
712+ m["to"].as_str().unwrap().to_owned(),
713+ )
714+ })
715+ .collect();
716+ assert_eq!(
717+ moves,
718+ [
719+ (id(&first), log[1]["id"].as_str().unwrap().to_owned()),
720+ (id(&second), log[0]["id"].as_str().unwrap().to_owned()),
721+ ]
722+ );
723+ let op = &json(&repo.root, &["op", "log", "-n", "1"])[0];
724+ assert_eq!(
725+ op["description"],
726+ format!(
727+ "land workspace ws on main: rebased 2 changesets: {} -> {}, {} -> {} (0 paths merged)",
728+ &moves[0].0[..12],
729+ &moves[0].1[..12],
730+ &moves[1].0[..12],
731+ &moves[1].1[..12]
732+ )
733+ );
673734 let messages: Vec<&str> = log.iter().map(|c| c["message"].as_str().unwrap()).collect();
674735 assert_eq!(messages, ["second", "first", "other", "seed"]);
675736 assert_eq!(
@@ -685,6 +746,86 @@
685746 assert!(repo.fsck_is_clean());
686747 }
687748
749+#[test]
750+fn land_and_update_print_the_same_fields() {
751+ let fields = [
752+ "base",
753+ "branch",
754+ "change",
755+ "conflicts",
756+ "head",
757+ "head_before",
758+ "landed",
759+ "merged_paths",
760+ "next",
761+ "operation",
762+ "outcome",
763+ "updated_paths",
764+ ];
765+ let keys = |report: &Value| {
766+ let mut keys: Vec<String> = report.as_object().unwrap().keys().cloned().collect();
767+ keys.sort();
768+ keys
769+ };
770+ let repo = Repo::new();
771+ seed(&repo, &[("a.txt", "1\n"), ("b.txt", "1\n")]);
772+ let ws = repo.workspace("ws");
773+ let other = repo.workspace("other");
774+ write(&ws, "a.txt", "2\n");
775+ let first = json(&ws, &["commit", "-m", "first"]);
776+ write(&other, "b.txt", "other\n");
777+ json(&other, &["commit", "-m", "other"]);
778+ let theirs = json(&other, &["land"]);
779+ let head = theirs["head"].as_str().unwrap().to_owned();
780+
781+ // update rebases the workspace's changeset onto the head, and brings
782+ // b.txt into the working copy.
783+ let updated = json(&ws, &["update"]);
784+ assert_eq!(keys(&updated), fields);
785+ assert_eq!(updated["outcome"], "rebased");
786+ assert_eq!(updated["head_before"], head.as_str());
787+ assert_eq!(updated["head"], head.as_str());
788+ assert_eq!(updated["operation"], Value::Null);
789+ assert_eq!(updated["next"], Value::Null);
790+ assert_eq!(updated["updated_paths"], serde_json::json!(["b.txt"]));
791+ let rebased = updated["base"].as_str().unwrap().to_owned();
792+ assert_eq!(
793+ updated["landed"],
794+ serde_json::json!([{ "from": first["changeset"], "to": rebased }])
795+ );
796+
797+ // land then fast-forwards to it, and writes nothing.
798+ let landed = json(&ws, &["land"]);
799+ assert_eq!(keys(&landed), fields);
800+ assert_eq!(landed["outcome"], "fast-forward");
801+ assert_eq!(landed["head_before"], head.as_str());
802+ assert_eq!(landed["head"], rebased.as_str());
803+ assert_eq!(landed["base"], rebased.as_str());
804+ assert_eq!(
805+ landed["landed"],
806+ serde_json::json!([{ "from": rebased, "to": rebased }])
807+ );
808+ assert_eq!(landed["updated_paths"], serde_json::json!([]));
809+ let op = &json(&repo.root, &["op", "log", "-n", "1"])[0];
810+ assert_eq!(op["seq"], landed["operation"]);
811+ assert_eq!(
812+ op["description"],
813+ format!(
814+ "land workspace ws on main: fast-forward {} -> {} (0 paths merged)",
815+ &rebased[..12],
816+ &rebased[..12]
817+ )
818+ );
819+ // Nothing left: both report it the same way.
820+ let nothing = json(&ws, &["land"]);
821+ assert_eq!(keys(&nothing), fields);
822+ assert_eq!(nothing["outcome"], "nothing");
823+ assert_eq!(nothing["landed"], serde_json::json!([]));
824+ let up_to_date = json(&ws, &["update"]);
825+ assert_eq!(keys(&up_to_date), fields);
826+ assert_eq!(up_to_date["outcome"], "up-to-date");
827+}
828+
688829 #[test]
689830 fn a_conflict_that_is_not_about_content_needs_resolve() {
690831 let repo = Repo::new();
modified crates/wc/src/change.rs +45 −26
@@ -14,7 +14,7 @@
1414
1515 use crate::error::Error;
1616 use crate::identity::Identity;
17-use crate::workspace::{LandReport, Landed};
17+use crate::workspace::{LandReport, Landed, Placed, describe_landing};
1818
1919 /// What the base must hold at a path.
2020 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -142,7 +142,8 @@
142142
143143 /// Lands `change` on `branch` in one op log transaction: the engine
144144 /// fast-forwards or rebases it onto the head, and the branch moves with a
145-/// compare-and-swap. With conflicts, or when the branch already has it, the
145+/// compare-and-swap. The operation says how it went, as a workspace's
146+/// landing does. With conflicts, or when the branch already has it, the
146147 /// branch does not move and no operation is recorded.
147148 pub fn land_change(
148149 store: &Store,
@@ -152,31 +153,42 @@
152153 committer: &Identity,
153154 ) -> Result<LandReport, Error> {
154155 let signature = committer.now();
155- let mut previous = None;
156+ let mut head_before = None;
156157 let mut landed = Landed::Nothing;
157- let description = format!("land {} on {branch}", change.short());
158- let result = store.transact(agent, &description, |refs| {
158+ let mut merged = Vec::new();
159+ let prefix = format!("land changeset on {branch}");
160+ let result = store.transact_with(agent, |refs| {
159161 let head = refs.get(branch);
160- previous = head;
161- let new = match land(store, head, change, signature).map_err(|err| Some(err.into()))? {
162- LandOutcome::FastForward(id) => {
163- landed = Landed::FastForward(id);
164- id
165- }
166- LandOutcome::Rebased { changeset, .. } => {
167- landed = Landed::Rebased(changeset);
168- changeset
169- }
170- LandOutcome::AlreadyApplied => {
171- landed = Landed::AlreadyApplied;
172- return Err(None);
173- }
174- LandOutcome::Conflicts(conflicts) => {
175- landed = Landed::Conflicts { change, conflicts };
176- return Err(None);
177- }
178- };
179- Ok(vec![RefUpdate::new(branch, head, Some(new))])
162+ head_before = head;
163+ let (new, outcome) =
164+ match land(store, head, change, signature).map_err(|err| Some(err.into()))? {
165+ LandOutcome::FastForward(id) => {
166+ landed = Landed::FastForward(id);
167+ (id, "fast-forward")
168+ }
169+ LandOutcome::Rebased {
170+ changeset,
171+ merged_paths,
172+ } => {
173+ landed = Landed::Rebased(changeset);
174+ merged = merged_paths;
175+ (changeset, "rebased")
176+ }
177+ LandOutcome::AlreadyApplied => {
178+ landed = Landed::AlreadyApplied;
179+ return Err(None);
180+ }
181+ LandOutcome::Conflicts(conflicts) => {
182+ landed = Landed::Conflicts { change, conflicts };
183+ return Err(None);
184+ }
185+ };
186+ let placed = [Placed {
187+ from: change,
188+ to: Some(new),
189+ }];
190+ let description = describe_landing(&prefix, outcome, &placed, merged.len());
191+ Ok((vec![RefUpdate::new(branch, head, Some(new))], description))
180192 });
181193 let operation = match result {
182194 Ok(op) => Some(op.seq),
@@ -185,11 +197,18 @@
185197 Err(TransactError::Aborted(Some(err))) => return Err(err),
186198 Err(TransactError::Store(err)) => return Err(err.into()),
187199 };
200+ let to = match &landed {
201+ Landed::FastForward(id) | Landed::Rebased(id) => Some(*id),
202+ _ => None,
203+ };
188204 Ok(LandReport {
189205 branch: branch.to_owned(),
190- previous,
206+ head_before,
191207 landed,
192208 operation,
209+ placed: vec![Placed { from: change, to }],
210+ merged_paths: merged,
211+ updated_paths: Vec::new(),
193212 })
194213 }
195214
modified crates/wc/src/checkout.rs +14 −0
@@ -59,6 +59,20 @@
5959 pub(crate) fn len(&self) -> usize {
6060 self.removes.len() + self.writes.len()
6161 }
62+
63+ /// The paths the checkout writes or removes, sorted: files, symlinks
64+ /// and gitlinks, not the directories that come and go with them.
65+ pub(crate) fn paths(&self) -> Vec<Vec<u8>> {
66+ let mut paths: Vec<Vec<u8>> = self
67+ .removes
68+ .iter()
69+ .chain(&self.writes)
70+ .map(|(path, _)| path.clone())
71+ .collect();
72+ paths.sort();
73+ paths.dedup();
74+ paths
75+ }
6276 }
6377
6478 /// Plans the checkout that turns the working copy of tree `from` into tree
modified crates/wc/src/lib.rs +2 −2
@@ -74,6 +74,6 @@
7474 pub use state::{Checkout, Rebase, RecordedConflict, State};
7575 pub use status::{ChangeKind, GUARD_SIZE, PathChange, Status, is_guarded};
7676 pub use workspace::{
77- CommitOutcome, CommitRequest, LandReport, Landed, RebaseProgress, StatusReport, Updated,
78- Workspace,
77+ CommitOutcome, CommitRequest, LandReport, Landed, Placed, RebaseProgress, StatusReport,
78+ UpdateReport, Updated, Workspace,
7979 };
modified crates/wc/src/rebase.rs +34 −8
@@ -27,6 +27,7 @@
2727 use crate::paths::is_within;
2828 use crate::state::RecordedConflict;
2929 use crate::tree::root_of;
30+use crate::workspace::Placed;
3031
3132 /// The extra field a temporary base carries, so that it can be told apart.
3233 pub const TEMPORARY: &[u8] = b"braid-temporary-base";
@@ -36,13 +37,22 @@
3637 pub(crate) enum Replayed {
3738 /// Every changeset is on top of the head; `tip` is the last of them, or
3839 /// the head itself when it had all of them already.
39- Done { tip: ObjectId, rebased: bool },
40+ Done {
41+ tip: ObjectId,
42+ rebased: bool,
43+ /// Where each changeset of the stack went, in order.
44+ placed: Vec<Placed>,
45+ /// The paths both sides changed, over the whole stack, sorted.
46+ merged_paths: Vec<Vec<u8>>,
47+ },
4048 /// The changeset at `index` of the stack conflicts with `onto`, the head
4149 /// or the last changeset replayed before it.
4250 Stopped {
4351 index: usize,
4452 onto: ObjectId,
4553 conflicts: Vec<Conflict>,
54+ /// Where the changesets before `index` went.
55+ placed: Vec<Placed>,
4656 },
4757 }
4858
@@ -72,6 +82,8 @@
7282 ) -> Result<Replayed, Error> {
7383 let mut tip = head;
7484 let mut rebased = false;
85+ let mut placed = Vec::with_capacity(stack.len());
86+ let mut merged = Vec::new();
7587 for (index, &change) in stack.iter().enumerate() {
7688 let outcome = match tip {
7789 Some(onto) if index > 0 || first == First::Pick => {
@@ -89,13 +101,17 @@
89101 other => other?,
90102 },
91103 };
92- match outcome {
93- LandOutcome::FastForward(id) => tip = Some(id),
94- LandOutcome::Rebased { changeset, .. } => {
95- tip = Some(changeset);
104+ let to = match outcome {
105+ LandOutcome::FastForward(id) => Some(id),
106+ LandOutcome::Rebased {
107+ changeset,
108+ merged_paths,
109+ } => {
96110 rebased = true;
111+ merged.extend(merged_paths);
112+ Some(changeset)
97113 }
98- LandOutcome::AlreadyApplied => {}
114+ LandOutcome::AlreadyApplied => None,
99115 LandOutcome::Conflicts(conflicts) => {
100116 let onto = tip.ok_or(Error::NotOnBranch {
101117 branch: branch.to_owned(),
@@ -104,12 +120,22 @@
104120 index,
105121 onto,
106122 conflicts,
123+ placed,
107124 });
108125 }
109- }
126+ };
127+ tip = to.or(tip);
128+ placed.push(Placed { from: change, to });
110129 }
130+ merged.sort();
131+ merged.dedup();
111132 match tip {
112- Some(tip) => Ok(Replayed::Done { tip, rebased }),
133+ Some(tip) => Ok(Replayed::Done {
134+ tip,
135+ rebased,
136+ placed,
137+ merged_paths: merged,
138+ }),
113139 None => Err(Error::NotOnBranch {
114140 branch: branch.to_owned(),
115141 }),
modified crates/wc/src/workspace.rs +303 −108
@@ -133,17 +133,38 @@
133133 },
134134 }
135135
136+/// One changeset of a workspace, and the changeset that holds it now.
137+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138+pub struct Placed {
139+ /// The changeset as the workspace had it.
140+ pub from: ObjectId,
141+ /// What holds it now: the same changeset after a fast-forward, the
142+ /// rebased one after a rebase, or `None` when it did not go anywhere:
143+ /// the branch had its changes already, or a conflict stopped it or one
144+ /// before it.
145+ pub to: Option<ObjectId>,
146+}
147+
136148 /// What a landing did.
137149 #[derive(Clone, Debug, PartialEq, Eq)]
138150 pub struct LandReport {
139151 /// The branch.
140152 pub branch: String,
141153 /// Its head before the landing.
142- pub previous: Option<ObjectId>,
154+ pub head_before: Option<ObjectId>,
143155 /// How it ended.
144156 pub landed: Landed,
145157 /// The op log operation that moved the branch, if it moved.
146158 pub operation: Option<u64>,
159+ /// Where each changeset of the stack went, oldest first; when the
160+ /// branch did not move, none went anywhere.
161+ pub placed: Vec<Placed>,
162+ /// The paths both sides changed, merged line by line or by kind, over
163+ /// the whole stack, sorted.
164+ pub merged_paths: Vec<Vec<u8>>,
165+ /// The paths of the working copy that the landing then wrote or
166+ /// removed, sorted; none for [`land_change`](crate::land_change).
167+ pub updated_paths: Vec<Vec<u8>>,
147168 }
148169
149170 impl LandReport {
@@ -151,11 +172,37 @@
151172 pub fn head(&self) -> Option<ObjectId> {
152173 match &self.landed {
153174 Landed::FastForward(id) | Landed::Rebased(id) => Some(*id),
154- _ => self.previous,
175+ _ => self.head_before,
155176 }
156177 }
157178 }
158179
180+/// What `update` did, with the outcome in [`UpdateReport::updated`].
181+#[derive(Clone, Debug, PartialEq, Eq)]
182+pub struct UpdateReport {
183+ /// The branch the workspace updates from.
184+ pub branch: String,
185+ /// Its head, which an update reads and never moves; `None` when the
186+ /// branch does not exist.
187+ pub head: Option<ObjectId>,
188+ /// How the update ended.
189+ pub updated: Updated,
190+ /// The workspace's base before the update.
191+ pub base_before: Option<ObjectId>,
192+ /// Its base after it.
193+ pub base: Option<ObjectId>,
194+ /// Where each of the workspace's own changesets went, oldest first: the
195+ /// rebased changeset on top of the head, or `None` from the one that
196+ /// conflicts on.
197+ pub placed: Vec<Placed>,
198+ /// The paths both sides changed, merged line by line or by kind, over
199+ /// the changesets rebased, sorted.
200+ pub merged_paths: Vec<Vec<u8>>,
201+ /// The paths of the working copy that the update wrote or removed,
202+ /// sorted.
203+ pub updated_paths: Vec<Vec<u8>>,
204+}
205+
159206 /// What `update` did.
160207 #[derive(Clone, Debug, PartialEq, Eq)]
161208 pub enum Updated {
@@ -203,19 +250,57 @@
203250 Nothing,
204251 AlreadyApplied {
205252 head: ObjectId,
253+ placed: Vec<Placed>,
206254 },
207255 Moved {
208256 tip: ObjectId,
209257 rebased: bool,
210258 tip_root: ObjectId,
211259 plan: Plan,
260+ placed: Vec<Placed>,
261+ merged_paths: Vec<Vec<u8>>,
212262 },
213263 Conflicts {
214264 change: ObjectId,
215265 conflicts: Vec<Conflict>,
266+ stack: Vec<ObjectId>,
216267 },
217268 }
218269
270+/// How many changesets an op log description names, at most.
271+const DESCRIBED: usize = 8;
272+
273+/// What the op log says a landing did, after `prefix`: how it went, each
274+/// changeset and the one it became (short ids), and how many paths were
275+/// merged, as in `rebased c57e1007e4f3 -> 3afaed346293 (1 path merged)`.
276+pub(crate) fn describe_landing(
277+ prefix: &str,
278+ outcome: &str,
279+ placed: &[Placed],
280+ merged_paths: usize,
281+) -> String {
282+ let mut moves: Vec<String> = placed
283+ .iter()
284+ .take(DESCRIBED)
285+ .map(|placed| match placed.to {
286+ Some(to) => format!("{} -> {}", placed.from.short(), to.short()),
287+ None => format!("{} already applied", placed.from.short()),
288+ })
289+ .collect();
290+ if placed.len() > DESCRIBED {
291+ moves.push(format!("and {} more", placed.len() - DESCRIBED));
292+ }
293+ let moves = match placed.len() {
294+ 1 => moves.concat(),
295+ n => format!("{n} changesets: {}", moves.join(", ")),
296+ };
297+ let merged = match merged_paths {
298+ 1 => "1 path".to_owned(),
299+ n => format!("{n} paths"),
300+ };
301+ format!("{prefix}: {outcome} {moves} ({merged} merged)")
302+}
303+
219304 impl<'r> Workspace<'r> {
220305 /// The directory that holds every workspace's state.
221306 pub fn states_dir(repo: &Repo) -> PathBuf {
@@ -318,7 +403,7 @@
318403 rebase: None,
319404 };
320405 let written = workspace.write(&root, &mut state, &plan, EMPTY_TREE, to)?;
321- Ok((workspace, written))
406+ Ok((workspace, written.len()))
322407 }
323408
324409 /// Opens the workspace named `name`, at the directory its state
@@ -482,7 +567,7 @@
482567 /// Writes a planned checkout from tree `from` to tree `to` and saves
483568 /// `state`. The state is saved first with the checkout marked as
484569 /// unfinished, so that a command interrupted half way through is
485- /// finished by the next one.
570+ /// finished by the next one. Returns the paths written or removed.
486571 fn write(
487572 &self,
488573 root: &Root,
@@ -490,17 +575,17 @@
490575 plan: &Plan,
491576 from: ObjectId,
492577 to: ObjectId,
493- ) -> Result<usize, Error> {
578+ ) -> Result<Vec<Vec<u8>>, Error> {
494579 if plan.len() == 0 {
495580 state.save(&self.state_dir)?;
496- return Ok(0);
581+ return Ok(Vec::new());
497582 }
498583 state.checkout = Some(Checkout { from, to });
499584 state.save(&self.state_dir)?;
500- let written = checkout::apply(self.store(), root, plan)?;
585+ checkout::apply(self.store(), root, plan)?;
501586 state.checkout = None;
502587 state.save(&self.state_dir)?;
503- Ok(written)
588+ Ok(plan.paths())
504589 }
505590
506591 /// Scans the working copy, saves the new stat cache, and compares it
@@ -755,6 +840,7 @@
755840 index,
756841 onto,
757842 conflicts,
843+ ..
758844 } => {
759845 let change = pending[index];
760846 self.stop_on_conflicts(
@@ -773,7 +859,8 @@
773859
774860 /// Writes the working copy for a rebase stopped by conflicts and
775861 /// records the rebase: `onto`'s tree, with `change`'s clean paths and
776- /// conflict markers, as the base `onto`.
862+ /// conflict markers, as the base `onto`. Returns the paths written or
863+ /// removed.
777864 #[allow(clippy::too_many_arguments)]
778865 fn stop_on_conflicts(
779866 &self,
@@ -784,7 +871,7 @@
784871 change: ObjectId,
785872 pending: &[ObjectId],
786873 conflicts: &[Conflict],
787- ) -> Result<(), Error> {
874+ ) -> Result<Vec<Vec<u8>>, Error> {
788875 let store = self.store();
789876 let subject = subject(&read_changeset(store, change)?.message);
790877 let ours = format!("{} ({})", state.branch, onto.short());
@@ -798,19 +885,20 @@
798885 pending: pending.to_vec(),
799886 conflicts: recorded,
800887 });
801- self.write(root, state, &plan, from, tree)?;
802- Ok(())
888+ self.write(root, state, &plan, from, tree)
803889 }
804890
805891 /// Lands the workspace's own changesets on `onto` (by default the
806892 /// branch it tracks), in one op log transaction: the head is read, the
807893 /// changesets are landed on it with the engine (fast-forward or
808- /// rebase), and the branch moves with a compare-and-swap. With
809- /// conflicts the branch does not move and nothing in the workspace
810- /// changes. Once the branch has moved, the working copy is brought from
811- /// the base's tree to the landed tree, writing only the difference, and
812- /// the landed changeset becomes the base. Refused with uncommitted
813- /// changes or a rebase in progress.
894+ /// rebase), and the branch moves with a compare-and-swap. The operation
895+ /// says how it went, which changeset became which, and how many paths
896+ /// were merged (see [`LandReport`]). With conflicts the branch does not
897+ /// move and nothing in the workspace changes. Once the branch has
898+ /// moved, the working copy is brought from the base's tree to the
899+ /// landed tree, writing only the difference, and the landed changeset
900+ /// becomes the base. Refused with uncommitted changes or a rebase in
901+ /// progress.
814902 pub fn land(
815903 &self,
816904 onto: Option<&str>,
@@ -826,120 +914,136 @@
826914 let store = self.store();
827915 let base_root = root_of(store, state.base)?;
828916 let signature = committer.now();
829- let mut previous = None;
917+ let mut head_before = None;
830918 let mut decision = None;
831- let description = format!("land workspace {} on {branch}", self.name);
832- let result = store.transact(
833- agent,
834- &description,
835- |refs| -> Result<Vec<RefUpdate>, Abort> {
836- let head = refs.get(&branch);
837- previous = head;
838- let stack = find_stack(store, head, state.base, state.upstream)?;
839- if stack.is_empty() {
840- decision = Some(Decision::Nothing);
841- return Err(Abort::Stop);
919+ let prefix = format!("land workspace {} on {branch}", self.name);
920+ let result = store.transact_with(agent, |refs| -> Result<_, Abort> {
921+ let head = refs.get(&branch);
922+ head_before = head;
923+ let stack = find_stack(store, head, state.base, state.upstream)?;
924+ if stack.is_empty() {
925+ decision = Some(Decision::Nothing);
926+ return Err(Abort::Stop);
927+ }
928+ match replay(
929+ store,
930+ &branch,
931+ head,
932+ &stack,
933+ &signature,
934+ First::MustBeOnBranch,
935+ )? {
936+ Replayed::Done { tip, placed, .. } if Some(tip) == head => {
937+ decision = Some(Decision::AlreadyApplied { head: tip, placed });
938+ Err(Abort::Stop)
842939 }
843- match replay(
844- store,
845- &branch,
846- head,
847- &stack,
848- &signature,
849- First::MustBeOnBranch,
850- )? {
851- Replayed::Done { tip, .. } if Some(tip) == head => {
852- decision = Some(Decision::AlreadyApplied { head: tip });
853- Err(Abort::Stop)
854- }
855- Replayed::Done { tip, rebased } => {
856- // Check the working copy can follow before the branch
857- // moves.
858- let tip_root = root_of(store, Some(tip))?;
859- let plan = checkout::plan(
860- store,
861- &root,
862- state.fs,
863- base_root,
864- tip_root,
865- Mode::Checked,
866- )?;
867- decision = Some(Decision::Moved {
868- tip,
869- rebased,
870- tip_root,
871- plan,
872- });
873- Ok(vec![RefUpdate::new(branch.clone(), head, Some(tip))])
874- }
875- Replayed::Stopped {
876- index, conflicts, ..
877- } => {
878- decision = Some(Decision::Conflicts {
879- change: stack[index],
880- conflicts,
881- });
882- Err(Abort::Stop)
883- }
940+ Replayed::Done {
941+ tip,
942+ rebased,
943+ placed,
944+ merged_paths,
945+ } => {
946+ // Check the working copy can follow before the branch
947+ // moves.
948+ let tip_root = root_of(store, Some(tip))?;
949+ let plan =
950+ checkout::plan(store, &root, state.fs, base_root, tip_root, Mode::Checked)?;
951+ let outcome = if rebased { "rebased" } else { "fast-forward" };
952+ let description =
953+ describe_landing(&prefix, outcome, &placed, merged_paths.len());
954+ decision = Some(Decision::Moved {
955+ tip,
956+ rebased,
957+ tip_root,
958+ plan,
959+ placed,
960+ merged_paths,
961+ });
962+ let updates = vec![RefUpdate::new(branch.clone(), head, Some(tip))];
963+ Ok((updates, description))
884964 }
885- },
886- );
965+ Replayed::Stopped {
966+ index, conflicts, ..
967+ } => {
968+ decision = Some(Decision::Conflicts {
969+ change: stack[index],
970+ conflicts,
971+ stack,
972+ });
973+ Err(Abort::Stop)
974+ }
975+ }
976+ });
887977 let operation = match result {
888978 Ok(op) => Some(op.seq),
889979 Err(TransactError::Aborted(Abort::Stop)) => None,
890980 Err(TransactError::Aborted(Abort::Failed(err))) => return Err(err),
891981 Err(TransactError::Store(err)) => return Err(err.into()),
892982 };
893- let landed = match decision {
983+ let mut report = LandReport {
984+ branch,
985+ head_before,
986+ landed: Landed::Nothing,
987+ operation,
988+ placed: Vec::new(),
989+ merged_paths: Vec::new(),
990+ updated_paths: Vec::new(),
991+ };
992+ match decision {
894993 Some(Decision::Moved {
895994 tip,
896995 rebased,
897996 tip_root,
898997 plan,
998+ placed,
999+ merged_paths,
8991000 }) => {
9001001 state.base = Some(tip);
9011002 state.upstream = Some(tip);
902- self.write(&root, &mut state, &plan, base_root, tip_root)?;
903- if rebased {
1003+ report.updated_paths = self.write(&root, &mut state, &plan, base_root, tip_root)?;
1004+ report.landed = if rebased {
9041005 Landed::Rebased(tip)
9051006 } else {
9061007 Landed::FastForward(tip)
907- }
1008+ };
1009+ report.placed = placed;
1010+ report.merged_paths = merged_paths;
9081011 }
909- Some(Decision::AlreadyApplied { head }) => {
1012+ Some(Decision::AlreadyApplied { head, placed }) => {
9101013 // The branch has it all: the workspace moves to the head.
911- self.move_to(&root, &mut state, base_root, head)?;
912- Landed::AlreadyApplied
1014+ report.updated_paths = self.move_to(&root, &mut state, base_root, head)?;
1015+ report.landed = Landed::AlreadyApplied;
1016+ report.placed = placed;
9131017 }
914- Some(Decision::Conflicts { change, conflicts }) => {
915- Landed::Conflicts { change, conflicts }
1018+ Some(Decision::Conflicts {
1019+ change,
1020+ conflicts,
1021+ stack,
1022+ }) => {
1023+ report.landed = Landed::Conflicts { change, conflicts };
1024+ report.placed = unplaced(&stack);
9161025 }
917- Some(Decision::Nothing) | None => Landed::Nothing,
918- };
919- Ok(LandReport {
920- branch,
921- previous,
922- landed,
923- operation,
924- })
1026+ Some(Decision::Nothing) | None => {}
1027+ }
1028+ Ok(report)
9251029 }
9261030
9271031 /// Brings the working copy from tree `from` to `head`'s tree and makes
928- /// `head` the base and the upstream.
1032+ /// `head` the base and the upstream. Returns the paths written or
1033+ /// removed.
9291034 fn move_to(
9301035 &self,
9311036 root: &Root,
9321037 state: &mut State,
9331038 from: ObjectId,
9341039 head: ObjectId,
935- ) -> Result<(), Error> {
1040+ ) -> Result<Vec<Vec<u8>>, Error> {
9361041 let store = self.store();
9371042 let to = root_of(store, Some(head))?;
9381043 let plan = checkout::plan(store, root, state.fs, from, to, Mode::Checked)?;
9391044 state.base = Some(head);
9401045 state.upstream = Some(head);
941- self.write(root, state, &plan, from, to)?;
942- Ok(())
1046+ self.write(root, state, &plan, from, to)
9431047 }
9441048
9451049 /// Brings the workspace onto the current head of its branch. Without
@@ -951,16 +1055,27 @@
9511055 /// markers; other conflicts keep the head's version and are reported. A
9521056 /// rebase is then in progress until `braid commit`. Refused with
9531057 /// uncommitted changes or a rebase in progress.
954- pub fn update(&self, committer: &Identity) -> Result<Updated, Error> {
1058+ pub fn update(&self, committer: &Identity) -> Result<UpdateReport, Error> {
9551059 let (_lock, mut state, root) = self.begin()?;
9561060 if state.rebase.is_some() {
9571061 return Err(Error::RebaseInProgress);
9581062 }
9591063 self.require_clean(&root, &state)?;
9601064 let store = self.store();
1065+ let mut report = UpdateReport {
1066+ branch: state.branch.clone(),
1067+ head: None,
1068+ updated: Updated::UpToDate,
1069+ base_before: state.base,
1070+ base: state.base,
1071+ placed: Vec::new(),
1072+ merged_paths: Vec::new(),
1073+ updated_paths: Vec::new(),
1074+ };
9611075 let Some(head) = store.refs()?.get(&state.branch) else {
962- return Ok(Updated::UpToDate);
1076+ return Ok(report);
9631077 };
1078+ report.head = Some(head);
9641079 let base_root = root_of(store, state.base)?;
9651080 let stack = find_stack(store, Some(head), state.base, state.upstream)?;
9661081 if stack.is_empty() {
@@ -969,10 +1084,12 @@
9691084 state.upstream = Some(head);
9701085 state.save(&self.state_dir)?;
9711086 }
972- return Ok(Updated::UpToDate);
1087+ return Ok(report);
9731088 }
974- self.move_to(&root, &mut state, base_root, head)?;
975- return Ok(Updated::Moved { head });
1089+ report.updated_paths = self.move_to(&root, &mut state, base_root, head)?;
1090+ report.updated = Updated::Moved { head };
1091+ report.base = state.base;
1092+ return Ok(report);
9761093 }
9771094 let signature = committer.now();
9781095 match replay(
@@ -983,26 +1100,35 @@
9831100 &signature,
9841101 First::Anywhere,
9851102 )? {
986- Replayed::Done { tip, .. } if tip == head => {
987- self.move_to(&root, &mut state, base_root, head)?;
988- Ok(Updated::Moved { head })
1103+ Replayed::Done { tip, placed, .. } if tip == head => {
1104+ report.updated_paths = self.move_to(&root, &mut state, base_root, head)?;
1105+ report.updated = Updated::Moved { head };
1106+ report.placed = placed;
9891107 }
990- Replayed::Done { tip, .. } => {
1108+ Replayed::Done {
1109+ tip,
1110+ placed,
1111+ merged_paths,
1112+ ..
1113+ } => {
9911114 let to = root_of(store, Some(tip))?;
9921115 let plan = checkout::plan(store, &root, state.fs, base_root, to, Mode::Checked)?;
9931116 state.base = Some(tip);
9941117 state.upstream = Some(head);
995- self.write(&root, &mut state, &plan, base_root, to)?;
996- Ok(Updated::Rebased { head, tip })
1118+ report.updated_paths = self.write(&root, &mut state, &plan, base_root, to)?;
1119+ report.updated = Updated::Rebased { head, tip };
1120+ report.placed = placed;
1121+ report.merged_paths = merged_paths;
9971122 }
9981123 Replayed::Stopped {
9991124 index,
10001125 onto,
10011126 conflicts,
1127+ mut placed,
10021128 } => {
10031129 let change = stack[index];
10041130 state.upstream = Some(head);
1005- self.stop_on_conflicts(
1131+ report.updated_paths = self.stop_on_conflicts(
10061132 &root,
10071133 &mut state,
10081134 base_root,
@@ -1011,13 +1137,17 @@
10111137 &stack[index + 1..],
10121138 &conflicts,
10131139 )?;
1014- Ok(Updated::Conflicts {
1140+ placed.extend(unplaced(&stack[index..]));
1141+ report.updated = Updated::Conflicts {
10151142 head,
10161143 change,
10171144 conflicts,
1018- })
1145+ };
1146+ report.placed = placed;
10191147 }
10201148 }
1149+ report.base = state.base;
1150+ Ok(report)
10211151 }
10221152
10231153 /// Marks conflicts of the rebase in progress resolved: those at each of
@@ -1135,6 +1265,14 @@
11351265 Ok(has_markers(&content))
11361266 }
11371267
1268+/// Changesets that went nowhere.
1269+fn unplaced(stack: &[ObjectId]) -> Vec<Placed> {
1270+ stack
1271+ .iter()
1272+ .map(|&from| Placed { from, to: None })
1273+ .collect()
1274+}
1275+
11381276 /// The first non-empty line of a message.
11391277 fn subject(message: &[u8]) -> String {
11401278 String::from_utf8_lossy(message)
@@ -1207,3 +1345,60 @@
12071345 stack.reverse();
12081346 Ok(stack)
12091347 }
1348+
1349+#[cfg(test)]
1350+mod tests {
1351+ use super::*;
1352+ use braid_format::Kind;
1353+
1354+ fn id(n: u8) -> ObjectId {
1355+ ObjectId::hash(Kind::Changeset, &[n])
1356+ }
1357+
1358+ #[test]
1359+ fn landing_descriptions() {
1360+ let one = [Placed {
1361+ from: id(1),
1362+ to: Some(id(2)),
1363+ }];
1364+ assert_eq!(
1365+ describe_landing("land workspace b on main", "rebased", &one, 1),
1366+ format!(
1367+ "land workspace b on main: rebased {} -> {} (1 path merged)",
1368+ id(1).short(),
1369+ id(2).short()
1370+ )
1371+ );
1372+ let two = [
1373+ Placed {
1374+ from: id(1),
1375+ to: None,
1376+ },
1377+ Placed {
1378+ from: id(3),
1379+ to: Some(id(4)),
1380+ },
1381+ ];
1382+ assert_eq!(
1383+ describe_landing("land", "rebased", &two, 0),
1384+ format!(
1385+ "land: rebased 2 changesets: {} already applied, {} -> {} (0 paths merged)",
1386+ id(1).short(),
1387+ id(3).short(),
1388+ id(4).short()
1389+ )
1390+ );
1391+ let many: Vec<Placed> = (0..20)
1392+ .map(|n| Placed {
1393+ from: id(n),
1394+ to: Some(id(n)),
1395+ })
1396+ .collect();
1397+ let text = describe_landing("land", "fast-forward", &many, 2);
1398+ assert!(
1399+ text.starts_with("land: fast-forward 20 changesets: "),
1400+ "{text}"
1401+ );
1402+ assert!(text.ends_with(", and 12 more (2 paths merged)"), "{text}");
1403+ }
1404+}
modified crates/wc/tests/hostile.rs +4 −1
@@ -42,7 +42,10 @@
4242 ],
4343 );
4444 f.set_branch("main", second);
45- assert_eq!(ws.update(&ada()).unwrap(), Updated::Moved { head: second });
45+ assert_eq!(
46+ ws.update(&ada()).unwrap().updated,
47+ Updated::Moved { head: second }
48+ );
4649 assert!(
4750 listing(outside.path()).is_empty(),
4851 "wrote outside the workspace"
modified crates/wc/tests/workspaces.rs +19 −3
@@ -9,7 +9,7 @@
99
1010 use std::fs;
1111
12-use braid_format::ChangeOp;
12+use braid_format::{ChangeOp, ObjectId};
1313 use braid_wc::{ChangeKind, CommitRequest, Error, Landed, RebaseProgress, Updated, Workspace};
1414 use common::{Fixture, ada};
1515
@@ -55,7 +55,10 @@
5555
5656 // Once the file is out of the way, the update goes through.
5757 fs::remove_file(dir.join("d/junk")).unwrap();
58- assert_eq!(ws.update(&ada()).unwrap(), Updated::Moved { head: second });
58+ assert_eq!(
59+ ws.update(&ada()).unwrap().updated,
60+ Updated::Moved { head: second }
61+ );
5962 assert_eq!(fs::read(dir.join("d")).unwrap(), b"now a file");
6063 }
6164
@@ -124,9 +127,10 @@
124127 let theirs = f.commit(&[seed], vec![("x", f.file("1\ntheirs\n3\n"))]);
125128 f.set_branch("main", theirs);
126129
130+ let report = ws.update(&ada()).unwrap();
127131 let Updated::Conflicts {
128132 change, conflicts, ..
129- } = ws.update(&ada()).unwrap()
133+ } = report.updated
130134 else {
131135 panic!("expected conflicts");
132136 };
@@ -135,6 +139,18 @@
135139 let state = ws.state().unwrap();
136140 let rebase = state.rebase.unwrap();
137141 assert_eq!(rebase.pending, [third]);
142+ // The first changeset went onto main's head, the others nowhere yet;
143+ // the working copy got main's x with markers, and lost z for now.
144+ assert_eq!(report.head, Some(theirs));
145+ assert_eq!(report.base_before, Some(third));
146+ assert_eq!(report.base, Some(rebase.onto));
147+ let placed: Vec<(ObjectId, Option<ObjectId>)> =
148+ report.placed.iter().map(|p| (p.from, p.to)).collect();
149+ assert_eq!(
150+ placed,
151+ [(first, Some(rebase.onto)), (second, None), (third, None)]
152+ );
153+ assert_eq!(report.updated_paths, [b"x".to_vec(), b"z".to_vec()]);
138154 // The working copy has the first changeset rebased, and the markers;
139155 // the third one waits.
140156 assert_eq!(fs::read(dir.join("y")).unwrap(), b"y, ours\n");