Elffuss BraidHub

utopia-ia/elffuss-braid public

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