| 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_hubproto::api::LandResponse; |
| 19 | use braid_repo::{Location, Repo}; |
| 20 | use braid_store::Refs; |
| 21 | use braid_wc::{ |
| 22 | BEHIND_LIMIT, Blocker, ChangeRequest, CommitRequest, Expect, Identity, LandReport, Landed, |
| 23 | Placed, RebaseProgress, UpdateReport, Updated, Workspace, |
| 24 | }; |
| 25 | use clap::{Args, Subcommand}; |
| 26 | use serde_json::{Value, json}; |
| 27 | |
| 28 | use crate::hub::{self, land::HubLanding}; |
| 29 | use crate::{Cli, change_json, open_repo, print_json, resolve_changeset}; |
| 30 | |
| 31 | /// Exit status of a command that stopped on conflicts. |
| 32 | pub(crate) const CONFLICTS: u8 = 2; |
| 33 | |
| 34 | /// The fields of the report `land`, `update` and `change create --land` |
| 35 | /// print with `--json`, for their long help. |
| 36 | macro_rules! report_fields { |
| 37 | () => { |
| 38 | "With --json, land and update print one object with these fields; |
| 39 | change 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 | |
| 73 | Ids in JSON are full; text output shows their first 12 hex digits." |
| 74 | }; |
| 75 | } |
| 76 | |
| 77 | /// The long help of `status`. |
| 78 | pub(crate) const STATUS_HELP: &str = "Show how the workspace differs from its base and its branch. |
| 79 | |
| 80 | With --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 | |
| 119 | Ids in JSON are full; text output shows their first 12 hex digits."; |
| 120 | |
| 121 | /// The long help of `land`. |
| 122 | pub(crate) const LAND_HELP: &str = concat!( |
| 123 | "Land the workspace's changesets on its branch, in one step: a |
| 124 | fast-forward when they were built on the head, a rebase onto it otherwise. |
| 125 | The working copy then follows the landed tree. On conflicts the branch does |
| 126 | not move and the exit status is 2; `braid update` brings the conflicts into |
| 127 | the working copy. |
| 128 | |
| 129 | In a repository linked to a hub (`braid hub publish`, `braid hub clone`), |
| 130 | land lands on the hub: it fetches, uploads what the hub lacks of the |
| 131 | workspace's changesets, with any changesets of the local branch below them |
| 132 | that the hub does not have yet, asks the hub to land them, fetches again, |
| 133 | and moves the workspace onto the new head. The output and the exit statuses |
| 134 | are 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`. |
| 141 | pub(crate) const UPDATE_HELP: &str = concat!( |
| 142 | "Bring the workspace onto its branch's head, rebasing its own changesets |
| 143 | without moving the branch. On conflicts the exit status is 2: the working |
| 144 | copy gets the head's tree with the clean paths and conflict markers, and a |
| 145 | rebase is in progress until `braid commit`. |
| 146 | |
| 147 | In a repository linked to a hub, update fetches from the hub first, so the |
| 148 | head is the hub's. --local, or BRAID_HUB=off, updates from the local branch |
| 149 | as it is. |
| 150 | |
| 151 | ", |
| 152 | report_fields!() |
| 153 | ); |
| 154 | |
| 155 | /// The long help of `workspace add`. |
| 156 | pub(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 |
| 158 | branch it tracks, a .braid file that names the workspace and the |
| 159 | repository, and a .git file that points nowhere, so that git run inside |
| 160 | the workspace stops with \"not a git repository\" instead of acting on a |
| 161 | checkout around it. |
| 162 | |
| 163 | The branch must be one the repository has: a name it does not have is |
| 164 | refused, since landing would start a new history under that name, with |
| 165 | none of the repository's. A repository with no branch yet takes any |
| 166 | name, and --new-branch takes one on purpose; the first landing starts it. |
| 167 | |
| 168 | With --json it prints name, path, branch, base (the changeset the working |
| 169 | copy is at, or null) and files (how many it wrote)."; |
| 170 | |
| 171 | /// The long help of `change create`. |
| 172 | pub(crate) const CREATE_HELP: &str = concat!( |
| 173 | "Make a changeset on a base without a working copy, and optionally land |
| 174 | it (exit status 2 on conflicts). Prints JSON whether or not --json is |
| 175 | given: change, the new changeset's id; base; and land, the report of the |
| 176 | landing, or null. |
| 177 | |
| 178 | In a repository linked to a hub, --land uploads the changeset and lands it |
| 179 | on the hub, then fetches. --local, or BRAID_HUB=off, lands here. |
| 180 | |
| 181 | ", |
| 182 | report_fields!() |
| 183 | ); |
| 184 | |
| 185 | #[derive(Debug, Subcommand)] |
| 186 | pub(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)] |
| 225 | pub(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)] |
| 233 | pub(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)] |
| 249 | pub(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)] |
| 261 | pub(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)] |
| 271 | pub(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)] |
| 279 | pub(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. |
| 309 | struct 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 | |
| 316 | impl 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. |
| 354 | pub(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`. |
| 363 | pub(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. |
| 377 | fn 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 | |
| 399 | pub(crate) fn 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. |
| 404 | fn 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 | |
| 414 | fn 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`. |
| 419 | pub(crate) fn count<N>(n: N, noun: &str) -> String |
| 420 | where |
| 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 | |
| 431 | pub(crate) fn hex(id: Option<ObjectId>) -> Value { |
| 432 | id.map_or(Value::Null, |id| Value::String(id.to_hex())) |
| 433 | } |
| 434 | |
| 435 | pub(crate) fn short(id: Option<ObjectId>) -> String { |
| 436 | id.map_or_else(|| "(none)".to_owned(), |id| id.short()) |
| 437 | } |
| 438 | |
| 439 | pub(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 | |
| 530 | pub(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. |
| 688 | fn 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 | |
| 700 | fn 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 | |
| 712 | pub(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`, `change create --land` and `revert` report, in |
| 767 | /// one shape: the fields their long help lists. A landing on a hub fills it |
| 768 | /// from the hub's answer, so that it prints exactly what a local landing |
| 769 | /// does. |
| 770 | pub(crate) struct Report { |
| 771 | pub(crate) branch: String, |
| 772 | pub(crate) outcome: String, |
| 773 | head_before: Option<ObjectId>, |
| 774 | pub(crate) head: Option<ObjectId>, |
| 775 | placed: Vec<Placed>, |
| 776 | merged_paths: Vec<String>, |
| 777 | operation: Option<u64>, |
| 778 | change: Option<ObjectId>, |
| 779 | /// Each conflict as data (see [`conflict_json`]). |
| 780 | pub(crate) conflicts: Vec<Value>, |
| 781 | pub(crate) next: Option<String>, |
| 782 | /// For a workspace: its base afterwards, and the paths of its working |
| 783 | /// copy written or removed. |
| 784 | workspace: Option<(Option<ObjectId>, Vec<String>)>, |
| 785 | } |
| 786 | |
| 787 | impl Report { |
| 788 | pub(crate) fn landing(report: &LandReport) -> Report { |
| 789 | let (outcome, change, conflicts): (_, _, &[Conflict]) = match &report.landed { |
| 790 | Landed::Nothing => ("nothing", None, &[]), |
| 791 | Landed::FastForward(_) => ("fast-forward", None, &[]), |
| 792 | Landed::Rebased(_) => ("rebased", None, &[]), |
| 793 | Landed::AlreadyApplied => ("already-applied", None, &[]), |
| 794 | Landed::Conflicts { change, conflicts } => ("conflicts", Some(*change), conflicts), |
| 795 | Landed::Refused => ("refused", None, &[]), |
| 796 | }; |
| 797 | Report { |
| 798 | branch: report.branch.clone(), |
| 799 | outcome: outcome.to_owned(), |
| 800 | head_before: report.head_before, |
| 801 | head: report.head(), |
| 802 | placed: report.placed.clone(), |
| 803 | merged_paths: report.merged_paths.iter().map(|p| show(p)).collect(), |
| 804 | operation: report.operation, |
| 805 | change, |
| 806 | conflicts: conflicts.iter().map(conflict_json).collect(), |
| 807 | next: None, |
| 808 | workspace: None, |
| 809 | } |
| 810 | } |
| 811 | |
| 812 | /// A landing as the hub answered it. |
| 813 | pub(crate) fn hub(response: &LandResponse) -> Report { |
| 814 | Report { |
| 815 | branch: response.reference.clone(), |
| 816 | outcome: response.outcome.clone(), |
| 817 | head_before: response.head_before, |
| 818 | head: response.head, |
| 819 | placed: response |
| 820 | .landed |
| 821 | .iter() |
| 822 | .map(|placed| Placed { |
| 823 | from: placed.from, |
| 824 | to: placed.to, |
| 825 | }) |
| 826 | .collect(), |
| 827 | merged_paths: response.merged_paths.clone(), |
| 828 | operation: response.operation, |
| 829 | change: response.change, |
| 830 | conflicts: response.conflicts.clone(), |
| 831 | next: None, |
| 832 | workspace: None, |
| 833 | } |
| 834 | } |
| 835 | |
| 836 | /// A workspace's landing on a hub. |
| 837 | fn hub_landing(landing: &HubLanding) -> Report { |
| 838 | let mut report = match &landing.response { |
| 839 | Some(response) => Report::hub(response), |
| 840 | // Nothing went to the hub: its branch stays where it was. |
| 841 | None => Report { |
| 842 | branch: landing.branch.clone(), |
| 843 | outcome: "nothing".to_owned(), |
| 844 | head_before: landing.head, |
| 845 | head: landing.head, |
| 846 | placed: Vec::new(), |
| 847 | merged_paths: Vec::new(), |
| 848 | operation: None, |
| 849 | change: None, |
| 850 | conflicts: Vec::new(), |
| 851 | next: None, |
| 852 | workspace: None, |
| 853 | }, |
| 854 | }; |
| 855 | report.workspace = Some(( |
| 856 | landing.base, |
| 857 | landing.updated_paths.iter().map(|p| show(p)).collect(), |
| 858 | )); |
| 859 | report |
| 860 | } |
| 861 | |
| 862 | fn update(report: &UpdateReport) -> Report { |
| 863 | let (outcome, change, conflicts): (_, _, &[Conflict]) = match &report.updated { |
| 864 | Updated::UpToDate => ("up-to-date", None, &[]), |
| 865 | Updated::Moved { .. } => ("moved", None, &[]), |
| 866 | Updated::Rebased { .. } => ("rebased", None, &[]), |
| 867 | Updated::Conflicts { |
| 868 | change, conflicts, .. |
| 869 | } => ("conflicts", Some(*change), conflicts), |
| 870 | }; |
| 871 | Report { |
| 872 | branch: report.branch.clone(), |
| 873 | outcome: outcome.to_owned(), |
| 874 | // An update reads the head and never moves it. |
| 875 | head_before: report.head, |
| 876 | head: report.head, |
| 877 | placed: report.placed.clone(), |
| 878 | merged_paths: report.merged_paths.iter().map(|p| show(p)).collect(), |
| 879 | operation: None, |
| 880 | change, |
| 881 | conflicts: conflicts.iter().map(conflict_json).collect(), |
| 882 | next: None, |
| 883 | workspace: Some(( |
| 884 | report.base, |
| 885 | report.updated_paths.iter().map(|p| show(p)).collect(), |
| 886 | )), |
| 887 | } |
| 888 | } |
| 889 | |
| 890 | pub(crate) fn conflicted(&self) -> bool { |
| 891 | self.outcome == "conflicts" || !self.conflicts.is_empty() |
| 892 | } |
| 893 | |
| 894 | pub(crate) fn json(&self) -> Value { |
| 895 | let mut value = json!({ |
| 896 | "branch": self.branch, |
| 897 | "outcome": self.outcome, |
| 898 | "head_before": hex(self.head_before), |
| 899 | "head": hex(self.head), |
| 900 | "landed": self.placed.iter().map(|placed| json!({ |
| 901 | "from": placed.from.to_hex(), |
| 902 | "to": hex(placed.to), |
| 903 | })).collect::<Vec<_>>(), |
| 904 | "merged_paths": self.merged_paths, |
| 905 | "operation": self.operation, |
| 906 | "change": hex(self.change), |
| 907 | "conflicts": self.conflicts, |
| 908 | "next": self.next, |
| 909 | }); |
| 910 | if let Some((base, updated)) = &self.workspace { |
| 911 | value["base"] = hex(*base); |
| 912 | value["updated_paths"] = updated.iter().map(|p| Value::String(p.clone())).collect(); |
| 913 | } |
| 914 | value |
| 915 | } |
| 916 | |
| 917 | pub(crate) fn exit_code(&self) -> ExitCode { |
| 918 | if self.conflicted() { |
| 919 | ExitCode::from(CONFLICTS) |
| 920 | } else { |
| 921 | ExitCode::SUCCESS |
| 922 | } |
| 923 | } |
| 924 | |
| 925 | /// ` (1 path merged)`, or nothing when no path was merged. |
| 926 | fn merged(&self) -> String { |
| 927 | match self.merged_paths.len() { |
| 928 | 0 => String::new(), |
| 929 | n => format!(" ({} merged)", count(n, "path")), |
| 930 | } |
| 931 | } |
| 932 | |
| 933 | /// Says how many paths of the working copy changed, if any did. |
| 934 | fn print_updated(&self) { |
| 935 | if let Some((_, updated)) = &self.workspace |
| 936 | && !updated.is_empty() |
| 937 | { |
| 938 | println!( |
| 939 | "Updated {} in the working copy", |
| 940 | count(updated.len(), "path") |
| 941 | ); |
| 942 | } |
| 943 | } |
| 944 | |
| 945 | /// Prints a landing as text. |
| 946 | pub(crate) fn print_landing(&self, cli: &Cli) { |
| 947 | let branch = &self.branch; |
| 948 | let several = self.placed.len() > 1; |
| 949 | match self.outcome.as_str() { |
| 950 | "nothing" => println!("Nothing to land on {branch}"), |
| 951 | "fast-forward" if several => println!( |
| 952 | "Landed {} on {branch} (fast-forward), up to {}", |
| 953 | count(self.placed.len(), "changeset"), |
| 954 | short(self.head) |
| 955 | ), |
| 956 | "fast-forward" => println!("Landed {} on {branch} (fast-forward)", short(self.head)), |
| 957 | "rebased" if several => println!( |
| 958 | "Landed {} on {branch}, rebased onto {}; the last is {}{}", |
| 959 | count(self.placed.len(), "changeset"), |
| 960 | short(self.head_before), |
| 961 | short(self.head), |
| 962 | self.merged() |
| 963 | ), |
| 964 | "rebased" => println!( |
| 965 | "Landed on {branch} as {}, rebased onto {}{}", |
| 966 | short(self.head), |
| 967 | short(self.head_before), |
| 968 | self.merged() |
| 969 | ), |
| 970 | "already-applied" => println!("{branch} already has these changes"), |
| 971 | "refused" => println!("{branch} refused the landing: it is not a fast-forward"), |
| 972 | "conflicts" => { |
| 973 | println!( |
| 974 | "{} conflicts with {branch} at {}; {branch} did not move:", |
| 975 | short(self.change), |
| 976 | short(self.head_before), |
| 977 | ); |
| 978 | print_conflicts(&self.conflicts); |
| 979 | println!( |
| 980 | "Run `{}` to bring the conflicts into the working copy.", |
| 981 | cli.hint("update") |
| 982 | ); |
| 983 | } |
| 984 | other => println!("The landing on {branch} ended with {other}"), |
| 985 | } |
| 986 | self.print_updated(); |
| 987 | } |
| 988 | } |
| 989 | |
| 990 | pub(crate) fn land(cli: &Cli, args: &LandArgs) -> Result<ExitCode> { |
| 991 | let target = Target::find(cli)?; |
| 992 | let workspace = target.open()?; |
| 993 | let committer = identity(&args.identity, &target.repo)?; |
| 994 | let mut report = match hub::linked(&target.repo, args.local)? { |
| 995 | Some(link) => { |
| 996 | let hub = hub::connect(&link)?; |
| 997 | let remote = hub.repo(link.repo.clone()); |
| 998 | let landing = hub::land::land_workspace( |
| 999 | &target.repo, |
| 1000 | &workspace, |
| 1001 | &remote, |
| 1002 | &link, |
| 1003 | args.onto.as_deref(), |
| 1004 | &cli.agent, |
| 1005 | )?; |
| 1006 | Report::hub_landing(&landing) |
| 1007 | } |
| 1008 | None => { |
| 1009 | let landing = workspace.land(args.onto.as_deref(), &cli.agent, &committer)?; |
| 1010 | let mut report = Report::landing(&landing); |
| 1011 | report.workspace = Some(( |
| 1012 | workspace.state()?.base, |
| 1013 | landing.updated_paths.iter().map(|p| show(p)).collect(), |
| 1014 | )); |
| 1015 | report |
| 1016 | } |
| 1017 | }; |
| 1018 | if report.conflicted() { |
| 1019 | report.next = Some(cli.hint("update")); |
| 1020 | } |
| 1021 | if cli.json { |
| 1022 | print_json(&report.json())?; |
| 1023 | } else { |
| 1024 | report.print_landing(cli); |
| 1025 | } |
| 1026 | Ok(report.exit_code()) |
| 1027 | } |
| 1028 | |
| 1029 | pub(crate) fn update(cli: &Cli, args: &UpdateArgs) -> Result<ExitCode> { |
| 1030 | let target = Target::find(cli)?; |
| 1031 | let workspace = target.open()?; |
| 1032 | let committer = identity(&args.identity, &target.repo)?; |
| 1033 | if let Some(link) = hub::linked(&target.repo, args.local)? { |
| 1034 | let hub = hub::connect(&link)?; |
| 1035 | let remote = hub.repo(link.repo.clone()); |
| 1036 | hub::fetch::fetch(&target.repo, &remote, &link, &cli.agent, None) |
| 1037 | .context("cannot fetch from the hub before updating (--local updates from the local branch as it is)")?; |
| 1038 | } |
| 1039 | let updated = workspace.update(&committer)?; |
| 1040 | let mut report = Report::update(&updated); |
| 1041 | if report.conflicted() { |
| 1042 | report.next = Some(cli.hint("commit")); |
| 1043 | } |
| 1044 | if cli.json { |
| 1045 | print_json(&report.json())?; |
| 1046 | return Ok(report.exit_code()); |
| 1047 | } |
| 1048 | match &updated.updated { |
| 1049 | Updated::UpToDate => println!("Up to date"), |
| 1050 | Updated::Moved { head } => println!("Moved to {}", head.short()), |
| 1051 | Updated::Rebased { head, tip } => { |
| 1052 | println!( |
| 1053 | "Rebased onto {}; now at {}{}", |
| 1054 | head.short(), |
| 1055 | tip.short(), |
| 1056 | report.merged() |
| 1057 | ); |
| 1058 | } |
| 1059 | Updated::Conflicts { head, change, .. } => { |
| 1060 | println!( |
| 1061 | "{} conflicts with {}; the working copy has the merge so far:", |
| 1062 | change.short(), |
| 1063 | head.short() |
| 1064 | ); |
| 1065 | print_conflicts(&report.conflicts); |
| 1066 | println!( |
| 1067 | "Fix the files, `{}` the other conflicts, then `{}`.", |
| 1068 | cli.hint("resolve"), |
| 1069 | cli.hint("commit") |
| 1070 | ); |
| 1071 | } |
| 1072 | } |
| 1073 | report.print_updated(); |
| 1074 | Ok(report.exit_code()) |
| 1075 | } |
| 1076 | |
| 1077 | pub(crate) fn resolve(cli: &Cli, paths: &[PathBuf]) -> Result<ExitCode> { |
| 1078 | let target = Target::find(cli)?; |
| 1079 | let workspace = target.open()?; |
| 1080 | let paths = workspace_paths(&workspace, paths)?; |
| 1081 | let remaining = workspace.resolve(&paths)?; |
| 1082 | if cli.json { |
| 1083 | print_json(&json!({ |
| 1084 | "resolved": paths.iter().map(|p| show(p)).collect::<Vec<_>>(), |
| 1085 | "remaining": remaining.iter().map(|c| show(&c.path)).collect::<Vec<_>>(), |
| 1086 | }))?; |
| 1087 | } else if remaining.is_empty() { |
| 1088 | println!("Every conflict needing `braid resolve` is resolved"); |
| 1089 | } else { |
| 1090 | println!("Still unresolved:"); |
| 1091 | for conflict in &remaining { |
| 1092 | println!(" {:<13} {}", conflict.code, show(&conflict.path)); |
| 1093 | } |
| 1094 | } |
| 1095 | Ok(ExitCode::SUCCESS) |
| 1096 | } |
| 1097 | |
| 1098 | pub(crate) fn track(cli: &Cli, paths: &[PathBuf]) -> Result<ExitCode> { |
| 1099 | let target = Target::find(cli)?; |
| 1100 | let workspace = target.open()?; |
| 1101 | let paths = workspace_paths(&workspace, paths)?; |
| 1102 | if paths.iter().any(Vec::is_empty) { |
| 1103 | bail!("give files or directories inside the workspace, not its root"); |
| 1104 | } |
| 1105 | let marks = workspace.track(&paths)?; |
| 1106 | if cli.json { |
| 1107 | print_json(&json!({ "tracked": marks.iter().map(|p| show(p)).collect::<Vec<_>>() }))?; |
| 1108 | } else { |
| 1109 | for path in &paths { |
| 1110 | println!("New files at {} will be committed", show(path)); |
| 1111 | } |
| 1112 | } |
| 1113 | Ok(ExitCode::SUCCESS) |
| 1114 | } |
| 1115 | |
| 1116 | /// The bytes of a command-line argument. |
| 1117 | fn arg_bytes(arg: &OsStr) -> Result<Vec<u8>> { |
| 1118 | braid_repo::text::path_bytes(Path::new(arg)) |
| 1119 | .with_context(|| format!("{} is not valid here", arg.to_string_lossy())) |
| 1120 | } |
| 1121 | |
| 1122 | pub(crate) fn change(cli: &Cli, action: &ChangeAction) -> Result<ExitCode> { |
| 1123 | // The output is JSON whether or not `--json` is given. |
| 1124 | let ChangeAction::Create(args) = action; |
| 1125 | let repo = open_repo(cli)?; |
| 1126 | let base = match args.base.as_str() { |
| 1127 | "none" => None, |
| 1128 | revision => Some(resolve_changeset(&repo, revision)?), |
| 1129 | }; |
| 1130 | let mut stdin_used = false; |
| 1131 | let mut sets = Vec::with_capacity(args.sets.len()); |
| 1132 | for set in &args.sets { |
| 1133 | let bytes = arg_bytes(set)?; |
| 1134 | let at = bytes |
| 1135 | .windows(2) |
| 1136 | .position(|pair| pair == b"=@") |
| 1137 | .with_context(|| { |
| 1138 | format!( |
| 1139 | "--set takes PATH=@FILE or PATH=@-, not {}", |
| 1140 | set.to_string_lossy() |
| 1141 | ) |
| 1142 | })?; |
| 1143 | let (path, source) = (bytes[..at].to_vec(), &bytes[at + 2..]); |
| 1144 | let content = if source == b"-" { |
| 1145 | if stdin_used { |
| 1146 | bail!("only one --set can read standard input"); |
| 1147 | } |
| 1148 | stdin_used = true; |
| 1149 | let mut content = Vec::new(); |
| 1150 | io::stdin() |
| 1151 | .lock() |
| 1152 | .read_to_end(&mut content) |
| 1153 | .context("cannot read standard input")?; |
| 1154 | content |
| 1155 | } else { |
| 1156 | let file = braid_repo::text::path_from_bytes(source).context("invalid file name")?; |
| 1157 | std::fs::read(&file).with_context(|| format!("cannot read {}", file.display()))? |
| 1158 | }; |
| 1159 | sets.push((path, content)); |
| 1160 | } |
| 1161 | let deletes = args |
| 1162 | .deletes |
| 1163 | .iter() |
| 1164 | .map(|path| arg_bytes(path)) |
| 1165 | .collect::<Result<Vec<_>>>()?; |
| 1166 | let mut expects = Vec::with_capacity(args.expects.len()); |
| 1167 | for expect in &args.expects { |
| 1168 | let bytes = arg_bytes(expect)?; |
| 1169 | let at = bytes |
| 1170 | .iter() |
| 1171 | .rposition(|byte| *byte == b'=') |
| 1172 | .with_context(|| { |
| 1173 | format!( |
| 1174 | "--expect takes PATH=ID or PATH=absent, not {}", |
| 1175 | expect.to_string_lossy() |
| 1176 | ) |
| 1177 | })?; |
| 1178 | let value = std::str::from_utf8(&bytes[at + 1..]).unwrap_or(""); |
| 1179 | let expected = match value { |
| 1180 | "absent" => Expect::Absent, |
| 1181 | id => Expect::Blob(id.parse().with_context(|| { |
| 1182 | format!("--expect needs a full blob id or \"absent\", not {id:?}") |
| 1183 | })?), |
| 1184 | }; |
| 1185 | expects.push((bytes[..at].to_vec(), expected)); |
| 1186 | } |
| 1187 | let author = identity(&args.identity, &repo)?; |
| 1188 | let request = ChangeRequest { |
| 1189 | base, |
| 1190 | sets, |
| 1191 | deletes, |
| 1192 | expects, |
| 1193 | message: args.message.as_bytes().to_vec(), |
| 1194 | author: author.clone(), |
| 1195 | agent: cli.agent.clone(), |
| 1196 | }; |
| 1197 | let change = braid_wc::create_change(repo.store(), &request)?; |
| 1198 | let report = match &args.land { |
| 1199 | Some(branch) => Some(match hub::linked(&repo, args.local)? { |
| 1200 | Some(link) => { |
| 1201 | let hub = hub::connect(&link)?; |
| 1202 | let remote = hub.repo(link.repo.clone()); |
| 1203 | let response = hub::land::land_change( |
| 1204 | &repo, |
| 1205 | &remote, |
| 1206 | &link, |
| 1207 | branch, |
| 1208 | change, |
| 1209 | &cli.agent, |
| 1210 | "braid change create", |
| 1211 | )?; |
| 1212 | Report::hub(&response) |
| 1213 | } |
| 1214 | None => Report::landing(&braid_wc::land_change( |
| 1215 | repo.store(), |
| 1216 | branch, |
| 1217 | change, |
| 1218 | &cli.agent, |
| 1219 | &author, |
| 1220 | )?), |
| 1221 | }), |
| 1222 | None => None, |
| 1223 | }; |
| 1224 | let conflicted = report.as_ref().is_some_and(Report::conflicted); |
| 1225 | // Always JSON: this command is for agents, which want the ids. |
| 1226 | let land = match report { |
| 1227 | Some(mut report) => { |
| 1228 | if report.conflicted() { |
| 1229 | // The change was built on a base the branch has moved past: |
| 1230 | // it is made again on the new head. |
| 1231 | report.next = Some(cli.hint(&format!( |
| 1232 | "change create --base {}", |
| 1233 | crate::shell_word(&report.branch) |
| 1234 | ))); |
| 1235 | } |
| 1236 | report.json() |
| 1237 | } |
| 1238 | None => Value::Null, |
| 1239 | }; |
| 1240 | print_json(&json!({ |
| 1241 | "change": change.to_hex(), |
| 1242 | "base": hex(base), |
| 1243 | "land": land, |
| 1244 | }))?; |
| 1245 | Ok(if conflicted { |
| 1246 | ExitCode::from(CONFLICTS) |
| 1247 | } else { |
| 1248 | ExitCode::SUCCESS |
| 1249 | }) |
| 1250 | } |
| 1251 | |
| 1252 | fn entry_json(entry: &Option<EntryKind>) -> Value { |
| 1253 | match entry { |
| 1254 | None => Value::Null, |
| 1255 | Some(EntryKind::Tree { tree }) => json!({ "kind": "tree", "tree": tree.to_hex() }), |
| 1256 | Some(kind) => match ChangeOp::from_entry(kind) { |
| 1257 | Some(op) => { |
| 1258 | let mut value = change_json(&braid_format::Change { |
| 1259 | path: Vec::new(), |
| 1260 | op, |
| 1261 | }); |
| 1262 | if let Some(object) = value.as_object_mut() { |
| 1263 | object.remove("path"); |
| 1264 | if let Some(op) = object.remove("op") { |
| 1265 | object.insert("kind".to_owned(), op); |
| 1266 | } |
| 1267 | } |
| 1268 | value |
| 1269 | } |
| 1270 | None => Value::Null, |
| 1271 | }, |
| 1272 | } |
| 1273 | } |
| 1274 | |
| 1275 | fn side_json(side: &HunkSide) -> Value { |
| 1276 | json!({ |
| 1277 | "start": side.lines.start, |
| 1278 | "end": side.lines.end, |
| 1279 | "text": String::from_utf8_lossy(&side.text), |
| 1280 | }) |
| 1281 | } |
| 1282 | |
| 1283 | /// A conflict as data, with its sides named from the caller's point of |
| 1284 | /// view: the path, the kind's code, the entries of `base` (the common |
| 1285 | /// ancestor), `branch` (what the branch has now) and `workspace` (the |
| 1286 | /// change: the workspace's, or the one `change create` made), and for |
| 1287 | /// content conflicts the hunks, with the same three sides. |
| 1288 | pub(crate) fn conflict_json(conflict: &Conflict) -> Value { |
| 1289 | let mut value = json!({ |
| 1290 | "path": show(&conflict.path), |
| 1291 | "kind": conflict.kind.code(), |
| 1292 | "base": entry_json(&conflict.base), |
| 1293 | "branch": entry_json(&conflict.ours), |
| 1294 | "workspace": entry_json(&conflict.theirs), |
| 1295 | "hunks": [], |
| 1296 | }); |
| 1297 | match &conflict.kind { |
| 1298 | ConflictKind::Content { hunks } => { |
| 1299 | value["hunks"] = hunks |
| 1300 | .iter() |
| 1301 | .map(|hunk| { |
| 1302 | json!({ |
| 1303 | "base": side_json(&hunk.base), |
| 1304 | "branch": side_json(&hunk.ours), |
| 1305 | "workspace": side_json(&hunk.theirs), |
| 1306 | }) |
| 1307 | }) |
| 1308 | .collect(); |
| 1309 | } |
| 1310 | ConflictKind::DirectoryRemoved { directory } => { |
| 1311 | value["directory"] = Value::String(show(directory)); |
| 1312 | } |
| 1313 | ConflictKind::Case { existing } => { |
| 1314 | value["existing"] = Value::String(show(existing)); |
| 1315 | } |
| 1316 | _ => {} |
| 1317 | } |
| 1318 | value |
| 1319 | } |
| 1320 | |
| 1321 | /// Prints conflicts as data ([`conflict_json`], or a hub's answer, which |
| 1322 | /// has the same shape), one line each: the kind, the path, and the regions |
| 1323 | /// of a content conflict, the directory removed, or the path collided with. |
| 1324 | pub(crate) fn print_conflicts(conflicts: &[Value]) { |
| 1325 | for conflict in conflicts { |
| 1326 | let text = |key: &str| conflict[key].as_str().unwrap_or(""); |
| 1327 | let regions = conflict["hunks"].as_array().map_or(0, Vec::len); |
| 1328 | let detail = if regions > 0 { |
| 1329 | format!(" ({})", count(regions, "region")) |
| 1330 | } else if let Some(directory) = conflict["directory"].as_str() { |
| 1331 | format!(" (directory {directory} removed)") |
| 1332 | } else if let Some(existing) = conflict["existing"].as_str() { |
| 1333 | format!(" (collides with {existing})") |
| 1334 | } else { |
| 1335 | String::new() |
| 1336 | }; |
| 1337 | println!(" {:<13} {}{detail}", text("kind"), text("path")); |
| 1338 | } |
| 1339 | } |