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