Elffuss BraidHub

utopia-ia/elffuss-braid public

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