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