| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Workspace commands: `workspace`, `status`, `commit`, `land`, `update`, |
| 5 | //! `resolve`, `track` and `change create`. |
| 6 | //! |
| 7 | //! Commands that report conflicts exit with status 2, so that an agent can |
| 8 | //! tell them from failures (status 1) without parsing anything. |
| 9 | |
| 10 | use std::ffi::{OsStr, OsString}; |
| 11 | use std::io::{self, Read, Write}; |
| 12 | use std::path::{Path, PathBuf}; |
| 13 | use std::process::ExitCode; |
| 14 | |
| 15 | use anyhow::{Context, Result, bail}; |
| 16 | use braid_engine::{Conflict, ConflictKind, HunkSide}; |
| 17 | use braid_format::{ChangeOp, EntryKind, ObjectId}; |
| 18 | use braid_repo::{Location, Repo}; |
| 19 | use braid_wc::{ |
| 20 | ChangeRequest, CommitRequest, Expect, Identity, LandReport, Landed, RebaseProgress, Updated, |
| 21 | Workspace, |
| 22 | }; |
| 23 | use clap::{Args, Subcommand}; |
| 24 | use serde_json::{Value, json}; |
| 25 | |
| 26 | use crate::{Cli, change_json, open_repo, print_json, resolve_changeset}; |
| 27 | |
| 28 | /// Exit status of a command that stopped on conflicts. |
| 29 | const CONFLICTS: u8 = 2; |
| 30 | |
| 31 | #[derive(Debug, Subcommand)] |
| 32 | pub(crate) enum WorkspaceAction { |
| 33 | /// Create a workspace and write its files. |
| 34 | Add { |
| 35 | /// The workspace's name: letters, digits, '.', '_' or '-'. |
| 36 | name: String, |
| 37 | /// Its directory, which must not exist or be empty (default: |
| 38 | /// ./<name>). |
| 39 | path: Option<PathBuf>, |
| 40 | /// The changeset to start at: a ref, an id or a short id (default: |
| 41 | /// the head of the tracked branch, or nothing if it does not exist |
| 42 | /// yet). |
| 43 | #[arg(long, value_name = "REV")] |
| 44 | at: Option<String>, |
| 45 | /// The branch the workspace lands on and updates from. |
| 46 | #[arg(long, value_name = "BRANCH", default_value = "main")] |
| 47 | track: String, |
| 48 | }, |
| 49 | /// List the repository's workspaces. |
| 50 | List, |
| 51 | /// Remove a workspace: its directory and its state. |
| 52 | Remove { |
| 53 | /// The workspace's name. |
| 54 | name: String, |
| 55 | /// Remove it even with uncommitted changes, unlanded changesets or |
| 56 | /// a rebase in progress. |
| 57 | #[arg(long)] |
| 58 | force: bool, |
| 59 | }, |
| 60 | } |
| 61 | |
| 62 | #[derive(Debug, Args)] |
| 63 | pub(crate) struct IdentityArgs { |
| 64 | /// Who records changesets, as "Name <email>" (default: BRAID_AUTHOR, |
| 65 | /// then name and email in .braid/config). |
| 66 | #[arg(long, env = "BRAID_AUTHOR", value_name = "IDENTITY")] |
| 67 | author: Option<String>, |
| 68 | } |
| 69 | |
| 70 | #[derive(Debug, Args)] |
| 71 | pub(crate) struct CommitArgs { |
| 72 | /// The message (while a rebase is in progress, the rebased changeset's |
| 73 | /// message by default). |
| 74 | #[arg(short, long)] |
| 75 | message: Option<String>, |
| 76 | /// Commit even if conflict markers remain or conflicts are not marked |
| 77 | /// resolved. |
| 78 | #[arg(long)] |
| 79 | force: bool, |
| 80 | #[command(flatten)] |
| 81 | identity: IdentityArgs, |
| 82 | /// Commit only these files and directories (default: everything). |
| 83 | paths: Vec<PathBuf>, |
| 84 | } |
| 85 | |
| 86 | #[derive(Debug, Args)] |
| 87 | pub(crate) struct LandArgs { |
| 88 | /// The branch to land on (default: the workspace's branch). |
| 89 | #[arg(long, value_name = "BRANCH")] |
| 90 | onto: Option<String>, |
| 91 | #[command(flatten)] |
| 92 | identity: IdentityArgs, |
| 93 | } |
| 94 | |
| 95 | #[derive(Debug, Subcommand)] |
| 96 | pub(crate) enum ChangeAction { |
| 97 | /// Make a changeset on a base without a working copy, and optionally |
| 98 | /// land it (exit status 2 on conflicts). Prints the ids as JSON. |
| 99 | Create(CreateArgs), |
| 100 | } |
| 101 | |
| 102 | #[derive(Debug, Args)] |
| 103 | pub(crate) struct CreateArgs { |
| 104 | /// The changeset to build on: a ref, an id, a short id (6 hex digits or |
| 105 | /// more), or "none" for a first changeset. |
| 106 | #[arg(long, value_name = "REV")] |
| 107 | base: String, |
| 108 | /// Set a file: PATH=@FILE takes the content of FILE, PATH=@- reads |
| 109 | /// standard input. Repeat for several. |
| 110 | #[arg(long = "set", value_name = "PATH=@FILE")] |
| 111 | sets: Vec<OsString>, |
| 112 | /// Delete a file. Repeat for several. |
| 113 | #[arg(long = "delete", value_name = "PATH")] |
| 114 | deletes: Vec<OsString>, |
| 115 | /// Require the base to hold this blob at PATH, or nothing ("absent"), |
| 116 | /// before anything is made. Repeat for several. |
| 117 | #[arg(long = "expect", value_name = "PATH=ID|absent")] |
| 118 | expects: Vec<OsString>, |
| 119 | /// The message. |
| 120 | #[arg(short, long)] |
| 121 | message: String, |
| 122 | /// Land the changeset on this branch. |
| 123 | #[arg(long, value_name = "BRANCH")] |
| 124 | land: Option<String>, |
| 125 | #[command(flatten)] |
| 126 | identity: IdentityArgs, |
| 127 | } |
| 128 | |
| 129 | /// The repository and the workspace a command acts on. |
| 130 | struct Target { |
| 131 | repo: Repo, |
| 132 | name: String, |
| 133 | /// Where its `.braid` file was found, when it was found by looking. |
| 134 | dir: Option<PathBuf>, |
| 135 | } |
| 136 | |
| 137 | impl Target { |
| 138 | /// The workspace named by `--workspace`, or the one containing the |
| 139 | /// current directory. |
| 140 | fn find(cli: &Cli) -> Result<Target> { |
| 141 | if let Some(name) = &cli.workspace { |
| 142 | return Ok(Target { |
| 143 | repo: open_repo(cli)?, |
| 144 | name: name.clone(), |
| 145 | dir: None, |
| 146 | }); |
| 147 | } |
| 148 | let cwd = std::env::current_dir()?; |
| 149 | match braid_repo::locate(&cwd)? { |
| 150 | Location::Workspace { dir, link } => { |
| 151 | let repo = match &cli.repo { |
| 152 | Some(root) => Repo::open(root)?, |
| 153 | None => Repo::open(&link.repository)?, |
| 154 | }; |
| 155 | Ok(Target { |
| 156 | repo, |
| 157 | name: link.name, |
| 158 | dir: Some(dir), |
| 159 | }) |
| 160 | } |
| 161 | Location::Root(_) => Err(braid_wc::Error::NotAWorkspace.into()), |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | fn open(&self) -> Result<Workspace<'_>> { |
| 166 | Ok(match &self.dir { |
| 167 | Some(dir) => Workspace::at(&self.repo, &self.name, dir)?, |
| 168 | None => Workspace::open(&self.repo, &self.name)?, |
| 169 | }) |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | fn identity(args: &IdentityArgs, repo: &Repo) -> Result<Identity> { |
| 174 | Ok(Identity::resolve(args.author.as_deref(), repo)?) |
| 175 | } |
| 176 | |
| 177 | /// Paths given on the command line, as paths of the workspace. |
| 178 | fn workspace_paths(workspace: &Workspace<'_>, given: &[PathBuf]) -> Result<Vec<Vec<u8>>> { |
| 179 | let root = std::fs::canonicalize(workspace.dir()) |
| 180 | .with_context(|| format!("cannot open {}", workspace.dir().display()))?; |
| 181 | let cwd = std::fs::canonicalize(std::env::current_dir()?)?; |
| 182 | given |
| 183 | .iter() |
| 184 | .map(|path| Ok(braid_wc::workspace_path(&root, &cwd, path)?)) |
| 185 | .collect() |
| 186 | } |
| 187 | |
| 188 | fn show(path: &[u8]) -> String { |
| 189 | String::from_utf8_lossy(path).into_owned() |
| 190 | } |
| 191 | |
| 192 | /// `1 path`, `3 paths`. |
| 193 | fn count(n: usize, noun: &str) -> String { |
| 194 | if n == 1 { |
| 195 | format!("1 {noun}") |
| 196 | } else { |
| 197 | format!("{n} {noun}s") |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | fn hex(id: Option<ObjectId>) -> Value { |
| 202 | id.map_or(Value::Null, |id| Value::String(id.to_hex())) |
| 203 | } |
| 204 | |
| 205 | fn short(id: Option<ObjectId>) -> String { |
| 206 | id.map_or_else(|| "(none)".to_owned(), |id| id.short()) |
| 207 | } |
| 208 | |
| 209 | pub(crate) fn workspace(cli: &Cli, action: &WorkspaceAction) -> Result<ExitCode> { |
| 210 | match action { |
| 211 | WorkspaceAction::Add { |
| 212 | name, |
| 213 | path, |
| 214 | at, |
| 215 | track, |
| 216 | } => { |
| 217 | let repo = open_repo(cli)?; |
| 218 | let at = match at { |
| 219 | Some(revision) => Some(resolve_changeset(&repo, revision)?), |
| 220 | None => repo.store().refs()?.get(track), |
| 221 | }; |
| 222 | let dir = match path { |
| 223 | Some(path) => path.clone(), |
| 224 | None => std::env::current_dir()?.join(name), |
| 225 | }; |
| 226 | let (workspace, files) = Workspace::create(&repo, name, &dir, at, track)?; |
| 227 | if cli.json { |
| 228 | print_json(&json!({ |
| 229 | "name": workspace.name(), |
| 230 | "path": workspace.dir().to_string_lossy(), |
| 231 | "branch": track, |
| 232 | "base": hex(at), |
| 233 | "files": files, |
| 234 | }))?; |
| 235 | } else { |
| 236 | println!( |
| 237 | "Created workspace {} in {} on {track} at {}, {}", |
| 238 | workspace.name(), |
| 239 | workspace.dir().display(), |
| 240 | short(at), |
| 241 | count(files, "file") |
| 242 | ); |
| 243 | } |
| 244 | } |
| 245 | WorkspaceAction::List => { |
| 246 | let repo = open_repo(cli)?; |
| 247 | let all = Workspace::list(&repo)?; |
| 248 | if cli.json { |
| 249 | let items: Vec<Value> = all |
| 250 | .iter() |
| 251 | .map(|(name, state)| { |
| 252 | json!({ |
| 253 | "name": name, |
| 254 | "path": state.path.to_string_lossy(), |
| 255 | "branch": state.branch, |
| 256 | "base": hex(state.base), |
| 257 | "rebase": state.rebase.is_some(), |
| 258 | "present": state.path.join(braid_repo::DIR).is_file(), |
| 259 | }) |
| 260 | }) |
| 261 | .collect(); |
| 262 | print_json(&Value::Array(items))?; |
| 263 | } else { |
| 264 | for (name, state) in &all { |
| 265 | println!( |
| 266 | "{name} {} {} {}{}", |
| 267 | state.branch, |
| 268 | short(state.base), |
| 269 | state.path.display(), |
| 270 | if state.rebase.is_some() { |
| 271 | " (rebase in progress)" |
| 272 | } else { |
| 273 | "" |
| 274 | } |
| 275 | ); |
| 276 | } |
| 277 | } |
| 278 | } |
| 279 | WorkspaceAction::Remove { name, force } => { |
| 280 | let repo = open_repo(cli)?; |
| 281 | Workspace::remove(&repo, name, *force)?; |
| 282 | if cli.json { |
| 283 | print_json(&json!({ "name": name, "removed": true }))?; |
| 284 | } else { |
| 285 | println!("Removed workspace {name}"); |
| 286 | } |
| 287 | } |
| 288 | } |
| 289 | Ok(ExitCode::SUCCESS) |
| 290 | } |
| 291 | |
| 292 | pub(crate) fn status(cli: &Cli) -> Result<ExitCode> { |
| 293 | let target = Target::find(cli)?; |
| 294 | let workspace = target.open()?; |
| 295 | let report = workspace.status()?; |
| 296 | let state = &report.state; |
| 297 | let status = &report.status; |
| 298 | if cli.json { |
| 299 | let by_kind = |kind: braid_wc::ChangeKind| -> Vec<String> { |
| 300 | status |
| 301 | .changes |
| 302 | .iter() |
| 303 | .filter(|change| change.kind == kind) |
| 304 | .map(|change| show(&change.path)) |
| 305 | .collect() |
| 306 | }; |
| 307 | let rebase = state.rebase.as_ref().map(|rebase| { |
| 308 | json!({ |
| 309 | "change": rebase.change.to_hex(), |
| 310 | "onto": rebase.onto.to_hex(), |
| 311 | "pending": rebase.pending.iter().map(ObjectId::to_hex).collect::<Vec<_>>(), |
| 312 | "conflicts": report.conflicts.iter().map(|(conflict, remain)| json!({ |
| 313 | "path": show(&conflict.path), |
| 314 | "kind": conflict.code, |
| 315 | "markers": conflict.markers, |
| 316 | "markers_remain": remain, |
| 317 | "resolved": conflict.resolved, |
| 318 | })).collect::<Vec<_>>(), |
| 319 | }) |
| 320 | }); |
| 321 | print_json(&json!({ |
| 322 | "workspace": workspace.name(), |
| 323 | "path": workspace.dir().to_string_lossy(), |
| 324 | "branch": state.branch, |
| 325 | "base": hex(state.base), |
| 326 | "head": hex(report.head), |
| 327 | "clean": status.is_clean(), |
| 328 | "unlanded": report.unlanded.iter().map(ObjectId::to_hex).collect::<Vec<_>>(), |
| 329 | "changes": status.changes.iter().map(|change| { |
| 330 | let mut value = change_json(&braid_format::Change { |
| 331 | path: change.path.clone(), |
| 332 | op: change.op.clone(), |
| 333 | }); |
| 334 | value["kind"] = Value::String(change.kind.name().to_owned()); |
| 335 | value |
| 336 | }).collect::<Vec<_>>(), |
| 337 | "added": by_kind(braid_wc::ChangeKind::Added), |
| 338 | "modified": by_kind(braid_wc::ChangeKind::Modified), |
| 339 | "deleted": by_kind(braid_wc::ChangeKind::Deleted), |
| 340 | "typechanged": by_kind(braid_wc::ChangeKind::TypeChanged), |
| 341 | "needs_track": status.needs_track.iter().map(|p| show(p)).collect::<Vec<_>>(), |
| 342 | "rebase": rebase, |
| 343 | }))?; |
| 344 | return Ok(ExitCode::SUCCESS); |
| 345 | } |
| 346 | let mut out = io::stdout().lock(); |
| 347 | writeln!( |
| 348 | out, |
| 349 | "Workspace {} on {}, at {}", |
| 350 | workspace.name(), |
| 351 | state.branch, |
| 352 | short(state.base) |
| 353 | )?; |
| 354 | if !report.unlanded.is_empty() { |
| 355 | writeln!( |
| 356 | out, |
| 357 | "{} not landed on {}", |
| 358 | count(report.unlanded.len(), "changeset"), |
| 359 | state.branch |
| 360 | )?; |
| 361 | } else if report.head.is_some() && report.head != state.base { |
| 362 | writeln!( |
| 363 | out, |
| 364 | "{} has moved on to {}: run `braid update`", |
| 365 | state.branch, |
| 366 | short(report.head) |
| 367 | )?; |
| 368 | } |
| 369 | if let Some(rebase) = &state.rebase { |
| 370 | writeln!( |
| 371 | out, |
| 372 | "Rebase of {} in progress onto {}; resolve, then `braid commit`", |
| 373 | rebase.change.short(), |
| 374 | rebase.onto.short() |
| 375 | )?; |
| 376 | for (conflict, remain) in &report.conflicts { |
| 377 | let note = if conflict.markers { |
| 378 | if *remain { "markers remain" } else { "edited" } |
| 379 | } else if conflict.resolved { |
| 380 | "resolved" |
| 381 | } else { |
| 382 | "run `braid resolve` once settled" |
| 383 | }; |
| 384 | writeln!( |
| 385 | out, |
| 386 | " {:<13} {} ({note})", |
| 387 | conflict.code, |
| 388 | show(&conflict.path) |
| 389 | )?; |
| 390 | } |
| 391 | } |
| 392 | if status.is_clean() { |
| 393 | writeln!(out, "Nothing to commit.")?; |
| 394 | } else { |
| 395 | writeln!(out, "Changes:")?; |
| 396 | for change in &status.changes { |
| 397 | writeln!(out, " {:<11} {}", change.kind.name(), show(&change.path))?; |
| 398 | } |
| 399 | } |
| 400 | if !status.needs_track.is_empty() { |
| 401 | writeln!(out, "New files not committed until `braid track <path>`:")?; |
| 402 | for path in &status.needs_track { |
| 403 | writeln!(out, " {}", show(path))?; |
| 404 | } |
| 405 | } |
| 406 | Ok(ExitCode::SUCCESS) |
| 407 | } |
| 408 | |
| 409 | fn progress_json(progress: &RebaseProgress) -> Value { |
| 410 | match progress { |
| 411 | RebaseProgress::None => Value::Null, |
| 412 | RebaseProgress::Finished { tip } => json!({ "outcome": "finished", "tip": tip.to_hex() }), |
| 413 | RebaseProgress::Stopped { change, conflicts } => json!({ |
| 414 | "outcome": "conflicts", |
| 415 | "change": change.to_hex(), |
| 416 | "conflicts": conflicts.iter().map(conflict_json).collect::<Vec<_>>(), |
| 417 | }), |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | pub(crate) fn commit(cli: &Cli, args: &CommitArgs) -> Result<ExitCode> { |
| 422 | let target = Target::find(cli)?; |
| 423 | let workspace = target.open()?; |
| 424 | let request = CommitRequest { |
| 425 | message: args.message.as_ref().map(|m| m.as_bytes().to_vec()), |
| 426 | paths: workspace_paths(&workspace, &args.paths)?, |
| 427 | author: None, |
| 428 | committer: identity(&args.identity, &target.repo)?, |
| 429 | force: args.force, |
| 430 | }; |
| 431 | let outcome = workspace.commit(&request)?; |
| 432 | let stopped = matches!(outcome.rebase, RebaseProgress::Stopped { .. }); |
| 433 | if cli.json { |
| 434 | print_json(&json!({ |
| 435 | "changeset": hex(outcome.changeset), |
| 436 | "changes": outcome.changes, |
| 437 | "rebase": progress_json(&outcome.rebase), |
| 438 | }))?; |
| 439 | } else { |
| 440 | match outcome.changeset { |
| 441 | Some(id) => println!( |
| 442 | "Committed {} ({})", |
| 443 | id.short(), |
| 444 | count(outcome.changes, "path") |
| 445 | ), |
| 446 | None => println!("Nothing left to record for this changeset"), |
| 447 | } |
| 448 | match &outcome.rebase { |
| 449 | RebaseProgress::None => {} |
| 450 | RebaseProgress::Finished { tip } => { |
| 451 | println!( |
| 452 | "Rebase finished at {}; `braid land` when ready", |
| 453 | tip.short() |
| 454 | ); |
| 455 | } |
| 456 | RebaseProgress::Stopped { change, conflicts } => { |
| 457 | println!("The next changeset, {}, conflicts too:", change.short()); |
| 458 | print_conflicts(conflicts); |
| 459 | } |
| 460 | } |
| 461 | } |
| 462 | Ok(if stopped { |
| 463 | ExitCode::from(CONFLICTS) |
| 464 | } else { |
| 465 | ExitCode::SUCCESS |
| 466 | }) |
| 467 | } |
| 468 | |
| 469 | /// Prints a landing's report and returns the exit status it calls for. |
| 470 | fn report_landing(cli: &Cli, report: &LandReport) -> Result<ExitCode> { |
| 471 | let (outcome, changeset) = match &report.landed { |
| 472 | Landed::Nothing => ("nothing", None), |
| 473 | Landed::FastForward(id) => ("fast-forward", Some(*id)), |
| 474 | Landed::Rebased(id) => ("rebased", Some(*id)), |
| 475 | Landed::AlreadyApplied => ("already-applied", None), |
| 476 | Landed::Conflicts { change, .. } => ("conflicts", Some(*change)), |
| 477 | }; |
| 478 | let conflicts: &[Conflict] = match &report.landed { |
| 479 | Landed::Conflicts { conflicts, .. } => conflicts, |
| 480 | _ => &[], |
| 481 | }; |
| 482 | if cli.json { |
| 483 | print_json(&json!({ |
| 484 | "branch": report.branch, |
| 485 | "outcome": outcome, |
| 486 | "previous": hex(report.previous), |
| 487 | "head": hex(report.head()), |
| 488 | "changeset": hex(changeset), |
| 489 | "operation": report.operation, |
| 490 | "conflicts": conflicts.iter().map(conflict_json).collect::<Vec<_>>(), |
| 491 | }))?; |
| 492 | } else { |
| 493 | match &report.landed { |
| 494 | Landed::Nothing => println!("Nothing to land on {}", report.branch), |
| 495 | Landed::FastForward(id) => { |
| 496 | println!("Landed {} on {} (fast-forward)", id.short(), report.branch); |
| 497 | } |
| 498 | Landed::Rebased(id) => println!( |
| 499 | "Landed on {} as {}, rebased onto {}", |
| 500 | report.branch, |
| 501 | id.short(), |
| 502 | short(report.previous) |
| 503 | ), |
| 504 | Landed::AlreadyApplied => println!("{} already has these changes", report.branch), |
| 505 | Landed::Conflicts { change, conflicts } => { |
| 506 | println!( |
| 507 | "{} conflicts with {} at {}; {} did not move:", |
| 508 | change.short(), |
| 509 | report.branch, |
| 510 | short(report.previous), |
| 511 | report.branch |
| 512 | ); |
| 513 | print_conflicts(conflicts); |
| 514 | } |
| 515 | } |
| 516 | } |
| 517 | Ok(if conflicts.is_empty() { |
| 518 | ExitCode::SUCCESS |
| 519 | } else { |
| 520 | ExitCode::from(CONFLICTS) |
| 521 | }) |
| 522 | } |
| 523 | |
| 524 | pub(crate) fn land(cli: &Cli, args: &LandArgs) -> Result<ExitCode> { |
| 525 | let target = Target::find(cli)?; |
| 526 | let workspace = target.open()?; |
| 527 | let committer = identity(&args.identity, &target.repo)?; |
| 528 | let report = workspace.land(args.onto.as_deref(), &cli.agent, &committer)?; |
| 529 | report_landing(cli, &report) |
| 530 | } |
| 531 | |
| 532 | pub(crate) fn update(cli: &Cli, args: &IdentityArgs) -> Result<ExitCode> { |
| 533 | let target = Target::find(cli)?; |
| 534 | let workspace = target.open()?; |
| 535 | let committer = identity(args, &target.repo)?; |
| 536 | let updated = workspace.update(&committer)?; |
| 537 | let (outcome, head, base, conflicts): (&str, Option<ObjectId>, Option<ObjectId>, &[Conflict]) = |
| 538 | match &updated { |
| 539 | Updated::UpToDate => ("up-to-date", None, None, &[]), |
| 540 | Updated::Moved { head } => ("moved", Some(*head), Some(*head), &[]), |
| 541 | Updated::Rebased { head, tip } => ("rebased", Some(*head), Some(*tip), &[]), |
| 542 | Updated::Conflicts { |
| 543 | head, conflicts, .. |
| 544 | } => ("conflicts", Some(*head), Some(*head), conflicts), |
| 545 | }; |
| 546 | if cli.json { |
| 547 | let change = match &updated { |
| 548 | Updated::Conflicts { change, .. } => Some(*change), |
| 549 | _ => None, |
| 550 | }; |
| 551 | print_json(&json!({ |
| 552 | "outcome": outcome, |
| 553 | "head": hex(head), |
| 554 | "base": hex(base.or(workspace.state()?.base)), |
| 555 | "change": hex(change), |
| 556 | "conflicts": conflicts.iter().map(conflict_json).collect::<Vec<_>>(), |
| 557 | }))?; |
| 558 | } else { |
| 559 | match &updated { |
| 560 | Updated::UpToDate => println!("Up to date"), |
| 561 | Updated::Moved { head } => println!("Moved to {}", head.short()), |
| 562 | Updated::Rebased { head, tip } => { |
| 563 | println!("Rebased onto {}; now at {}", head.short(), tip.short()); |
| 564 | } |
| 565 | Updated::Conflicts { |
| 566 | head, |
| 567 | change, |
| 568 | conflicts, |
| 569 | } => { |
| 570 | println!( |
| 571 | "{} conflicts with {}; the working copy has the merge so far:", |
| 572 | change.short(), |
| 573 | head.short() |
| 574 | ); |
| 575 | print_conflicts(conflicts); |
| 576 | println!( |
| 577 | "Fix the files, `braid resolve` the other conflicts, then `braid commit`." |
| 578 | ); |
| 579 | } |
| 580 | } |
| 581 | } |
| 582 | Ok(if conflicts.is_empty() { |
| 583 | ExitCode::SUCCESS |
| 584 | } else { |
| 585 | ExitCode::from(CONFLICTS) |
| 586 | }) |
| 587 | } |
| 588 | |
| 589 | pub(crate) fn resolve(cli: &Cli, paths: &[PathBuf]) -> Result<ExitCode> { |
| 590 | let target = Target::find(cli)?; |
| 591 | let workspace = target.open()?; |
| 592 | let paths = workspace_paths(&workspace, paths)?; |
| 593 | let remaining = workspace.resolve(&paths)?; |
| 594 | if cli.json { |
| 595 | print_json(&json!({ |
| 596 | "resolved": paths.iter().map(|p| show(p)).collect::<Vec<_>>(), |
| 597 | "remaining": remaining.iter().map(|c| show(&c.path)).collect::<Vec<_>>(), |
| 598 | }))?; |
| 599 | } else if remaining.is_empty() { |
| 600 | println!("Every conflict needing `braid resolve` is resolved"); |
| 601 | } else { |
| 602 | println!("Still unresolved:"); |
| 603 | for conflict in &remaining { |
| 604 | println!(" {:<13} {}", conflict.code, show(&conflict.path)); |
| 605 | } |
| 606 | } |
| 607 | Ok(ExitCode::SUCCESS) |
| 608 | } |
| 609 | |
| 610 | pub(crate) fn track(cli: &Cli, paths: &[PathBuf]) -> Result<ExitCode> { |
| 611 | let target = Target::find(cli)?; |
| 612 | let workspace = target.open()?; |
| 613 | let paths = workspace_paths(&workspace, paths)?; |
| 614 | if paths.iter().any(Vec::is_empty) { |
| 615 | bail!("give files or directories inside the workspace, not its root"); |
| 616 | } |
| 617 | let marks = workspace.track(&paths)?; |
| 618 | if cli.json { |
| 619 | print_json(&json!({ "tracked": marks.iter().map(|p| show(p)).collect::<Vec<_>>() }))?; |
| 620 | } else { |
| 621 | for path in &paths { |
| 622 | println!("New files at {} will be committed", show(path)); |
| 623 | } |
| 624 | } |
| 625 | Ok(ExitCode::SUCCESS) |
| 626 | } |
| 627 | |
| 628 | /// The bytes of a command-line argument. |
| 629 | fn arg_bytes(arg: &OsStr) -> Result<Vec<u8>> { |
| 630 | braid_repo::text::path_bytes(Path::new(arg)) |
| 631 | .with_context(|| format!("{} is not valid here", arg.to_string_lossy())) |
| 632 | } |
| 633 | |
| 634 | pub(crate) fn change(cli: &Cli, action: &ChangeAction) -> Result<ExitCode> { |
| 635 | // The output is JSON whether or not `--json` is given. |
| 636 | let ChangeAction::Create(args) = action; |
| 637 | let repo = open_repo(cli)?; |
| 638 | let base = match args.base.as_str() { |
| 639 | "none" => None, |
| 640 | revision => Some(resolve_changeset(&repo, revision)?), |
| 641 | }; |
| 642 | let mut stdin_used = false; |
| 643 | let mut sets = Vec::with_capacity(args.sets.len()); |
| 644 | for set in &args.sets { |
| 645 | let bytes = arg_bytes(set)?; |
| 646 | let at = bytes |
| 647 | .windows(2) |
| 648 | .position(|pair| pair == b"=@") |
| 649 | .with_context(|| { |
| 650 | format!( |
| 651 | "--set takes PATH=@FILE or PATH=@-, not {}", |
| 652 | set.to_string_lossy() |
| 653 | ) |
| 654 | })?; |
| 655 | let (path, source) = (bytes[..at].to_vec(), &bytes[at + 2..]); |
| 656 | let content = if source == b"-" { |
| 657 | if stdin_used { |
| 658 | bail!("only one --set can read standard input"); |
| 659 | } |
| 660 | stdin_used = true; |
| 661 | let mut content = Vec::new(); |
| 662 | io::stdin() |
| 663 | .lock() |
| 664 | .read_to_end(&mut content) |
| 665 | .context("cannot read standard input")?; |
| 666 | content |
| 667 | } else { |
| 668 | let file = braid_repo::text::path_from_bytes(source).context("invalid file name")?; |
| 669 | std::fs::read(&file).with_context(|| format!("cannot read {}", file.display()))? |
| 670 | }; |
| 671 | sets.push((path, content)); |
| 672 | } |
| 673 | let deletes = args |
| 674 | .deletes |
| 675 | .iter() |
| 676 | .map(|path| arg_bytes(path)) |
| 677 | .collect::<Result<Vec<_>>>()?; |
| 678 | let mut expects = Vec::with_capacity(args.expects.len()); |
| 679 | for expect in &args.expects { |
| 680 | let bytes = arg_bytes(expect)?; |
| 681 | let at = bytes |
| 682 | .iter() |
| 683 | .rposition(|byte| *byte == b'=') |
| 684 | .with_context(|| { |
| 685 | format!( |
| 686 | "--expect takes PATH=ID or PATH=absent, not {}", |
| 687 | expect.to_string_lossy() |
| 688 | ) |
| 689 | })?; |
| 690 | let value = std::str::from_utf8(&bytes[at + 1..]).unwrap_or(""); |
| 691 | let expected = match value { |
| 692 | "absent" => Expect::Absent, |
| 693 | id => Expect::Blob(id.parse().with_context(|| { |
| 694 | format!("--expect needs a full blob id or \"absent\", not {id:?}") |
| 695 | })?), |
| 696 | }; |
| 697 | expects.push((bytes[..at].to_vec(), expected)); |
| 698 | } |
| 699 | let author = identity(&args.identity, &repo)?; |
| 700 | let request = ChangeRequest { |
| 701 | base, |
| 702 | sets, |
| 703 | deletes, |
| 704 | expects, |
| 705 | message: args.message.as_bytes().to_vec(), |
| 706 | author: author.clone(), |
| 707 | }; |
| 708 | let change = braid_wc::create_change(repo.store(), &request)?; |
| 709 | let landing = match &args.land { |
| 710 | Some(branch) => Some(braid_wc::land_change( |
| 711 | repo.store(), |
| 712 | branch, |
| 713 | change, |
| 714 | &cli.agent, |
| 715 | &author, |
| 716 | )?), |
| 717 | None => None, |
| 718 | }; |
| 719 | let conflicted = matches!( |
| 720 | landing.as_ref().map(|report| &report.landed), |
| 721 | Some(Landed::Conflicts { .. }) |
| 722 | ); |
| 723 | // Always JSON: this command is for agents, which want the ids. |
| 724 | let land = match &landing { |
| 725 | Some(report) => landing_json(report), |
| 726 | None => Value::Null, |
| 727 | }; |
| 728 | print_json(&json!({ |
| 729 | "change": change.to_hex(), |
| 730 | "base": hex(base), |
| 731 | "land": land, |
| 732 | }))?; |
| 733 | Ok(if conflicted { |
| 734 | ExitCode::from(CONFLICTS) |
| 735 | } else { |
| 736 | ExitCode::SUCCESS |
| 737 | }) |
| 738 | } |
| 739 | |
| 740 | fn landing_json(report: &LandReport) -> Value { |
| 741 | let outcome = match &report.landed { |
| 742 | Landed::Nothing => "nothing", |
| 743 | Landed::FastForward(_) => "fast-forward", |
| 744 | Landed::Rebased(_) => "rebased", |
| 745 | Landed::AlreadyApplied => "already-applied", |
| 746 | Landed::Conflicts { .. } => "conflicts", |
| 747 | }; |
| 748 | let conflicts: &[Conflict] = match &report.landed { |
| 749 | Landed::Conflicts { conflicts, .. } => conflicts, |
| 750 | _ => &[], |
| 751 | }; |
| 752 | json!({ |
| 753 | "branch": report.branch, |
| 754 | "outcome": outcome, |
| 755 | "previous": hex(report.previous), |
| 756 | "head": hex(report.head()), |
| 757 | "operation": report.operation, |
| 758 | "conflicts": conflicts.iter().map(conflict_json).collect::<Vec<_>>(), |
| 759 | }) |
| 760 | } |
| 761 | |
| 762 | fn entry_json(entry: &Option<EntryKind>) -> Value { |
| 763 | match entry { |
| 764 | None => Value::Null, |
| 765 | Some(EntryKind::Tree { tree }) => json!({ "kind": "tree", "tree": tree.to_hex() }), |
| 766 | Some(kind) => match ChangeOp::from_entry(kind) { |
| 767 | Some(op) => { |
| 768 | let mut value = change_json(&braid_format::Change { |
| 769 | path: Vec::new(), |
| 770 | op, |
| 771 | }); |
| 772 | if let Some(object) = value.as_object_mut() { |
| 773 | object.remove("path"); |
| 774 | if let Some(op) = object.remove("op") { |
| 775 | object.insert("kind".to_owned(), op); |
| 776 | } |
| 777 | } |
| 778 | value |
| 779 | } |
| 780 | None => Value::Null, |
| 781 | }, |
| 782 | } |
| 783 | } |
| 784 | |
| 785 | fn side_json(side: &HunkSide) -> Value { |
| 786 | json!({ |
| 787 | "start": side.lines.start, |
| 788 | "end": side.lines.end, |
| 789 | "text": String::from_utf8_lossy(&side.text), |
| 790 | }) |
| 791 | } |
| 792 | |
| 793 | /// A conflict as data: the path, the kind's code, the entries of the base, |
| 794 | /// ours (the branch head) and theirs (the change), and for content |
| 795 | /// conflicts the hunks. |
| 796 | pub(crate) fn conflict_json(conflict: &Conflict) -> Value { |
| 797 | let mut value = json!({ |
| 798 | "path": show(&conflict.path), |
| 799 | "kind": conflict.kind.code(), |
| 800 | "base": entry_json(&conflict.base), |
| 801 | "ours": entry_json(&conflict.ours), |
| 802 | "theirs": entry_json(&conflict.theirs), |
| 803 | "hunks": [], |
| 804 | }); |
| 805 | match &conflict.kind { |
| 806 | ConflictKind::Content { hunks } => { |
| 807 | value["hunks"] = hunks |
| 808 | .iter() |
| 809 | .map(|hunk| { |
| 810 | json!({ |
| 811 | "base": side_json(&hunk.base), |
| 812 | "ours": side_json(&hunk.ours), |
| 813 | "theirs": side_json(&hunk.theirs), |
| 814 | }) |
| 815 | }) |
| 816 | .collect(); |
| 817 | } |
| 818 | ConflictKind::DirectoryRemoved { directory } => { |
| 819 | value["directory"] = Value::String(show(directory)); |
| 820 | } |
| 821 | ConflictKind::Case { existing } => { |
| 822 | value["existing"] = Value::String(show(existing)); |
| 823 | } |
| 824 | _ => {} |
| 825 | } |
| 826 | value |
| 827 | } |
| 828 | |
| 829 | fn print_conflicts(conflicts: &[Conflict]) { |
| 830 | for conflict in conflicts { |
| 831 | let detail = match &conflict.kind { |
| 832 | ConflictKind::Content { hunks } if !hunks.is_empty() => { |
| 833 | format!(" ({})", count(hunks.len(), "region")) |
| 834 | } |
| 835 | ConflictKind::DirectoryRemoved { directory } => { |
| 836 | format!(" (directory {} removed)", show(directory)) |
| 837 | } |
| 838 | ConflictKind::Case { existing } => format!(" (collides with {})", show(existing)), |
| 839 | _ => String::new(), |
| 840 | }; |
| 841 | println!( |
| 842 | " {:<13} {}{detail}", |
| 843 | conflict.kind.code(), |
| 844 | show(&conflict.path) |
| 845 | ); |
| 846 | } |
| 847 | } |