Elffuss BraidHub

utopia-ia/elffuss-braid public

44bd6adbea21 · 38.5 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Workspace commands: `workspace`, `status`, `commit`, `land`, `update`,
5//! `resolve`, `track` and `change create`.
6//!
7//! Commands that report conflicts exit with status 2, so that an agent can
8//! tell them from failures (status 1) without parsing anything.
9
10use std::ffi::{OsStr, OsString};
11use std::io::{self, Read, Write};
12use std::path::{Path, PathBuf};
13use std::process::ExitCode;
14
15use anyhow::{Context, Result, bail};
16use braid_engine::{Conflict, ConflictKind, HunkSide};
17use braid_format::{ChangeOp, EntryKind, ObjectId};
18use braid_repo::{Location, Repo};
19use braid_wc::{
20 BEHIND_LIMIT, Blocker, ChangeRequest, CommitRequest, Expect, Identity, LandReport, Landed,
21 Placed, RebaseProgress, UpdateReport, Updated, Workspace,
22};
23use clap::{Args, Subcommand};
24use serde_json::{Value, json};
25
26use crate::{Cli, change_json, open_repo, print_json, resolve_changeset};
27
28/// Exit status of a command that stopped on conflicts.
29const CONFLICTS: u8 = 2;
30
31/// The fields of the report `land`, `update` and `change create --land`
32/// print with `--json`, for their long help.
33macro_rules! report_fields {
34 () => {
35 "With --json, land and update print one object with these fields;
36change 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
67Ids in JSON are full; text output shows their first 12 hex digits."
68 };
69}
70
71/// The long help of `status`.
72pub(crate) const STATUS_HELP: &str = "Show how the workspace differs from its base and its branch.
73
74With --json, status prints one object:
75
76 workspace the workspace's name
77 path its directory
78 branch the branch it lands on and updates from
79 base the changeset its working copy is at, or null
80 head the branch's head, or null when the branch does not exist
81 behind whether the branch has changesets the workspace does not
82 behind_by how many: the changesets from the branch's head down to
83 the one the workspace's own start from, along first
84 parents; null when there are more than 5000
85 unlanded the workspace's own changesets that the branch does not
86 have, oldest first; while a rebase is in progress, also
87 the changeset being rebased and those waiting after it
88 clean whether no change would be committed
89 changes what a commit would record, by path: kind (added,
90 modified, deleted or typechange), op, and blob and size
91 added, modified, deleted, typechanged
92 the paths of changes, by kind
93 needs_track new files the secrets guard holds back until `braid
94 track`: names like .env*, *.pem or id_*, or files larger
95 than 1 MiB
96 ready_to_commit whether `braid commit` would record a changeset now:
97 there are changes, or a rebase to finish, and nothing
98 blocks it
99 blocking why `braid commit` would refuse, each {reason, path,
100 message}: markers (conflict markers remain in the file),
101 unresolved (a conflict that is not about content, not
102 marked resolved with `braid resolve`), both with the
103 conflict's kind, or needs_track; commit refuses with the
104 same list, unless --force
105 rebase null, or the rebase in progress: change (the changeset
106 being rebased), onto, pending (those waiting after it),
107 and conflicts, each {path, kind, markers, markers_remain,
108 resolved}
109
110Ids in JSON are full; text output shows their first 12 hex digits.";
111
112/// The long help of `land`.
113pub(crate) const LAND_HELP: &str = concat!(
114 "Land the workspace's changesets on its branch, in one step: a
115fast-forward when they were built on the head, a rebase onto it otherwise.
116The working copy then follows the landed tree. On conflicts the branch does
117not move and the exit status is 2; `braid update` brings the conflicts into
118the working copy.
119
120",
121 report_fields!()
122);
123
124/// The long help of `update`.
125pub(crate) const UPDATE_HELP: &str = concat!(
126 "Bring the workspace onto its branch's head, rebasing its own changesets
127without moving the branch. On conflicts the exit status is 2: the working
128copy gets the head's tree with the clean paths and conflict markers, and a
129rebase is in progress until `braid commit`.
130
131",
132 report_fields!()
133);
134
135/// The long help of `change create`.
136pub(crate) const CREATE_HELP: &str = concat!(
137 "Make a changeset on a base without a working copy, and optionally land
138it (exit status 2 on conflicts). Prints JSON whether or not --json is
139given: change, the new changeset's id; base; and land, the report of the
140landing, or null.
141
142",
143 report_fields!()
144);
145
146#[derive(Debug, Subcommand)]
147pub(crate) enum WorkspaceAction {
148 /// Create a workspace and write its files.
149 Add {
150 /// The workspace's name: letters, digits, '.', '_' or '-'.
151 name: String,
152 /// Its directory, which must not exist or be empty (default:
153 /// ./<name>).
154 path: Option<PathBuf>,
155 /// The changeset to start at: a ref, an id or a short id (default:
156 /// the head of the tracked branch, or nothing if it does not exist
157 /// yet).
158 #[arg(long, value_name = "REV")]
159 at: Option<String>,
160 /// The branch the workspace lands on and updates from.
161 #[arg(long, value_name = "BRANCH", default_value = "main")]
162 track: String,
163 },
164 /// List the repository's workspaces.
165 List,
166 /// Remove a workspace: its directory and its state.
167 Remove {
168 /// The workspace's name.
169 name: String,
170 /// Remove it even with uncommitted changes, unlanded changesets or
171 /// a rebase in progress.
172 #[arg(long)]
173 force: bool,
174 },
175}
176
177#[derive(Debug, Args)]
178pub(crate) struct IdentityArgs {
179 /// Who records changesets, as "Name <email>" (default: BRAID_AUTHOR,
180 /// then name and email in .braid/config).
181 #[arg(long, env = "BRAID_AUTHOR", value_name = "IDENTITY")]
182 author: Option<String>,
183}
184
185#[derive(Debug, Args)]
186pub(crate) struct CommitArgs {
187 /// The message. While a rebase is in progress it may be left out, and
188 /// the rebased changeset's own is kept; one given replaces it.
189 #[arg(short, long)]
190 message: Option<String>,
191 /// Commit even if conflict markers remain or conflicts are not marked
192 /// resolved; new files waiting for `braid track` stay out.
193 #[arg(long)]
194 force: bool,
195 #[command(flatten)]
196 identity: IdentityArgs,
197 /// Commit only these files and directories (default: everything).
198 paths: Vec<PathBuf>,
199}
200
201#[derive(Debug, Args)]
202pub(crate) struct LandArgs {
203 /// The branch to land on (default: the workspace's branch).
204 #[arg(long, value_name = "BRANCH")]
205 onto: Option<String>,
206 #[command(flatten)]
207 identity: IdentityArgs,
208}
209
210#[derive(Debug, Subcommand)]
211pub(crate) enum ChangeAction {
212 /// Make a changeset on a base without a working copy, and optionally
213 /// land it (exit status 2 on conflicts). Prints the ids as JSON.
214 #[command(long_about = CREATE_HELP)]
215 Create(CreateArgs),
216}
217
218#[derive(Debug, Args)]
219pub(crate) struct CreateArgs {
220 /// The changeset to build on: a ref, an id, a short id (6 hex digits or
221 /// more), or "none" for a first changeset.
222 #[arg(long, value_name = "REV")]
223 base: String,
224 /// Set a file: PATH=@FILE takes the content of FILE, PATH=@- reads
225 /// standard input. Repeat for several.
226 #[arg(long = "set", value_name = "PATH=@FILE")]
227 sets: Vec<OsString>,
228 /// Delete a file. Repeat for several.
229 #[arg(long = "delete", value_name = "PATH")]
230 deletes: Vec<OsString>,
231 /// Require the base to hold this blob at PATH, or nothing ("absent"),
232 /// before anything is made. Repeat for several.
233 #[arg(long = "expect", value_name = "PATH=ID|absent")]
234 expects: Vec<OsString>,
235 /// The message.
236 #[arg(short, long)]
237 message: String,
238 /// Land the changeset on this branch.
239 #[arg(long, value_name = "BRANCH")]
240 land: Option<String>,
241 #[command(flatten)]
242 identity: IdentityArgs,
243}
244
245/// The repository and the workspace a command acts on.
246struct Target {
247 repo: Repo,
248 name: String,
249 /// Where its `.braid` file was found, when it was found by looking.
250 dir: Option<PathBuf>,
251}
252
253impl Target {
254 /// The workspace named by `--workspace`, or the one containing the
255 /// current directory.
256 fn find(cli: &Cli) -> Result<Target> {
257 if let Some(name) = &cli.workspace {
258 return Ok(Target {
259 repo: open_repo(cli)?,
260 name: name.clone(),
261 dir: None,
262 });
263 }
264 let cwd = std::env::current_dir()?;
265 match braid_repo::locate(&cwd)? {
266 Location::Workspace { dir, link } => {
267 let repo = match &cli.repo {
268 Some(root) => Repo::open(root)?,
269 None => Repo::open(&link.repository)?,
270 };
271 Ok(Target {
272 repo,
273 name: link.name,
274 dir: Some(dir),
275 })
276 }
277 Location::Root(_) => Err(braid_wc::Error::NotAWorkspace.into()),
278 }
279 }
280
281 fn open(&self) -> Result<Workspace<'_>> {
282 Ok(match &self.dir {
283 Some(dir) => Workspace::at(&self.repo, &self.name, dir)?,
284 None => Workspace::open(&self.repo, &self.name)?,
285 })
286 }
287}
288
289fn identity(args: &IdentityArgs, repo: &Repo) -> Result<Identity> {
290 Ok(Identity::resolve(args.author.as_deref(), repo)?)
291}
292
293/// Paths given on the command line, as paths of the workspace.
294fn workspace_paths(workspace: &Workspace<'_>, given: &[PathBuf]) -> Result<Vec<Vec<u8>>> {
295 let root = std::fs::canonicalize(workspace.dir())
296 .with_context(|| format!("cannot open {}", workspace.dir().display()))?;
297 let cwd = std::fs::canonicalize(std::env::current_dir()?)?;
298 given
299 .iter()
300 .map(|path| Ok(braid_wc::workspace_path(&root, &cwd, path)?))
301 .collect()
302}
303
304fn show(path: &[u8]) -> String {
305 String::from_utf8_lossy(path).into_owned()
306}
307
308/// `1 path`, `3 paths`.
309fn count(n: usize, noun: &str) -> String {
310 if n == 1 {
311 format!("1 {noun}")
312 } else {
313 format!("{n} {noun}s")
314 }
315}
316
317fn hex(id: Option<ObjectId>) -> Value {
318 id.map_or(Value::Null, |id| Value::String(id.to_hex()))
319}
320
321fn short(id: Option<ObjectId>) -> String {
322 id.map_or_else(|| "(none)".to_owned(), |id| id.short())
323}
324
325pub(crate) fn workspace(cli: &Cli, action: &WorkspaceAction) -> Result<ExitCode> {
326 match action {
327 WorkspaceAction::Add {
328 name,
329 path,
330 at,
331 track,
332 } => {
333 let repo = open_repo(cli)?;
334 let at = match at {
335 Some(revision) => Some(resolve_changeset(&repo, revision)?),
336 None => repo.store().refs()?.get(track),
337 };
338 let dir = match path {
339 Some(path) => path.clone(),
340 None => std::env::current_dir()?.join(name),
341 };
342 let (workspace, files) = Workspace::create(&repo, name, &dir, at, track)?;
343 if cli.json {
344 print_json(&json!({
345 "name": workspace.name(),
346 "path": workspace.dir().to_string_lossy(),
347 "branch": track,
348 "base": hex(at),
349 "files": files,
350 }))?;
351 } else {
352 println!(
353 "Created workspace {} in {} on {track} at {}, {}",
354 workspace.name(),
355 workspace.dir().display(),
356 short(at),
357 count(files, "file")
358 );
359 }
360 }
361 WorkspaceAction::List => {
362 let repo = open_repo(cli)?;
363 let all = Workspace::list(&repo)?;
364 if cli.json {
365 let items: Vec<Value> = all
366 .iter()
367 .map(|(name, state)| {
368 json!({
369 "name": name,
370 "path": state.path.to_string_lossy(),
371 "branch": state.branch,
372 "base": hex(state.base),
373 "rebase": state.rebase.is_some(),
374 "present": state.path.join(braid_repo::DIR).is_file(),
375 })
376 })
377 .collect();
378 print_json(&Value::Array(items))?;
379 } else {
380 for (name, state) in &all {
381 println!(
382 "{name} {} {} {}{}",
383 state.branch,
384 short(state.base),
385 state.path.display(),
386 if state.rebase.is_some() {
387 " (rebase in progress)"
388 } else {
389 ""
390 }
391 );
392 }
393 }
394 }
395 WorkspaceAction::Remove { name, force } => {
396 let repo = open_repo(cli)?;
397 Workspace::remove(&repo, name, *force)?;
398 if cli.json {
399 print_json(&json!({ "name": name, "removed": true }))?;
400 } else {
401 println!("Removed workspace {name}");
402 }
403 }
404 }
405 Ok(ExitCode::SUCCESS)
406}
407
408pub(crate) fn status(cli: &Cli) -> Result<ExitCode> {
409 let target = Target::find(cli)?;
410 let workspace = target.open()?;
411 let report = workspace.status()?;
412 let state = &report.state;
413 let status = &report.status;
414 if cli.json {
415 let by_kind = |kind: braid_wc::ChangeKind| -> Vec<String> {
416 status
417 .changes
418 .iter()
419 .filter(|change| change.kind == kind)
420 .map(|change| show(&change.path))
421 .collect()
422 };
423 let rebase = state.rebase.as_ref().map(|rebase| {
424 json!({
425 "change": rebase.change.to_hex(),
426 "onto": rebase.onto.to_hex(),
427 "pending": rebase.pending.iter().map(ObjectId::to_hex).collect::<Vec<_>>(),
428 "conflicts": report.conflicts.iter().map(|(conflict, remain)| json!({
429 "path": show(&conflict.path),
430 "kind": conflict.code,
431 "markers": conflict.markers,
432 "markers_remain": remain,
433 "resolved": conflict.resolved,
434 })).collect::<Vec<_>>(),
435 })
436 });
437 print_json(&json!({
438 "workspace": workspace.name(),
439 "path": workspace.dir().to_string_lossy(),
440 "branch": state.branch,
441 "base": hex(state.base),
442 "head": hex(report.head),
443 "behind": report.behind(),
444 "behind_by": report.behind_by,
445 "clean": status.is_clean(),
446 "unlanded": report.unlanded.iter().map(ObjectId::to_hex).collect::<Vec<_>>(),
447 "changes": status.changes.iter().map(|change| {
448 let mut value = change_json(&braid_format::Change {
449 path: change.path.clone(),
450 op: change.op.clone(),
451 });
452 value["kind"] = Value::String(change.kind.name().to_owned());
453 value
454 }).collect::<Vec<_>>(),
455 "added": by_kind(braid_wc::ChangeKind::Added),
456 "modified": by_kind(braid_wc::ChangeKind::Modified),
457 "deleted": by_kind(braid_wc::ChangeKind::Deleted),
458 "typechanged": by_kind(braid_wc::ChangeKind::TypeChanged),
459 "needs_track": status.needs_track.iter().map(|p| show(p)).collect::<Vec<_>>(),
460 "ready_to_commit": report.ready_to_commit(),
461 "blocking": report.blocking.iter().map(blocker_json).collect::<Vec<_>>(),
462 "rebase": rebase,
463 }))?;
464 return Ok(ExitCode::SUCCESS);
465 }
466 let mut out = io::stdout().lock();
467 writeln!(
468 out,
469 "Workspace {} on {}, at {}",
470 workspace.name(),
471 state.branch,
472 short(state.base)
473 )?;
474 if !report.unlanded.is_empty() {
475 writeln!(
476 out,
477 "{} not landed on {}",
478 count(report.unlanded.len(), "changeset"),
479 state.branch
480 )?;
481 }
482 if report.behind() {
483 let ahead = match report.behind_by {
484 Some(n) => count(n, "changeset"),
485 None => format!("more than {BEHIND_LIMIT} changesets"),
486 };
487 writeln!(
488 out,
489 "{} is {ahead} ahead, at {}: run `braid update`",
490 state.branch,
491 short(report.head)
492 )?;
493 }
494 if let Some(rebase) = &state.rebase {
495 writeln!(
496 out,
497 "Rebase of {} in progress onto {}; resolve, then `braid commit`",
498 rebase.change.short(),
499 rebase.onto.short()
500 )?;
501 for (conflict, remain) in &report.conflicts {
502 let note = if conflict.markers {
503 if *remain { "markers remain" } else { "edited" }
504 } else if conflict.resolved {
505 "resolved"
506 } else {
507 "run `braid resolve` once settled"
508 };
509 writeln!(
510 out,
511 " {:<13} {} ({note})",
512 conflict.code,
513 show(&conflict.path)
514 )?;
515 }
516 }
517 if status.is_clean() {
518 writeln!(out, "Nothing to commit.")?;
519 } else {
520 writeln!(out, "Changes:")?;
521 for change in &status.changes {
522 writeln!(out, " {:<11} {}", change.kind.name(), show(&change.path))?;
523 }
524 }
525 if !status.needs_track.is_empty() {
526 writeln!(out, "New files not committed until `braid track <path>`:")?;
527 for path in &status.needs_track {
528 writeln!(out, " {}", show(path))?;
529 }
530 }
531 if !report.blocking.is_empty() {
532 writeln!(out, "Not ready to commit:")?;
533 for blocker in &report.blocking {
534 writeln!(out, " - {blocker}")?;
535 }
536 } else if report.ready_to_commit() {
537 writeln!(out, "Ready to commit.")?;
538 }
539 Ok(ExitCode::SUCCESS)
540}
541
542/// One reason a commit would be refused, as data: what it is, the path,
543/// the kind of conflict it comes from, and what to do.
544fn blocker_json(blocker: &Blocker) -> Value {
545 let mut value = json!({
546 "reason": blocker.code(),
547 "path": show(blocker.path()),
548 "message": blocker.to_string(),
549 });
550 if let Some(kind) = blocker.conflict() {
551 value["kind"] = Value::String(kind.to_owned());
552 }
553 value
554}
555
556fn progress_json(progress: &RebaseProgress) -> Value {
557 match progress {
558 RebaseProgress::None => Value::Null,
559 RebaseProgress::Finished { tip } => json!({ "outcome": "finished", "tip": tip.to_hex() }),
560 RebaseProgress::Stopped { change, conflicts } => json!({
561 "outcome": "conflicts",
562 "change": change.to_hex(),
563 "conflicts": conflicts.iter().map(conflict_json).collect::<Vec<_>>(),
564 }),
565 }
566}
567
568pub(crate) fn commit(cli: &Cli, args: &CommitArgs) -> Result<ExitCode> {
569 let target = Target::find(cli)?;
570 let workspace = target.open()?;
571 let request = CommitRequest {
572 message: args.message.as_ref().map(|m| m.as_bytes().to_vec()),
573 paths: workspace_paths(&workspace, &args.paths)?,
574 author: None,
575 committer: identity(&args.identity, &target.repo)?,
576 agent: cli.agent.clone(),
577 force: args.force,
578 };
579 let outcome = workspace.commit(&request)?;
580 let stopped = matches!(outcome.rebase, RebaseProgress::Stopped { .. });
581 if cli.json {
582 print_json(&json!({
583 "changeset": hex(outcome.changeset),
584 "changes": outcome.changes,
585 "message_replaced": outcome.message_replaced,
586 "rebase": progress_json(&outcome.rebase),
587 }))?;
588 } else {
589 match outcome.changeset {
590 Some(id) => println!(
591 "Committed {} ({})",
592 id.short(),
593 count(outcome.changes, "path")
594 ),
595 None => println!("Nothing left to record for this changeset"),
596 }
597 if outcome.message_replaced {
598 println!("The message given replaces the rebased changeset's own.");
599 }
600 match &outcome.rebase {
601 RebaseProgress::None => {}
602 RebaseProgress::Finished { tip } => {
603 println!(
604 "Rebase finished at {}; `braid land` when ready",
605 tip.short()
606 );
607 }
608 RebaseProgress::Stopped { change, conflicts } => {
609 println!("The next changeset, {}, conflicts too:", change.short());
610 print_conflicts(conflicts);
611 }
612 }
613 }
614 Ok(if stopped {
615 ExitCode::from(CONFLICTS)
616 } else {
617 ExitCode::SUCCESS
618 })
619}
620
621/// What `land`, `update` and `change create --land` report, in one shape:
622/// the fields their long help lists.
623struct Report<'a> {
624 branch: &'a str,
625 outcome: &'static str,
626 head_before: Option<ObjectId>,
627 head: Option<ObjectId>,
628 placed: &'a [Placed],
629 merged_paths: &'a [Vec<u8>],
630 operation: Option<u64>,
631 change: Option<ObjectId>,
632 conflicts: &'a [Conflict],
633 next: Option<String>,
634 /// For a workspace: its base afterwards, and the paths of its working
635 /// copy written or removed.
636 workspace: Option<(Option<ObjectId>, &'a [Vec<u8>])>,
637}
638
639impl<'a> Report<'a> {
640 fn landing(report: &'a LandReport) -> Report<'a> {
641 let (outcome, change, conflicts): (_, _, &[Conflict]) = match &report.landed {
642 Landed::Nothing => ("nothing", None, &[]),
643 Landed::FastForward(_) => ("fast-forward", None, &[]),
644 Landed::Rebased(_) => ("rebased", None, &[]),
645 Landed::AlreadyApplied => ("already-applied", None, &[]),
646 Landed::Conflicts { change, conflicts } => ("conflicts", Some(*change), conflicts),
647 };
648 Report {
649 branch: &report.branch,
650 outcome,
651 head_before: report.head_before,
652 head: report.head(),
653 placed: &report.placed,
654 merged_paths: &report.merged_paths,
655 operation: report.operation,
656 change,
657 conflicts,
658 next: None,
659 workspace: None,
660 }
661 }
662
663 fn update(report: &'a UpdateReport) -> Report<'a> {
664 let (outcome, change, conflicts): (_, _, &[Conflict]) = match &report.updated {
665 Updated::UpToDate => ("up-to-date", None, &[]),
666 Updated::Moved { .. } => ("moved", None, &[]),
667 Updated::Rebased { .. } => ("rebased", None, &[]),
668 Updated::Conflicts {
669 change, conflicts, ..
670 } => ("conflicts", Some(*change), conflicts),
671 };
672 Report {
673 branch: &report.branch,
674 outcome,
675 // An update reads the head and never moves it.
676 head_before: report.head,
677 head: report.head,
678 placed: &report.placed,
679 merged_paths: &report.merged_paths,
680 operation: None,
681 change,
682 conflicts,
683 next: (!conflicts.is_empty()).then(|| "braid commit".to_owned()),
684 workspace: Some((report.base, &report.updated_paths)),
685 }
686 }
687
688 fn json(&self) -> Value {
689 let mut value = json!({
690 "branch": self.branch,
691 "outcome": self.outcome,
692 "head_before": hex(self.head_before),
693 "head": hex(self.head),
694 "landed": self.placed.iter().map(|placed| json!({
695 "from": placed.from.to_hex(),
696 "to": hex(placed.to),
697 })).collect::<Vec<_>>(),
698 "merged_paths": self.merged_paths.iter().map(|p| show(p)).collect::<Vec<_>>(),
699 "operation": self.operation,
700 "change": hex(self.change),
701 "conflicts": self.conflicts.iter().map(conflict_json).collect::<Vec<_>>(),
702 "next": self.next,
703 });
704 if let Some((base, updated)) = self.workspace {
705 value["base"] = hex(base);
706 value["updated_paths"] = updated.iter().map(|p| Value::String(show(p))).collect();
707 }
708 value
709 }
710
711 fn exit_code(&self) -> ExitCode {
712 if self.conflicts.is_empty() {
713 ExitCode::SUCCESS
714 } else {
715 ExitCode::from(CONFLICTS)
716 }
717 }
718
719 /// `, 1 path merged`, or nothing when none was.
720 fn merged(&self) -> String {
721 match self.merged_paths.len() {
722 0 => String::new(),
723 n => format!(" ({} merged)", count(n, "path")),
724 }
725 }
726
727 /// Says how many paths of the working copy changed, if any did.
728 fn print_updated(&self) {
729 if let Some((_, updated)) = self.workspace
730 && !updated.is_empty()
731 {
732 println!(
733 "Updated {} in the working copy",
734 count(updated.len(), "path")
735 );
736 }
737 }
738}
739
740pub(crate) fn land(cli: &Cli, args: &LandArgs) -> Result<ExitCode> {
741 let target = Target::find(cli)?;
742 let workspace = target.open()?;
743 let committer = identity(&args.identity, &target.repo)?;
744 let landing = workspace.land(args.onto.as_deref(), &cli.agent, &committer)?;
745 let mut report = Report::landing(&landing);
746 report.workspace = Some((workspace.state()?.base, &landing.updated_paths));
747 if !report.conflicts.is_empty() {
748 report.next = Some("braid update".to_owned());
749 }
750 if cli.json {
751 print_json(&report.json())?;
752 return Ok(report.exit_code());
753 }
754 let branch = &landing.branch;
755 let several = landing.placed.len() > 1;
756 match &landing.landed {
757 Landed::Nothing => println!("Nothing to land on {branch}"),
758 Landed::FastForward(id) if several => println!(
759 "Landed {} on {branch} (fast-forward), up to {}",
760 count(landing.placed.len(), "changeset"),
761 id.short()
762 ),
763 Landed::FastForward(id) => println!("Landed {} on {branch} (fast-forward)", id.short()),
764 Landed::Rebased(id) if several => println!(
765 "Landed {} on {branch}, rebased onto {}; the last is {}{}",
766 count(landing.placed.len(), "changeset"),
767 short(landing.head_before),
768 id.short(),
769 report.merged()
770 ),
771 Landed::Rebased(id) => println!(
772 "Landed on {branch} as {}, rebased onto {}{}",
773 id.short(),
774 short(landing.head_before),
775 report.merged()
776 ),
777 Landed::AlreadyApplied => println!("{branch} already has these changes"),
778 Landed::Conflicts { change, conflicts } => {
779 println!(
780 "{} conflicts with {branch} at {}; {branch} did not move:",
781 change.short(),
782 short(landing.head_before),
783 );
784 print_conflicts(conflicts);
785 println!("Run `braid update` to bring the conflicts into the working copy.");
786 }
787 }
788 report.print_updated();
789 Ok(report.exit_code())
790}
791
792pub(crate) fn update(cli: &Cli, args: &IdentityArgs) -> Result<ExitCode> {
793 let target = Target::find(cli)?;
794 let workspace = target.open()?;
795 let committer = identity(args, &target.repo)?;
796 let updated = workspace.update(&committer)?;
797 let report = Report::update(&updated);
798 if cli.json {
799 print_json(&report.json())?;
800 return Ok(report.exit_code());
801 }
802 match &updated.updated {
803 Updated::UpToDate => println!("Up to date"),
804 Updated::Moved { head } => println!("Moved to {}", head.short()),
805 Updated::Rebased { head, tip } => {
806 println!(
807 "Rebased onto {}; now at {}{}",
808 head.short(),
809 tip.short(),
810 report.merged()
811 );
812 }
813 Updated::Conflicts {
814 head,
815 change,
816 conflicts,
817 } => {
818 println!(
819 "{} conflicts with {}; the working copy has the merge so far:",
820 change.short(),
821 head.short()
822 );
823 print_conflicts(conflicts);
824 println!("Fix the files, `braid resolve` the other conflicts, then `braid commit`.");
825 }
826 }
827 report.print_updated();
828 Ok(report.exit_code())
829}
830
831pub(crate) fn resolve(cli: &Cli, paths: &[PathBuf]) -> Result<ExitCode> {
832 let target = Target::find(cli)?;
833 let workspace = target.open()?;
834 let paths = workspace_paths(&workspace, paths)?;
835 let remaining = workspace.resolve(&paths)?;
836 if cli.json {
837 print_json(&json!({
838 "resolved": paths.iter().map(|p| show(p)).collect::<Vec<_>>(),
839 "remaining": remaining.iter().map(|c| show(&c.path)).collect::<Vec<_>>(),
840 }))?;
841 } else if remaining.is_empty() {
842 println!("Every conflict needing `braid resolve` is resolved");
843 } else {
844 println!("Still unresolved:");
845 for conflict in &remaining {
846 println!(" {:<13} {}", conflict.code, show(&conflict.path));
847 }
848 }
849 Ok(ExitCode::SUCCESS)
850}
851
852pub(crate) fn track(cli: &Cli, paths: &[PathBuf]) -> Result<ExitCode> {
853 let target = Target::find(cli)?;
854 let workspace = target.open()?;
855 let paths = workspace_paths(&workspace, paths)?;
856 if paths.iter().any(Vec::is_empty) {
857 bail!("give files or directories inside the workspace, not its root");
858 }
859 let marks = workspace.track(&paths)?;
860 if cli.json {
861 print_json(&json!({ "tracked": marks.iter().map(|p| show(p)).collect::<Vec<_>>() }))?;
862 } else {
863 for path in &paths {
864 println!("New files at {} will be committed", show(path));
865 }
866 }
867 Ok(ExitCode::SUCCESS)
868}
869
870/// The bytes of a command-line argument.
871fn arg_bytes(arg: &OsStr) -> Result<Vec<u8>> {
872 braid_repo::text::path_bytes(Path::new(arg))
873 .with_context(|| format!("{} is not valid here", arg.to_string_lossy()))
874}
875
876pub(crate) fn change(cli: &Cli, action: &ChangeAction) -> Result<ExitCode> {
877 // The output is JSON whether or not `--json` is given.
878 let ChangeAction::Create(args) = action;
879 let repo = open_repo(cli)?;
880 let base = match args.base.as_str() {
881 "none" => None,
882 revision => Some(resolve_changeset(&repo, revision)?),
883 };
884 let mut stdin_used = false;
885 let mut sets = Vec::with_capacity(args.sets.len());
886 for set in &args.sets {
887 let bytes = arg_bytes(set)?;
888 let at = bytes
889 .windows(2)
890 .position(|pair| pair == b"=@")
891 .with_context(|| {
892 format!(
893 "--set takes PATH=@FILE or PATH=@-, not {}",
894 set.to_string_lossy()
895 )
896 })?;
897 let (path, source) = (bytes[..at].to_vec(), &bytes[at + 2..]);
898 let content = if source == b"-" {
899 if stdin_used {
900 bail!("only one --set can read standard input");
901 }
902 stdin_used = true;
903 let mut content = Vec::new();
904 io::stdin()
905 .lock()
906 .read_to_end(&mut content)
907 .context("cannot read standard input")?;
908 content
909 } else {
910 let file = braid_repo::text::path_from_bytes(source).context("invalid file name")?;
911 std::fs::read(&file).with_context(|| format!("cannot read {}", file.display()))?
912 };
913 sets.push((path, content));
914 }
915 let deletes = args
916 .deletes
917 .iter()
918 .map(|path| arg_bytes(path))
919 .collect::<Result<Vec<_>>>()?;
920 let mut expects = Vec::with_capacity(args.expects.len());
921 for expect in &args.expects {
922 let bytes = arg_bytes(expect)?;
923 let at = bytes
924 .iter()
925 .rposition(|byte| *byte == b'=')
926 .with_context(|| {
927 format!(
928 "--expect takes PATH=ID or PATH=absent, not {}",
929 expect.to_string_lossy()
930 )
931 })?;
932 let value = std::str::from_utf8(&bytes[at + 1..]).unwrap_or("");
933 let expected = match value {
934 "absent" => Expect::Absent,
935 id => Expect::Blob(id.parse().with_context(|| {
936 format!("--expect needs a full blob id or \"absent\", not {id:?}")
937 })?),
938 };
939 expects.push((bytes[..at].to_vec(), expected));
940 }
941 let author = identity(&args.identity, &repo)?;
942 let request = ChangeRequest {
943 base,
944 sets,
945 deletes,
946 expects,
947 message: args.message.as_bytes().to_vec(),
948 author: author.clone(),
949 agent: cli.agent.clone(),
950 };
951 let change = braid_wc::create_change(repo.store(), &request)?;
952 let landing = match &args.land {
953 Some(branch) => Some(braid_wc::land_change(
954 repo.store(),
955 branch,
956 change,
957 &cli.agent,
958 &author,
959 )?),
960 None => None,
961 };
962 let conflicted = matches!(
963 landing.as_ref().map(|report| &report.landed),
964 Some(Landed::Conflicts { .. })
965 );
966 // Always JSON: this command is for agents, which want the ids.
967 let land = match &landing {
968 Some(landing) => {
969 let mut report = Report::landing(landing);
970 if !report.conflicts.is_empty() {
971 // The change was built on a base the branch has moved past:
972 // it is made again on the new head.
973 report.next = Some(format!("braid change create --base {}", landing.branch));
974 }
975 report.json()
976 }
977 None => Value::Null,
978 };
979 print_json(&json!({
980 "change": change.to_hex(),
981 "base": hex(base),
982 "land": land,
983 }))?;
984 Ok(if conflicted {
985 ExitCode::from(CONFLICTS)
986 } else {
987 ExitCode::SUCCESS
988 })
989}
990
991fn entry_json(entry: &Option<EntryKind>) -> Value {
992 match entry {
993 None => Value::Null,
994 Some(EntryKind::Tree { tree }) => json!({ "kind": "tree", "tree": tree.to_hex() }),
995 Some(kind) => match ChangeOp::from_entry(kind) {
996 Some(op) => {
997 let mut value = change_json(&braid_format::Change {
998 path: Vec::new(),
999 op,
1000 });
1001 if let Some(object) = value.as_object_mut() {
1002 object.remove("path");
1003 if let Some(op) = object.remove("op") {
1004 object.insert("kind".to_owned(), op);
1005 }
1006 }
1007 value
1008 }
1009 None => Value::Null,
1010 },
1011 }
1012}
1013
1014fn side_json(side: &HunkSide) -> Value {
1015 json!({
1016 "start": side.lines.start,
1017 "end": side.lines.end,
1018 "text": String::from_utf8_lossy(&side.text),
1019 })
1020}
1021
1022/// A conflict as data, with its sides named from the caller's point of
1023/// view: the path, the kind's code, the entries of `base` (the common
1024/// ancestor), `branch` (what the branch has now) and `workspace` (the
1025/// change: the workspace's, or the one `change create` made), and for
1026/// content conflicts the hunks, with the same three sides.
1027pub(crate) fn conflict_json(conflict: &Conflict) -> Value {
1028 let mut value = json!({
1029 "path": show(&conflict.path),
1030 "kind": conflict.kind.code(),
1031 "base": entry_json(&conflict.base),
1032 "branch": entry_json(&conflict.ours),
1033 "workspace": entry_json(&conflict.theirs),
1034 "hunks": [],
1035 });
1036 match &conflict.kind {
1037 ConflictKind::Content { hunks } => {
1038 value["hunks"] = hunks
1039 .iter()
1040 .map(|hunk| {
1041 json!({
1042 "base": side_json(&hunk.base),
1043 "branch": side_json(&hunk.ours),
1044 "workspace": side_json(&hunk.theirs),
1045 })
1046 })
1047 .collect();
1048 }
1049 ConflictKind::DirectoryRemoved { directory } => {
1050 value["directory"] = Value::String(show(directory));
1051 }
1052 ConflictKind::Case { existing } => {
1053 value["existing"] = Value::String(show(existing));
1054 }
1055 _ => {}
1056 }
1057 value
1058}
1059
1060fn print_conflicts(conflicts: &[Conflict]) {
1061 for conflict in conflicts {
1062 let detail = match &conflict.kind {
1063 ConflictKind::Content { hunks } if !hunks.is_empty() => {
1064 format!(" ({})", count(hunks.len(), "region"))
1065 }
1066 ConflictKind::DirectoryRemoved { directory } => {
1067 format!(" (directory {} removed)", show(directory))
1068 }
1069 ConflictKind::Case { existing } => format!(" (collides with {})", show(existing)),
1070 _ => String::new(),
1071 };
1072 println!(
1073 " {:<13} {}{detail}",
1074 conflict.kind.code(),
1075 show(&conflict.path)
1076 );
1077 }
1078}