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