//! Commands that act on the local repository and working copy. use super::format::{ author_name, deps_line, deps_of, plural, short_id, signature_line, signature_mark_of, subject_of, via, when, }; use super::json; use super::open; use super::ui; use anyhow::Result; use oxy_core::objects::ChangeKind; use oxy_core::repo::SignatureStatus; use oxy_core::repo::{render_change, ChangeStatus, Repo}; use std::io::Write; use std::path::PathBuf; pub fn init(path: Option, bare: bool, store: Option<&str>) -> Result { let path = path.unwrap_or(std::env::current_dir()?); let repo = Repo::init_new(&path, bare, store)?; println!( "{} {}oxy repository in {}", ui::done("Initialized"), if bare { "bare " } else { "" }, ui::path(repo.root().display()) ); println!( "{}", ui::kv("bookmark", ui::bookmark(&repo.config.bookmark)) ); if let Some(url) = &repo.config.storage_url { println!( "{}", ui::kv( "store", format!( "{url} (cache in {}, up to {} MiB)", ui::path(repo.root().join(".oxy/cache").display()), repo.config.storage_cache >> 20 ) ) ); } println!( "{}", ui::kv( "author", format!( "{} <{}>", ui::author(&repo.config.author_name), repo.config.author_email ) ) ); Ok(0) } fn status_tag(s: ChangeStatus) -> &'static str { match s { ChangeStatus::Added => "A", ChangeStatus::Modified => "M", ChangeStatus::Removed => "D", ChangeStatus::Renamed => "R", ChangeStatus::ModeChanged => "X", ChangeStatus::ConflictEdited => "C!", ChangeStatus::Resolved => "V", } } /// New untracked files left out of the snapshot for their size (oxygen#98): /// named, with how to keep them out quietly or take them in. fn print_skipped_large(repo: &Repo) { let skipped = repo.skipped_large(); if skipped.is_empty() { return; } let size = |n: u64| { if n >= 1 << 30 { format!("{:.1} GiB", n as f64 / (1u64 << 30) as f64) } else { format!("{:.0} MiB", n as f64 / (1u64 << 20) as f64) } }; println!(); println!( "{} {}", ui::section(ui::warn("Not tracked")), ui::dim(format!("new files over {}", size(repo.config.max_new_file))) ); for (p, n) in &skipped { println!(" {} {} {}", ui::caution(), ui::path(p), ui::dim(size(*n))); } println!( " {} {}", ui::note(), ui::dim( "to leave them out quietly, list them in .oxyignore; to track one, \ raise snapshot.max-new-file-size (oxy config snapshot.max-new-file-size 2G)" ) ); } /// Name what a checkout removed from the working copy (oxygen#102): a /// switch to a bookmark lacking files takes them off disk, which an /// editor open on the tree notices before a person reading a count does. fn print_removed(r: &oxy_core::repo::CheckoutReport) { if r.removed == 0 { return; } let more = r.removed.saturating_sub(r.removed_paths.len()); let names = r.removed_paths.join(", "); let tail = if more > 0 { format!(" and {more} more") } else { String::new() }; let lead = if r.removed >= 20 { ui::caution() } else { ui::note() }; println!( " {} {}", lead, ui::dim(format!( "removed from disk (the bookmark does not have them): {names}{tail}" )) ); } /// Folders holding a repository of their own, which oxy leaves out (oxygen#43): /// named, with how to track them. fn print_untracked_nested(repo: &Repo, nested: &[String]) { if nested.is_empty() { return; } println!(); println!( "{} {}", ui::section(ui::warn("Not tracked")), ui::dim("folders holding a repository of their own") ); for p in nested { let kind = if repo.root().join(p).join(".git").exists() { "Git" } else { "Oxygen" }; println!( " {} {} {}", ui::caution(), ui::path(format!("{p}/")), ui::dim(format!("a nested {kind} repository")) ); } println!( " {} {}", ui::note(), ui::dim( "to track one's files, remove its .git (or .oxy); to keep it a repository of its own, \ oxy submodule add URL PATH; to leave it out quietly, list it in .oxyignore" ) ); } /// The working copy's changed paths, or that it is clean. fn print_statuses(statuses: &[oxy_core::repo::PathStatus]) { if statuses.is_empty() { println!( " {} {}", ui::ok(ui::glyph("✔", "*")), ui::dim("nothing to commit, working copy clean") ); return; } println!(); for s in statuses { println!( " {} {}", ui::status_mark(status_tag(s.status)), ui::path(&s.path) ); } } /// Say when the working copy has fallen behind its own bookmark: a /// "clean" status there hid a pull that left it on old code (oxygen#89). fn print_behind(repo: &Repo) { if let Ok(Some(n)) = repo.working_copy_behind() { println!( " {} {}", ui::caution(), ui::warn(format!( "the working copy is behind {}: it lacks {} the bookmark has; oxy checkout brings it up", repo.config.bookmark, plural(n, "change") )) ); } } pub fn status(json: bool) -> Result { let repo = open()?; // Answered by the manifest alone, with no history to load (oxygen#35, // #41): a clean working copy, or one as the last snapshot left it. let known = if json { None } else { repo.status_by_manifest()? }; if let Some(statuses) = known { let (_, wc) = repo.working_copy()?; let heads = repo.bookmark_heads()?; println!( "{} {}{}working copy {}{}{}", ui::dim("On"), ui::bookmark(&repo.config.bookmark), ui::sep(), ui::id(wc.change_id.short(8)), ui::sep(), ui::dim(plural(heads.len(), "head")) ); print_behind(&repo); print_statuses(&statuses); print_untracked_nested(&repo, &repo.untracked_nested()); print_skipped_large(&repo); return Ok(0); } let sp = ui::spinner("Snapshotting the working copy…"); let snap = repo.snapshot_status("oxy status")?; let heads = { let _t = oxy_core::timing::phase("status: heads"); repo.bookmark_heads()? }; let _drop = oxy_core::timing::phase("status: print and drop"); sp.clear(); if json { println!("{}", repo.status_json(&snap)?); return Ok(if snap.base_snapshot.is_conflicted() { 2 } else { 0 }); } println!( "{} {}{}working copy {}{}{}", ui::dim("On"), ui::bookmark(&repo.config.bookmark), ui::sep(), ui::id(snap.wc.change_id.short(8)), ui::sep(), ui::dim(plural(heads.len(), "head")) ); print_behind(&repo); print_statuses(&snap.statuses); print_untracked_nested(&repo, &snap.untracked_nested); print_skipped_large(&repo); if !snap.base_snapshot.is_conflicted() { return Ok(0); } println!(); println!( "{} {}", ui::section(ui::err("Conflicts")), ui::dim("edit the marked files, or the .oxy-conflict-N candidates, then commit") ); for c in &snap.base_snapshot.tree.conflicts { println!(" {} tree: {c:?}", ui::err(ui::glyph("✱", "!"))); } for (p, f) in &snap.base_snapshot.files { if f.is_conflicted() { let state = match snap .statuses .iter() .find(|s| s.path == *p) .map(|s| s.status) { Some(ChangeStatus::Resolved) => { ui::ok(format!("{} resolved in working copy", ui::glyph("✔", "*"))) } Some(ChangeStatus::ConflictEdited) => { ui::warn(format!("{} markers remain", ui::glyph("‼", "!"))) } _ => ui::err(format!("{} unresolved", ui::glyph("✱", "!"))), }; println!(" {} {state}", ui::path(p)); } } Ok(2) } pub fn commit( message: &str, depends_on: &[String], paths: &[String], interactive: bool, hunks: &[usize], ) -> Result { let repo = open()?; let mut deps = Vec::new(); for d in depends_on { deps.push(repo.resolve_change(d)?); } let selection = if !hunks.is_empty() { oxy_core::repo::Selection::Hunks(hunks.to_vec()) } else if interactive { let (_, hunks) = repo.hunks()?; if hunks.is_empty() { anyhow::bail!("nothing to commit: the working copy matches its base"); } let hunks: Vec<_> = hunks .into_iter() .filter(|h| { paths.is_empty() || paths.iter().any(|p| { h.path == *p || h.path.starts_with(&format!("{}/", p.trim_end_matches('/'))) }) }) .collect(); let mut chosen = Vec::new(); let stdin = std::io::stdin(); let mut take_rest = false; for (n, h) in hunks.iter().enumerate() { if take_rest { chosen.push(h.index); continue; } println!( "{} {} {}", ui::section(format!("hunk {} of {}", n + 1, hunks.len())), ui::path(&h.path), ui::dim(format!("(#{})", h.index)) ); for line in h.text.lines() { let styled = if line.starts_with('+') { ui::ok(line) } else if line.starts_with('-') { ui::err(line) } else { ui::dim(line) }; println!(" {styled}"); } loop { print!( "{} ", ui::warn("Commit this hunk? [y]es [n]o [a]ll remaining [q]uit:") ); use std::io::Write as _; std::io::stdout().flush()?; let mut answer = String::new(); if stdin.read_line(&mut answer)? == 0 { anyhow::bail!("aborted"); } match answer.trim() { "y" | "Y" => { chosen.push(h.index); break; } "n" | "N" | "" => break, "a" | "A" => { chosen.push(h.index); take_rest = true; break; } "q" | "Q" => anyhow::bail!("aborted; nothing committed"), _ => continue, } } } if chosen.is_empty() { anyhow::bail!("no hunks chosen; nothing committed"); } oxy_core::repo::Selection::Hunks(chosen) } else if paths.is_empty() { oxy_core::repo::Selection::All } else { oxy_core::repo::Selection::Paths(paths.to_vec()) }; let sp = ui::spinner("Committing…"); let (h, partial) = repo.commit_selection_partial(message, &deps, &selection)?; // The metadata only: a first commit's change holds the whole tree. let meta = repo.store().get_change_meta(&h)?; sp.done(&format!( "{} {} {} {}", ui::done("Committed"), ui::id(meta.change_id.short(8)), ui::hash(format!("#{}", h.short(12))), ui::subject(subject_of(message)) )); print_untracked_nested(&repo, &repo.untracked_nested()); print_skipped_large(&repo); // Only a commit that took part of the working copy leaves anything. if partial { let rest = repo.snapshot_status("oxy commit")?; if !rest.statuses.is_empty() { println!( " {} {}", ui::note(), ui::dim(format!( "{} left uncommitted", plural(rest.statuses.len(), "path") )) ); } } where_now(&repo); Ok(0) } pub fn blame(path: &str, json: bool) -> Result { let repo = open()?; let lines = repo.blame(path)?; if json { let items = lines.iter().map(|l| { format!( "{{\"line\":{},\"change_id\":{},\"hash\":{},\"index\":{},\"author\":{},\"when_ms\":{}}}", l.line, oxy_core::repo::json_str(&l.change_id.to_hex()), oxy_core::repo::json_str(&l.hash.to_hex()), l.index, oxy_core::repo::json_str(&l.author), l.when_ms ) }); println!("{}", oxy_core::repo::json_array(items)); return Ok(0); } let width = lines .iter() .map(|l| l.author.chars().count()) .max() .unwrap_or(0) .min(20); let digits = lines.len().to_string().len(); let _t = oxy_core::timing::phase("blame: print"); // Most lines share their change with many others: each change's id, // author and age are formatted once, and the lines go out through one // buffered lock on stdout. let mut prefix: std::collections::HashMap = std::collections::HashMap::new(); let bar = ui::dim(ui::glyph("│", "|")); let mut out = std::io::BufWriter::with_capacity(1 << 16, std::io::stdout().lock()); for l in &lines { let p = prefix.entry(l.hash).or_insert_with(|| { let author: String = l.author.chars().take(20).collect(); format!( "{} {} {}", ui::id(l.change_id.short(8)), ui::author(format!("{author:digits$}{bar} {}", l.line, text.trim_end_matches('\n') ) .is_err() { // A closed pipe (blame | head): stop quietly. return Ok(0); } } let _ = out.flush(); Ok(0) } fn bisect_report(repo: &Repo, step: &oxy_core::repo::BisectStep) -> Result { use oxy_core::repo::BisectStep::*; match step { NeedMarks { good, bad } => { println!( "{} {} {}", ui::note(), ui::dim(format!("{good} good, {bad} bad;")), ui::dim(if *good == 0 { "mark a known-good change or bookmark: oxy bisect good CHANGE" } else { "mark a known-bad change or bookmark: oxy bisect bad CHANGE" }) ); Ok(0) } Testing { heads, remaining, steps_left, } => { println!( "{} {} {}", ui::done("Testing"), ui::dim(format!( "{} in the state under test;", plural(heads.len(), "head") )), ui::dim(format!( "{remaining} candidates left, about {steps_left} more steps" )) ); println!( " {} {}", ui::note(), ui::dim("run your test, then oxy bisect good | bad | skip") ); Ok(0) } Found { culprit } => { let c = repo.store().get_change(culprit)?; println!( "{} {} {} {}", ui::done("Found"), ui::id(short_id(&c)), ui::hash(format!("#{}", culprit.short(12))), ui::subject(subject_of(&c.message)) ); println!(" {} {}", ui::note(), ui::dim("the first change whose inclusion makes the state bad; oxy bisect reset to return")); Ok(0) } Inconclusive { candidates } => { println!( "{} {}", ui::caution(), ui::warn(format!( "every remaining candidate was skipped ({}); oxy bisect reset to return", plural(candidates.len(), "change") )) ); Ok(1) } } } pub fn bisect_start() -> Result { let repo = open()?; repo.bisect_start()?; println!( "{} bisect; {}", ui::done("Started"), ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE") ); Ok(0) } pub fn bisect_mark(good: Option, changes: &[String]) -> Result { let repo = open()?; let mut heads = Vec::new(); for c in changes { heads.extend(repo.resolve_heads(c)?); } let step = repo.bisect_mark(good, &heads)?; bisect_report(&repo, &step) } pub fn bisect_run(command: &[String]) -> Result { let repo = open()?; let step = repo.bisect_run(command)?; bisect_report(&repo, &step) } pub fn bisect_status(as_json: bool) -> Result { let repo = open()?; if as_json { use oxy_core::repo::BisectStep::*; let v = match repo.bisect_status()? { None => "null".to_string(), Some(NeedMarks { good, bad }) => json::obj([ ("state", json::s("need-marks")), ("good", json::n(good)), ("bad", json::n(bad)), ]), Some(Testing { heads, remaining, steps_left, }) => json::obj([ ("state", json::s("testing")), ("heads", json::hashes(&heads)), ("remaining", json::n(remaining)), ("steps_left", json::n(steps_left)), ]), Some(Found { culprit }) => json::obj([ ("state", json::s("found")), ("culprit", json::s(&culprit.to_hex())), ]), Some(Inconclusive { candidates }) => json::obj([ ("state", json::s("inconclusive")), ("candidates", json::hashes(&candidates)), ]), }; println!("{v}"); return Ok(0); } match repo.bisect_status()? { None => { println!("{}", ui::dim("No bisect in progress.")); Ok(0) } Some(step) => bisect_report(&repo, &step), } } pub fn bisect_reset() -> Result { let repo = open()?; repo.bisect_reset()?; println!("{} bisect; working copy restored", ui::done("Reset")); Ok(0) } /// The log: one entry per change, newest first, joined by a rail. The /// default view is the subject and a metadata line; `verbose` adds the full /// message, dependencies, and the authenticating key. fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result { Ok(match repo.authenticate_change(h)? { SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]), SignatureStatus::Valid { key, name, email, sealed, revoked, } => json::obj([ ("status", json::s(if sealed { "sealed" } else { "signed" })), ("key", json::s(&key.to_hex())), ("name", json::s(&name)), ("email", json::s(&email)), ("revoked", json::b(revoked)), ]), SignatureStatus::Invalid(why) => { json::obj([("status", json::s("invalid")), ("reason", json::s(&why))]) } }) } fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result { let c = &e.change; Ok(json::obj([ ("hash", json::s(&e.hash.to_hex())), ("change_id", json::s(&c.change_id.to_hex())), ("author", json::s(&author_name(repo, c))), ("author_key", json::s(&c.author.to_hex())), ( "via", match via( repo, &repo.authenticate_change_known(&e.hash, Some(c))?, &c.author, ) { Some(v) => json::obj([ ("name", json::s(&v.name)), ("email", json::s(&v.email)), ("key", json::s(&v.key.to_hex())), ("scope", json::opt(v.scope.as_deref(), json::s)), ("expires_ms", json::opt(v.expires, json::n)), ("revoked", json::b(v.revoked)), ]), None => "null".to_string(), }, ), ("when_ms", json::n(c.hlc.wall_ms)), ("message", json::s(&c.message)), ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())), ("deps", json::hashes(&c.deps)), ("head", json::b(e.is_head)), ("working_copy", json::b(e.is_working_copy)), ( "signature", if e.is_working_copy { "null".into() } else { signature_json(repo, &e.hash)? }, ), ])) } /// `START,END:PATH` for `oxy log -L`. fn parse_line_range(spec: &str) -> Result<(usize, usize, &str)> { let bad = || anyhow::anyhow!("-L {spec}: expected START,END:PATH, as 10,24:src/lib.rs"); let (range, path) = spec.split_once(':').ok_or_else(bad)?; let (a, b) = range.split_once(',').ok_or_else(bad)?; Ok(( a.trim().parse().map_err(|_| bad())?, b.trim().parse().map_err(|_| bad())?, path, )) } pub fn log( revset: Option<&str>, limit: Option, verbose: bool, path: Option<&str>, lines: Option<&str>, as_json: bool, ) -> Result { let repo = open()?; // Whether the working copy is clean and conflicted: from the manifest // when it proves the working copy clean, else from a snapshot. // The working copy as last recorded, without looking at the files (as // Git's log does not): whether its change holds edits, and whether its // base was conflicted. `oxy status` is what checks the disk. let conflicted = !repo.is_at_op() && repo.recorded_conflicted()?; let listing = oxy_core::timing::phase("log: entries"); let entries = match (path, lines) { _ if revset.is_some() => repo.log_revset(revset.unwrap_or_default())?, (_, Some(spec)) => { let (first, last, p) = parse_line_range(spec)?; let (_, wc) = repo.working_copy()?; let base = repo.load_state_history(&wc.deps)?.maximal(&wc.deps); repo.line_history(&base, p, first, last)? } (Some(p), None) => repo.log_for_path(p)?, (None, None) => repo.log()?, }; drop(listing); let _print = oxy_core::timing::phase("log: print"); if as_json { let shown = limit.unwrap_or(entries.len()).min(entries.len()); let mut items = Vec::new(); for e in entries.iter().take(shown) { items.push(log_entry_json(&repo, e)?); } println!( "{}", json::obj([ ("bookmark", json::s(&repo.config.bookmark)), ("total", json::n(entries.len())), ("changes", json::arr(items)) ]) ); return Ok(0); } let total = entries.len(); let shown = limit.unwrap_or(total).min(total); // Lay out a little past what is shown, so edges into the cut are drawn. let window: Vec<(ChangeHash, Vec)> = entries .iter() .take((shown + MAX_EDGE).min(total)) .map(|e| (e.hash, e.change.deps.clone())) .collect(); let rows = oxy_core::lanes::graph(&window, MAX_EDGE); // Highlight the shortest prefix that names each change: against the // whole log, which is what `resolve_change` searches. let everything; let all = if path.is_some() || lines.is_some() || revset.is_some() { everything = repo.log()?; &everything } else { &entries }; let prefixes = oxy_core::timing::phase("log: id prefixes"); let id_prefix = id_prefixes( all.iter().map(|e| e.change.change_id.0).collect(), entries.iter().take(shown).map(|e| e.change.change_id.0), ); drop(prefixes); let labels = reference_labels(&repo)?; for (e, row) in entries.iter().take(shown).zip(&rows) { let c = &e.change; let bullet = ui::log_bullet( e.is_working_copy, e.is_head, e.is_working_copy && conflicted, ); let id = c.change_id.to_hex(); let n = id_prefix.get(&c.change_id.0).copied().unwrap_or(8).min(8); let mut head = vec![format!("{}{}", ui::id(&id[..n]), ui::dim(&id[n..8]))]; head.push(ui::author(author_name(&repo, c))); head.push(ui::dim(ui::ago(c.hlc.wall_ms))); if let Some(names) = labels.get(&e.hash) { head.push(names.join(" ")); } if c.kind == ChangeKind::Resolution { head.push(ui::warn("resolution")); } if !e.is_working_copy { head.push(ui::hash(format!("#{}", e.hash.short(8)))); let status = repo.authenticate_change_known(&e.hash, Some(c))?; if let Some(agent) = via(&repo, &status, &c.author) { head.push(ui::dim(format!("via {}", agent.name))); } head.push(signature_mark_of(&status)); } println!("{}{}", node_line(row, &bullet), head.join(" ")); let subject = if e.is_working_copy && c.message.is_empty() { let edited = repo .store() .get_change(&e.hash) .is_ok_and(|w| !w.tree_ops.is_empty() || !w.edits.is_empty()); ui::dim(if edited { "(working copy, uncommitted changes)" } else { "(working copy)" }) } else if c.message.trim().is_empty() { ui::dim("(no description)") } else { subject_of(&c.message).to_string() }; println!("{}{subject}", below_line(row)); if verbose { let rail = continuation(row); if !e.is_working_copy { println!( "{rail}{}", ui::dim(format!( "{} {}", when(c.hlc.wall_ms), signature_line(&repo, &e.hash)? )) ); } if !c.deps.is_empty() { println!( "{rail}{} {}", ui::dim(ui::glyph("↳", "->")), ui::dim(deps_of(&c.deps)) ); } let body: Vec<&str> = c .message .lines() .skip(1) .skip_while(|l| l.trim().is_empty()) .collect(); for line in body { println!("{rail} {line}"); } } } if shown < total { if let Some(last) = rows.get(shown.saturating_sub(1)) { let cut: String = last .below .iter() .map(|c| match c { Cell::Blank | Cell::Elided | Cell::JoinRight => " ", _ => "~ ", }) .collect(); if cut.trim().is_empty() { println!("{}", ui::dim("~")); } else { println!("{}", ui::dim(cut.trim_end())); } } println!( "{}", ui::dim(format!( "{} {} more; pass -n to see them", ui::glyph("…", "..."), total - shown )) ); } Ok(0) } /// Rows a drawn edge may span in `oxy log`; a longer one is elided (`~`). const MAX_EDGE: usize = 12; use oxy_core::hash::ChangeHash; use oxy_core::lanes::{Cell, GraphRow}; /// A graph cell, two columns wide. fn cell(c: Cell) -> &'static str { match c { Cell::Blank => " ", Cell::Line => ui::glyph("│ ", "| "), Cell::Elided => "~ ", Cell::JoinLeft => ui::glyph("├─", "|-"), Cell::JoinPass => ui::glyph("──", "--"), Cell::JoinCross => ui::glyph("┼─", "+-"), Cell::JoinRight => ui::glyph("╯ ", "' "), } } /// The graph part of a change's own line, its bullet in its column. fn node_line(row: &GraphRow, bullet: &str) -> String { let width = row .passing .iter() .copied() .max() .unwrap_or(0) .max(row.column) + 1; let mut out = String::new(); for c in 0..width { if c == row.column { out.push_str(bullet); out.push(' '); } else if row.passing.contains(&c) { out.push_str(&ui::dim(cell(Cell::Line))); } else { out.push_str(" "); } } out.push(' '); out } /// The graph part of the line under a change: lanes carrying on, a join, /// or `~` for an elided edge. fn below_line(row: &GraphRow) -> String { let g: String = row.below.iter().map(|c| cell(*c)).collect(); format!("{} ", ui::dim(g)) } /// The graph part of any further line of a change (`-v`). fn continuation(row: &GraphRow) -> String { let g: String = row .below .iter() .map(|c| match c { Cell::Line | Cell::JoinLeft | Cell::JoinCross => cell(Cell::Line), _ => " ", }) .collect(); format!("{} ", ui::dim(g)) } /// For each hex ID, the length of its shortest prefix no other ID shares. /// The shortest prefix, in hex digits, that names each of `wanted` among /// `all`: worked out for the few shown rather than for the whole history. fn id_prefixes( mut all: Vec<[u8; 16]>, wanted: impl Iterator, ) -> std::collections::HashMap<[u8; 16], usize> { all.sort_unstable(); all.dedup(); // Hex digits two ids share at the start. let common = |a: &[u8; 16], b: &[u8; 16]| { let bytes = a.iter().zip(b).take_while(|(x, y)| x == y).count(); match (a.get(bytes), b.get(bytes)) { (Some(x), Some(y)) if x >> 4 == y >> 4 => 2 * bytes + 1, _ => 2 * bytes, } }; let mut out = std::collections::HashMap::new(); for id in wanted { let Ok(i) = all.binary_search(&id) else { continue; }; let before = i.checked_sub(1).map_or(0, |j| common(&all[j], &id)); let after = all.get(i + 1).map_or(0, |n| common(&id, n)); out.insert(id, before.max(after) + 1); } out } fn unique_prefixes(ids: impl Iterator) -> std::collections::HashMap { let mut v: Vec = ids.collect(); v.sort(); v.dedup(); let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count(); let mut out = std::collections::HashMap::with_capacity(v.len()); for i in 0..v.len() { let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 }; let after = if i + 1 < v.len() { common(&v[i], &v[i + 1]) } else { 0 }; out.insert(v[i].clone(), before.max(after) + 1); } out } /// Bookmark, remote bookmark and tag names to show beside the changes they /// point at. A name is shown on each head of its state; one with more than /// three heads names too much of the log to help, so it is left out (oxy /// bookmark list shows it). A remote bookmark at the same state as the /// local one of that name is not repeated. fn reference_labels(repo: &Repo) -> Result>> { const MAX_HEADS: usize = 3; let view = repo.view()?; let mut out: std::collections::HashMap> = Default::default(); let mut add = |heads: Vec, label: String| { if heads.len() <= MAX_HEADS { for h in heads { out.entry(h).or_default().push(label.clone()); } } }; for (name, st) in &view.bookmarks { add(repo.store().get_state(st)?.heads, ui::bookmark(name)); } for (remote, bookmarks) in &view.remotes { for (name, st) in bookmarks { if view.bookmarks.get(name) == Some(st) { continue; } add( repo.store().get_state(st)?.heads, ui::dim(format!("{remote}/{name}")), ); } } for t in repo.tags()? { add(t.heads.clone(), ui::warn(&t.name)); } Ok(out) } pub fn diff(change: Option<&str>, as_json: bool) -> Result { let repo = open()?; let hash = change.map(|c| repo.resolve_change(c)).transpose()?; if as_json { let files = repo.diff_files(hash.as_ref())?; let items = files.iter().map(|f| { json::obj([ ("path", json::s(&f.path)), ("kind", json::s(&f.kind)), ("from", json::opt(f.from.as_deref(), json::s)), ( "hunks", json::arr(f.hunks.iter().map(|h| { json::obj([ ("base_line", json::n(h.base_line)), ( "added", json::arr( h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))), ), ), ( "removed", json::arr(h.removed.iter().map(|(n, l)| { json::obj([ ("line", json::n(*n)), ("text", json::s(&String::from_utf8_lossy(l))), ]) })), ), ]) })), ), ]) }); println!( "{}", json::obj([ ("change", json::opt(hash, |h| json::s(&h.to_hex()))), ("files", json::arr(items)) ]) ); return Ok(0); } match hash { Some(h) => { let c = repo.store().get_change(&h)?; let (base, snapshot) = repo.change_base(&c)?; print!("{}", render_change(&c, &base, &snapshot)); } None => { // Nothing changed: nothing to show, and no base to load. let Some((wc, base, snapshot)) = repo.working_copy_with_base_unless_unchanged()? else { return Ok(0); }; let text = { let _t = oxy_core::timing::phase("diff: render the change"); render_change(&wc, &base, &snapshot) }; print!("{text}"); // The process ends here: freeing the base's tree and graphs // one by one would only cost time (about 27 ms on Linux). std::mem::forget((wc, base, snapshot)); } } Ok(0) } pub fn cat(path: &str, change: Option<&str>) -> Result { let repo = open()?; let heads = change.map(|c| repo.resolve_heads(c)).transpose()?; let bytes = match repo.file_at(path, heads.as_deref()) { Ok(b) => b, // -r CHANGE reads that change's dependency closure, not the // bookmark it is on: say so when the bookmark has the file // (oxygen#76). Err(e) => match change { Some(c) if !repo.view()?.bookmarks.contains_key(c) && repo.tag_heads(c)?.is_none() && repo.file_at(path, None).is_ok() => { anyhow::bail!( "{path} is not in {c}'s dependency closure (the change and what it \ depends on); it is on the bookmark: try -r {}, or --at-op OP for the \ state at an operation", repo.config.bookmark ) } _ => return Err(e.into()), }, }; use std::io::Write as _; std::io::stdout().write_all(&bytes)?; Ok(0) } pub fn root(as_json: bool) -> Result { let Ok(repo) = Repo::open(&std::env::current_dir()?) else { if as_json { println!("null"); } return Ok(1); }; if as_json { println!( "{}", json::obj([ ("root", json::s(&repo.root().to_string_lossy())), ("workspace", json::s(&repo.workspace().to_hex())), ("bookmark", json::s(&repo.config.bookmark)) ]) ); } else { println!("{}", repo.root().display()); } Ok(0) } pub fn version(as_json: bool) -> Result { if as_json { println!( "{}", json::obj([ ("version", json::s(env!("CARGO_PKG_VERSION"))), // What was built: a release's or install's `oxy describe`, // a Flow build's heads, or "local build". ("build", json::s(env!("OXY_BUILD_ID"))), ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)), ("format", json::n(2)) ]) ); } else { println!( "oxy {} (repository format 2, protocol {})", env!("OXY_VERSION_LONG"), oxy_core::protocol::PROTOCOL_VERSION ); } Ok(0) } pub fn discard(paths: &[String], hunks: &[usize]) -> Result { let repo = open()?; if paths.is_empty() && hunks.is_empty() { anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks"); } let mut n = 0; if !hunks.is_empty() { n += repo.discard_hunks(hunks)?; } if !paths.is_empty() { n += repo.discard(paths)?; } println!( "{} {} restored to the working copy's base", ui::done("Discarded"), plural(n, "path") ); Ok(0) } pub fn hunks(as_json: bool) -> Result { let repo = open()?; let (_, hunks) = repo.hunks()?; if as_json { println!( "{}", json::arr(hunks.iter().map(|h| json::obj([ ("index", json::n(h.index)), ("path", json::s(&h.path)), ("text", json::s(&h.text)) ]))) ); return Ok(0); } if hunks.is_empty() { println!( "{}", ui::dim("No hunks: the working copy matches its base.") ); } for h in &hunks { println!( "{} {}", ui::section(format!("hunk {}", h.index)), ui::path(&h.path) ); for line in h.text.lines() { let styled = if line.starts_with('+') { ui::ok(line) } else if line.starts_with('-') { ui::err(line) } else { ui::dim(line) }; println!(" {styled}"); } } Ok(0) } pub fn show(change: Option<&str>, revset: Option<&str>, as_json: bool) -> Result { let repo = open()?; repo.snapshot_status("oxy show")?; let Some(r) = revset else { let h = repo.resolve_change(change.unwrap_or("@"))?; return show_one(&repo, h, as_json, false); }; // Several changes: a JSON array, or the changes one after another. let hashes = repo.revset(r)?.hashes; if as_json { print!("["); for (i, h) in hashes.iter().enumerate() { if i > 0 { print!(","); } show_one(&repo, *h, true, true)?; } println!("]"); return Ok(0); } if hashes.is_empty() { println!("{}", ui::dim(format!("No change matches {r:?}."))); return Ok(0); } for (i, h) in hashes.iter().enumerate() { if i > 0 { println!(); } show_one(&repo, *h, false, false)?; } Ok(0) } /// One change, as `oxy show` prints it; `inline` JSON goes without its /// newline, for an array. fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool) -> Result { let c = repo.store().get_change(&h)?; if as_json { let files = repo.diff_files(Some(&h))?; let heads = repo.bookmark_heads()?; let entry = oxy_core::repo::LogEntry { hash: h, change: oxy_core::state::ChangeMeta::of(&c), is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy, is_head: heads.contains(&h), }; let mut body = log_entry_json(repo, &entry)?; body.pop(); body.push_str(&format!( ",{}:{}}}", json::s("files"), json::arr(files.iter().map(|f| json::obj([ ("path", json::s(&f.path)), ("kind", json::s(&f.kind)), ("from", json::opt(f.from.as_deref(), json::s)) ]))) )); if inline { print!("{body}"); } else { println!("{body}"); } return Ok(0); } println!( "{} {} {}", ui::section("change"), ui::id(short_id(&c)), ui::hash(format!("#{h}")) ); println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase())); // Fetched but not pulled (oxygen#56): say where it is. if let Some(at) = repo.remote_only_location(&h)? { println!( "{}", ui::kv( "only in", ui::warn(format!( "{at}: fetched, not yet in a local bookmark (oxy pull)" )) ) ); } let meta = oxy_core::state::ChangeMeta::of(&c); let status = repo.authenticate_change_known(&h, Some(&meta))?; println!("{}", ui::kv("author", ui::author(author_name(repo, &meta)))); if let Some(agent) = via(repo, &status, &meta.author) { println!("{}", ui::kv("via", agent.line())); } println!( "{}", ui::kv( "date", format!( "{} {}", when(c.hlc.wall_ms), ui::dim(format!("({})", ui::ago(c.hlc.wall_ms))) ) ) ); println!("{}", ui::kv("deps", ui::dim(deps_line(&c)))); println!("{}", ui::kv("sig", signature_line(repo, &h)?)); println!(); for line in (if c.message.is_empty() { "(no description)" } else { &c.message }) .lines() { println!(" {line}"); } println!(); print!("{}", repo.describe_change(&h)?); Ok(0) } pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result { let repo = open()?; // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout // BRANCH` is: checking its files out under another bookmark's name // made the next commit move the wrong bookmark (oxygen#60). if let [name] = changes { if *name != repo.config.bookmark && names_bookmark(&repo, name)? { drop(repo); return bookmark_switch(name, discard, carry); } } let heads = if changes.is_empty() { repo.bookmark_heads()? } else { let mut heads = Vec::new(); for c in changes { heads.extend(repo.resolve_heads(c)?); } heads }; let spec = if changes.is_empty() { repo.config.bookmark.clone() } else { changes.join(" ") }; let sp = ui::spinner(&format!("Checking out {spec}…")); let command = format!("oxy checkout {spec}"); let (r, carried) = if carry { repo.checkout_carry(&heads, &spec, &command)? } else { (repo.checkout(&heads, discard, &command)?, vec![]) }; sp.done(&format!( "{} on {}: {} written, {} removed{}", ui::done("Working copy"), ui::bookmark(&spec), plural(r.written, "file"), r.removed, if carried.is_empty() { String::new() } else { format!("; carried {}", plural(carried.len(), "changed path")) } )); print_removed(&r); for n in &r.notes { println!(" {} {n}", ui::note()); } if r.conflicted { println!( " {} {}", ui::caution(), ui::warn("this state has conflicts; see oxy status") ); } where_now(&repo); Ok(0) } pub fn resolve(as_json: bool) -> Result { let repo = open()?; let snap = repo.snapshot("oxy resolve")?; if as_json { println!("{}", repo.status_json(&snap)?); return Ok(if snap.base_snapshot.is_conflicted() { 2 } else { 0 }); } if !snap.base_snapshot.is_conflicted() { println!("The working copy's base has no conflicts."); return Ok(0); } let mut remaining = 0; for (p, f) in &snap.base_snapshot.files { if !f.is_conflicted() { continue; } match snap .statuses .iter() .find(|s| s.path == *p) .map(|s| s.status) { Some(ChangeStatus::Resolved) => println!("resolved {p}"), Some(ChangeStatus::ConflictEdited) => { remaining += 1; println!("markers {p}"); } _ => { remaining += 1; println!("unresolved {p}"); } } } for c in &snap.base_snapshot.tree.conflicts { remaining += 1; println!("tree {c:?}"); } if remaining == 0 { println!("All conflicts are resolved; `oxy commit` will record the resolution."); Ok(0) } else { Ok(2) } } pub fn undo() -> Result { let repo = open()?; let u = repo.undo()?; println!("{} {}", ui::done("Undone:"), u.command); for c in &u.changes { println!(" {} {}", ui::note(), change_words(&repo, c)); } if u.others_kept > 0 { let s = if u.others_kept == 1 { "" } else { "s" }; println!( " {} {}", ui::note(), ui::dim(format!( "{} newer operation{s} from other workspaces left as they are", u.others_kept )) ); } for (bookmark, remote) in &u.pushed { println!( " {} {}", ui::caution(), ui::warn(format!( "{remote}/{bookmark} already has what this undid: undone here only; the next push of {bookmark} needs --force to take it back there" )) ); } where_now(&repo); Ok(0) } pub fn op_log(limit: Option, as_json: bool) -> Result { let repo = open()?; let ops = repo.op_log()?; // What each operation changed, against the one before it. let changes_of = |i: usize| -> Result> { match ops.get(i + 1) { Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?), None => Ok(vec![]), } }; if as_json { let mut items = Vec::new(); for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) { let summary: Vec = changes_of(i)? .iter() .map(|c| change_words(&repo, c)) .collect(); items.push(json::obj([ ("id", json::s(&r.to_hex())), ("when_ms", json::n(op.hlc.wall_ms)), ("command", json::s(&op.command)), ("snapshot", json::b(op.is_snapshot())), ("current", json::b(i == 0)), ("changes", json::arr(summary.iter().map(|x| json::s(x)))), ])); } println!("{}", json::arr(items)); return Ok(0); } let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex())); let id = |r: &oxy_core::hash::ObjectRef| { let hex = r.to_hex(); let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12); format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12])) }; let rail = ui::dim(ui::glyph("│", "|")); let (mut i, mut shown) = (0, 0); while i < ops.len() && shown < limit.unwrap_or(usize::MAX) { let (r, op) = &ops[i]; let bullet = if i == 0 { ui::ok(ui::glyph("@", "@")) } else { ui::dim(ui::glyph("○", "o")) }; // A run of snapshots folds into one entry. let mut run = 1; while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() { run += 1; } let when = ui::dim(ui::ago(op.hlc.wall_ms)); if op.is_snapshot() { let span = if run > 1 { format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0)) } else { String::new() }; println!( "{bullet} {}{} {when}", id(r), if span.is_empty() { String::new() } else { format!(" {span}") } ); println!( "{rail} {}", ui::dim(if run == 1 { "working-copy snapshot".to_string() } else { format!("{run} working-copy snapshots") }) ); } else { println!("{bullet} {} {when}", id(r)); let words: Vec = changes_of(i)? .iter() .map(|c| change_words(&repo, c)) .collect(); let summary = if words.is_empty() { if i + 1 == ops.len() { "created the repository".to_string() } else { "no bookmark or working-copy change".to_string() } } else { words.join("; ") }; println!( "{rail} {}", if i == 0 { ui::subject(&summary) } else { summary } ); let cmd = op.command.lines().next().unwrap_or(""); let cmd: String = cmd.chars().take(100).collect(); println!("{rail} {}", ui::dim(cmd)); } i += run; shown += 1; } if i < ops.len() { println!( "{}", ui::dim(format!( "{} {} older; pass -n to see more", ui::glyph("…", "..."), plural(ops.len() - i, "operation") )) ); } Ok(0) } /// One change an operation made, in words. fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String { use oxy_core::repo::ViewChange::*; match c { BookmarkCreated { name, heads } => { format!("created bookmark {name} ({})", plural(*heads, "head")) } BookmarkDeleted { name } => format!("deleted bookmark {name}"), BookmarkMoved { name, from, to } if from == to => format!("moved {name}"), BookmarkMoved { name, from, to } => format!( "{name}: {from} {} {}", ui::glyph("→", "->"), plural(*to, "head") ), RemoteMoved { remote, name } => format!("{remote}/{name} updated"), TagCreated { name } => format!("tagged {name}"), TagDeleted { name } => format!("removed tag {name}"), Policy => "trust policy changed".to_string(), WorkingCopy { change } => match repo.store().get_change_meta(change) { Ok(m) => format!("working copy now {}", m.change_id.short(8)), Err(_) => "working copy moved".to_string(), }, } } pub fn op_restore(op: &str, discard: bool) -> Result { let repo = open()?; let sp = ui::spinner(&format!("Restoring to operation {op}…")); let r = repo.op_restore(op, discard)?; sp.done(&format!( "{} to operation {} {}", ui::done("Restored"), ui::hash(r.op.short(12)), ui::dim(r.command.lines().next().unwrap_or("")) )); println!( " {} {}", ui::note(), ui::dim(format!( "{} written, {} removed; oxy undo goes back again", plural(r.checkout.written, "file"), r.checkout.removed )) ); where_now(&repo); Ok(0) } pub fn op_revert(op: &str) -> Result { let repo = open()?; let r = repo.op_revert(op)?; let view = repo.view()?; let names: Vec = r .reverted .iter() .map(|n| { if view.bookmarks.contains_key(n) { ui::bookmark(n) } else { format!("{} (removed)", ui::bookmark(n)) } }) .collect(); println!( "{} operation {} {}", ui::done("Reverted"), ui::hash(r.op.short(12)), ui::dim(r.command.lines().next().unwrap_or("")) ); println!( " {} {}", ui::note(), ui::dim(format!("as before it: {}", names.join(", "))) ); if !r.kept.is_empty() { println!( " {} {}", ui::caution(), ui::warn(format!( "left as they are, having moved again since: {}", r.kept.join(", ") )) ); } if !r.checked_out && r.reverted.contains(&repo.config.bookmark) { println!( " {} {}", ui::note(), ui::dim("the working copy has work of its own: oxy checkout to move it") ); } where_now(&repo); Ok(0) } /// Where the working copy and bookmark are now, after a command moved /// them (as jj says "Working copy now at"). pub fn where_now(repo: &Repo) { let Ok((_, wc)) = repo.working_copy() else { return; }; let heads = repo.bookmark_heads().unwrap_or_default(); let newest = heads .iter() .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h))) .max_by_key(|(m, _)| m.hlc); println!( " {} {}", ui::dim(format!("{:<13}", "Working copy")), ui::id(wc.change_id.short(8)) ); let tail = match newest { Some((m, _)) => format!( ", newest {} {}", ui::id(m.change_id.short(8)), subject_of(&m.message) ), None => String::new(), }; println!( " {} {}: {}{tail}", ui::dim(format!("{:<13}", "Bookmark")), ui::bookmark(&repo.config.bookmark), plural(heads.len(), "head") ); } pub fn gc(now: bool, expire_snapshots: bool) -> Result { let mut repo = open()?; if expire_snapshots { repo.config.snapshot_retention_days = 0; } let sp = ui::spinner("Packing and pruning…"); let r = repo.gc_with(now, &mut |phase| sp.set(&format!("{phase}…")))?; sp.clear(); if r.packed.objects > 0 { println!( "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).", plural(r.packed.objects, "object"), r.packed.raw_bytes, r.packed.packed_bytes, 100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64 ); } println!( "{} reachable; pruned {} ({} bytes){}{}; {} present.", plural(r.reachable, "object"), plural(r.pruned.objects, "unreachable object"), r.pruned.bytes, if r.pruned.deferred > 0 { format!( "; {} deferred by the grace period (use --now)", plural(r.pruned.deferred, "object") ) } else { String::new() }, if r.merged_packs > 0 { format!("; merged {} into one", plural(r.merged_packs, "pack")) } else { String::new() }, plural(repo.store().pack_count(), "pack") ); // What earlier repacks replaced stays an hour for readers still using // it (oxygenhub#249); a collection after that deletes it. let kept = if r.retired.kept > 0 { format!( "{} retired less than an hour ago kept for readers", plural(r.retired.kept, "file") ) } else { String::new() }; if r.retired.packs + r.retired.loose > 0 { println!( "Deleted {} and {} retired by earlier repacks{}.", plural(r.retired.packs, "pack"), plural(r.retired.loose, "loose object"), if kept.is_empty() { String::new() } else { format!("; {kept}") } ); } else if !kept.is_empty() { println!("{kept}."); } Ok(0) } /// `oxy gc --remote NAME`: fold a store remote's bundles into one. pub fn gc_remote(name: &str, now: bool) -> Result { let repo = open()?; let sp = ui::spinner(&format!("Folding {name}'s bundles…")); let r = repo.gc_remote(name, now)?; sp.clear(); if r.merged > 0 { println!( "{} {} into one of {} bytes ({})", ui::done("Folded"), plural(r.merged, "bundle"), r.bundle_bytes, plural(r.changes, "change") ); } else { println!( "{} {}", ui::note(), ui::dim("nothing to fold: one bundle holds everything") ); } println!( " {} {}", ui::note(), ui::dim(format!( "removed {}{}", plural(r.deleted, "superseded bundle"), if r.deferred > 0 { format!( "; {} kept for readers that may still fetch them (use --now)", plural(r.deferred, "bundle") ) } else { String::new() } )) ); Ok(0) } /// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed). pub fn doctor(offline: bool, as_json: bool) -> Result { use oxy_core::repo::Health; let repo = open()?; let sp = ui::spinner(if offline { "Checking…" } else { "Checking, and contacting remotes…" }); let r = repo.doctor(!offline); sp.clear(); let code = if r.worst() == Health::Fail { 1 } else { 0 }; let word = |h: Health| match h { Health::Ok => "ok", Health::Warn => "warning", Health::Fail => "fail", }; if as_json { let checks: Vec = r .checks .iter() .map(|c| { json::obj([ ("area", json::s(&c.area)), ("health", json::s(word(c.health))), ("message", json::s(&c.message)), ("hint", json::opt(c.hint.as_deref(), json::s)), ]) }) .collect(); println!( "{}", json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))]) ); return Ok(code); } let mut last = ""; for c in &r.checks { if c.area != last { println!("{}", ui::section(&c.area)); last = &c.area; } let mark = match c.health { Health::Ok => ui::ok(ui::glyph("✔", "v")), Health::Warn => ui::caution(), Health::Fail => ui::err(ui::glyph("✖", "x")), }; println!(" {mark} {}", c.message); if let Some(h) = &c.hint { println!(" {} {}", ui::dim("→"), ui::dim(h)); } } let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count(); let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count(); if fails + warns == 0 { println!("{}", ui::done("Everything looks right.")); } else { println!( "{} {}, {}.", if fails > 0 { ui::err(ui::glyph("✖", "x")) } else { ui::caution() }, plural(fails, "problem"), plural(warns, "warning") ); } Ok(code) } /// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error. pub fn fsck(as_json: bool) -> Result { use oxy_core::repo::Severity; let repo = open()?; let sp = ui::spinner("Checking every object…"); let r = repo.fsck()?; sp.clear(); let code = if r.errors() > 0 { 1 } else { 0 }; if as_json { let problems: Vec = r .problems .iter() .map(|p| { json::obj([ ( "severity", json::s(match p.severity { Severity::Error => "error", Severity::Warning => "warning", }), ), ( "object", json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s), ), ("what", json::s(&p.what)), ]) }) .collect(); println!( "{}", json::obj([ ("ok", json::b(code == 0)), ("objects", json::n(r.objects)), ("ops", json::n(r.ops)), ("changes", json::n(r.changes)), ("signed", json::n(r.signed)), ("unsigned", json::n(r.unsigned)), ("checkpoints", json::n(r.checkpoints)), ("attestations", json::n(r.attestations)), ("errors", json::n(r.errors())), ("warnings", json::n(r.warnings())), ("problems", json::arr(problems)), ]) ); return Ok(code); } println!( "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.", plural(r.objects, "object"), plural(r.ops, "operation"), plural(r.changes, "change"), r.signed, r.unsigned, plural(r.checkpoints, "checkpoint"), plural(r.attestations, "attestation"), ); for p in &r.problems { let obj = p .object .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12))))) .unwrap_or_default(); match p.severity { Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what), Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what), } } if r.problems.is_empty() { println!("{}", ui::done("No problems found.")); } else if code == 0 { println!( "{}", ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning"))) ); } else { println!( "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.", ui::err(ui::glyph("✖", "x")), plural(r.errors(), "error"), plural(r.warnings(), "warning") ); } Ok(code) } /// The head the working copy sits on, for commands that default to it. With /// several heads beneath the working copy, the most recently made one is /// chosen and announced. fn current_head(repo: &Repo) -> Result { let snap = repo.snapshot_status("oxy")?; let base = snap.base.maximal(&snap.wc.deps); match base.as_slice() { [] => anyhow::bail!("the working copy sits on no change yet"), [h] => Ok(*h), many => { let latest = many .iter() .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h))) .copied() .unwrap(); let c = repo.store().get_change(&latest)?; println!( "Defaulting to {} #{} (most recent of the {} heads under the working copy)", short_id(&c), latest.short(12), many.len() ); Ok(latest) } } } /// `oxy describe` without -m: the working copy's name for a build. pub fn describe_name(as_json: bool) -> Result { let repo = open()?; let d = repo.describe_working_copy()?; if as_json { println!( "{}", json::obj([ ("describe", json::s(&d.line())), ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))), ("distance", json::n(d.distance)), ("bookmark", json::s(&d.bookmark)), ("change", json::s(&d.change.to_hex())), ("hash", json::s(&d.hash.to_hex())), ("dirty", json::b(d.dirty)), ]) ); } else { println!("{}", d.line()); } Ok(0) } pub fn describe(message: &str, change: Option<&str>) -> Result { let repo = open()?; let h = match change { Some(c) => repo.resolve_change(c)?, None => current_head(&repo)?, }; let new = repo.describe(&h, message)?; let c = repo.store().get_change_meta(&new)?; println!( "{} {} {} {}", ui::done("Described"), ui::id(c.change_id.short(8)), ui::hash(format!("#{}", new.short(12))), ui::subject(subject_of(message)) ); Ok(0) } pub fn amend(message: Option<&str>, into: Option<&str>) -> Result { let repo = open()?; let before = repo.view()?; let new = match into { Some(spec) => { let target = repo.resolve_change(spec)?; repo.amend_into(&target, message)? } None => repo.amend(message)?, }; let c = repo.store().get_change_meta(&new)?; println!( "{} {} {} {}", ui::done("Amended"), ui::id(c.change_id.short(8)), ui::hash(format!("#{}", new.short(12))), ui::subject(subject_of(&c.message)) ); // Rewriting what a remote already has means the next push replaces it // there (oxygen#99): say so now, not when the push is refused. let bookmark = repo.config.bookmark.clone(); let (had, has) = ( repo.heads_of(&before, &bookmark)?, repo.heads_of(&repo.view()?, &bookmark)?, ); for (remote, bookmarks) in &before.remotes { let Some(st) = bookmarks.get(&bookmark) else { continue; }; let theirs = repo.store().get_state(st)?.heads; if theirs.iter().any(|h| had.contains(h) && !has.contains(h)) { println!( " {} {}", ui::caution(), ui::warn(format!( "{remote}/{bookmark} has the change as it was: the next push of {bookmark} needs --force to replace it" )) ); } } where_now(&repo); Ok(0) } pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result { let repo = open()?; let Some(r) = revset else { let h = repo.resolve_change(change.unwrap_or_default())?; abandon_one(&repo, h)?; where_now(&repo); return Ok(0); }; // A revset: say what it selects, refuse an empty set, ask above a few. let selected = repo.revset(r)?; let wc = repo.working_copy().ok().map(|(h, _)| h); let hashes: Vec = selected .hashes .iter() .copied() .filter(|h| Some(*h) != wc) .collect(); if hashes.is_empty() { anyhow::bail!("{r:?} selects no change to abandon"); } println!( "{} {} selects {}:", ui::section("abandon"), ui::id(r), plural(hashes.len(), "change") ); for h in &hashes { if let Some(m) = selected.metas.get(h) { println!( " {} {} {}", ui::id(m.change_id.short(8)), ui::hash(format!("#{}", h.short(12))), subject_of(&m.message) ); } } const ASK_ABOVE: usize = 5; if hashes.len() > ASK_ABOVE && !yes { anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all"); } // Newest first: abandoning a change rewrites what depends on it, so a // later member is found again by its ChangeId. let mut done = 0; for h in &hashes { let Some(m) = selected.metas.get(h) else { continue; }; let now = match repo.resolve_change(&m.change_id.to_hex()) { Ok(h) => h, Err(_) => continue, }; abandon_one(&repo, now)?; done += 1; } println!("{} {}", ui::done("Abandoned"), plural(done, "change")); where_now(&repo); Ok(0) } fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> { let c = repo.store().get_change_meta(&h)?; let notes = repo.abandon(&h)?; println!( "{} {} {} {}", ui::done("Abandoned"), ui::id(c.change_id.short(8)), ui::hash(format!("#{}", h.short(12))), ui::dim("its content remains on disk as uncommitted work if the working copy sat on it") ); for n in notes { println!(" {} {n}", ui::note()); } Ok(()) } pub fn checkpoint() -> Result { let repo = open()?; let sp = ui::spinner("Writing checkpoint…"); let (r, changes, bytes) = repo.checkpoint()?; sp.done(&format!( "{} {} of {} ({} bytes) for {}", ui::done("Checkpoint"), ui::hash(format!("#{}", r.short(12))), plural(changes, "change"), bytes, ui::id(&repo.config.bookmark) )); Ok(0) } /// For shell prompts: silent (exit 1) outside a repository, otherwise one line. pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result { let Ok(repo) = Repo::open(&std::env::current_dir()?) else { return Ok(1); }; let info = repo.quick_status()?; let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT { oxy_core::repo::GLYPH_PROMPT_FORMAT } else { format }; let line = match color { Some("bash") => info.format_colored(fmt, ("\\[", "\\]")), Some("zsh") => info.format_colored(fmt, ("%{", "%}")), Some(_) => info.format_colored(fmt, ("", "")), None => info.format(fmt), }; println!("{line}"); Ok(0) } pub fn sparse(paths: &[String]) -> Result { let mut repo = open()?; if paths.is_empty() { if repo.config.sparse_paths.is_empty() { println!("No sparse filter: the whole tree is materialized."); } else { println!("{}", ui::heading("Sparse filter")); for p in &repo.config.sparse_paths { println!(" {}", ui::path(p)); } } return Ok(0); } let snap = repo.snapshot("oxy sparse")?; if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() { anyhow::bail!( "the working copy has changes; commit them before changing the sparse filter" ); } repo.config.set("filter.paths", &paths.join(","))?; repo.save_config()?; let heads = repo.bookmark_heads()?; let sp = ui::spinner("Re-checking out with the new filter…"); let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?; sp.done(&format!( "{} {}: {} written, {} removed", ui::done("Sparse filter set to"), ui::path(paths.join(",")), plural(r.written, "file"), r.removed )); Ok(0) } pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result { let repo = open()?; repo.snapshot_status("oxy tag")?; let heads = if changes.is_empty() { repo.bookmark_heads()? } else { let mut heads = Vec::new(); for c in changes { heads.extend(repo.resolve_heads(c)?); } heads }; let t = repo.tag_create(name, &heads, message)?; println!( "{} {} {} {} ({}){}", ui::done("Tagged"), ui::bookmark(&t.name), ui::dim(ui::glyph("→", "->")), ui::hash(format!("#{}", t.state.short(12))), plural(t.heads.len(), "head"), t.signer .map(|s| format!(", signed by {s}")) .unwrap_or_else(|| ui::dim(", unsigned")) ); Ok(0) } pub fn tag_list(as_json: bool) -> Result { let repo = open()?; let tags = repo.tags()?; if as_json { println!( "{}", json::arr(tags.iter().map(|t| { json::obj([ ("name", json::s(&t.name)), ("state", json::s(&t.state.to_hex())), ("heads", json::hashes(&t.heads)), ("message", json::s(&t.message)), ( "signer", json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())), ), ]) })) ); return Ok(0); } if tags.is_empty() { println!("{}", ui::dim("No tags.")); } for t in tags { println!( "{} {} {}{}{}{}", ui::ok(ui::glyph("⚑", "#")), ui::bookmark(&t.name), // The heads, as `oxy log` shows changes, not the state hash. ui::hash( t.heads .iter() .map(|h| format!("#{}", h.short(12))) .collect::>() .join(" ") ), ui::sep() + &ui::dim(plural(t.heads.len(), "head")), if t.message.is_empty() { String::new() } else { format!(" {}", ui::subject(subject_of(&t.message))) }, t.signer .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v")))) .unwrap_or_default() ); } Ok(0) } /// Whether `name` is a bookmark, here or only on a remote: what checkout /// and workspace add take as "be on this bookmark" (oxygen#60). fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result { Ok(repo.view()?.bookmarks.contains_key(name) || repo .remote_only_bookmarks()? .iter() .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name)) } pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result { let repo = open()?; // One bookmark named: the new workspace is on it (oxygen#60), not on // this workspace's bookmark with that one's files. if let [name] = changes { if names_bookmark(&repo, name)? { let (local, _) = repo.local_bookmark_for(name)?; let heads = repo.resolve_heads(&local)?; let sp = ui::spinner(&format!("Creating workspace at {}…", path.display())); let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?; sp.done(&format!( "{} {} (workspace {}) on {}", ui::done("Workspace created at"), ui::path(ws.root().display()), ui::id(ws.workspace().short(8)), ui::bookmark(&local) )); return Ok(0); } } let heads = if changes.is_empty() { None } else { let mut heads = Vec::new(); for c in changes { heads.extend(repo.resolve_heads(c)?); } Some(heads) }; let sp = ui::spinner(&format!("Creating workspace at {}…", path.display())); let ws = repo.workspace_add(path, heads.as_deref())?; sp.done(&format!( "{} {} (workspace {})", ui::done("Workspace created at"), ui::path(ws.root().display()), ui::id(ws.workspace().short(8)) )); Ok(0) } pub fn workspace_list(as_json: bool) -> Result { let repo = open()?; if as_json { println!( "{}", json::arr(repo.workspaces()?.iter().map(|w| { json::obj([ ("id", json::s(&w.id.to_hex())), ("path", json::s(&w.path.to_string_lossy())), ("current", json::b(w.current)), ( "working_copy", json::opt(w.working_copy, |h| json::s(&h.to_hex())), ), ]) })) ); return Ok(0); } for w in repo.workspaces()? { println!( "{} {} {}{}", if w.current { ui::ok(ui::glyph("●", "*")) } else { ui::dim(ui::glyph("○", "o")) }, ui::id(w.id.short(8)), ui::path(w.path.display()), w.working_copy .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12)))) .unwrap_or_else(|| ui::sep() + &ui::warn("not in view")) ); } Ok(0) } pub fn workspace_forget(spec: &str) -> Result { let repo = open()?; let all = repo.workspaces()?; let target = std::fs::canonicalize(spec).ok(); let matches: Vec<_> = all .iter() .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path)) .collect(); let w = match matches.as_slice() { [w] => *w, [] => anyhow::bail!("no workspace matches {spec:?}"), _ => anyhow::bail!("{spec:?} is ambiguous"), }; repo.workspace_forget(&w.id)?; println!( "{} workspace {} at {}; its files were left in place.", ui::done("Forgot"), ui::id(w.id.short(8)), ui::path(w.path.display()) ); Ok(0) } pub fn lock(path: &str) -> Result { let repo = open()?; repo.lock_path(path)?; println!( "{} {} {}", ui::done("Locked"), ui::path(path), ui::dim("(advisory, local)") ); Ok(0) } pub fn unlock(path: &str) -> Result { let repo = open()?; repo.unlock_path(path)?; println!("{} {}", ui::done("Unlocked"), ui::path(path)); Ok(0) } pub fn split(change: &str, paths: &[String]) -> Result { let repo = open()?; let h = repo.resolve_change(change)?; let (h1, h2) = repo.split(&h, paths)?; let c1 = repo.store().get_change_meta(&h1)?; let c2 = repo.store().get_change_meta(&h2)?; println!( "{} into {} {} and {} {}", ui::done("Split"), ui::id(c1.change_id.short(8)), ui::hash(format!("#{}", h1.short(12))), ui::id(c2.change_id.short(8)), ui::hash(format!("#{}", h2.short(12))) ); Ok(0) } fn heads_from(repo: &Repo, changes: &[String]) -> Result> { let mut heads = Vec::new(); for c in changes { heads.extend(repo.resolve_heads(c)?); } Ok(heads) } pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result { let repo = open()?; repo.snapshot_status("oxy bookmark create")?; let heads = if changes.is_empty() { None } else { let named = heads_from(&repo, changes)?; let (_, wc) = repo.working_copy()?; let gap = repo.state_gap(&wc.deps, &named)?; if upto { Some(gap.upto) } else if only || gap.earlier.is_empty() { Some(named) } else { anyhow::bail!( "{name} at {} would lack {} of the current state recorded before it:\n{}\n\ A state is its heads and what they depend on, not everything recorded before them.\n\ Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\ or --only for just {0} and what it depends on.", changes.join(" "), plural(gap.earlier.len(), "change"), listed_changes(&repo, &gap.earlier) ); } }; let heads = repo.bookmark_create(name, heads.as_deref())?; println!( "{} bookmark {} {} {}", ui::done("Created"), ui::bookmark(name), ui::dim(ui::glyph("→", "->")), ui::dim(plural(heads.len(), "head")) ); println!( " {} {}", ui::note(), ui::dim(format!("switch to it with oxy bookmark switch {name}")) ); Ok(0) } /// Up to five changes, newest last, as ` #hash subject` lines. fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String { let shown = changes.len().min(5); let mut lines: Vec = changes[changes.len() - shown..] .iter() .map(|h| { let subject = repo .store() .get_change(h) .map(|c| subject_of(&c.message).to_string()) .unwrap_or_default(); format!(" #{} {subject}", h.short(12)) }) .collect(); if changes.len() > shown { lines.insert(0, format!(" … and {} earlier", changes.len() - shown)); } lines.join("\n") } pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result { let repo = open()?; repo.snapshot_status("oxy bookmark set")?; let named = heads_from(&repo, changes)?; // What the bookmark holds now and the new heads would leave out. let current = repo .bookmarks()? .into_iter() .find(|b| b.name == name) .map(|b| b.heads) .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?; let gap = repo.state_gap(¤t, &named)?; // A fast-forward: the new heads hold the bookmark's newest head, so // what they leave out is older work nothing since has built on, such // as an early change no later one depends on (oxygen#78). Keep it, as // --upto does, and say so. let newest = current .iter() .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m.hlc, *h))) .max() .map(|(_, h)| h); // Ahead, too: a head the bookmark holds already (it would only drop // the others) is not a move forward. let ahead = repo .load_state_history(¤t) .is_ok_and(|st| named.iter().any(|h| !st.contains(h))); let forward = !only && ahead && !gap.earlier.is_empty() && newest.is_some_and(|n| { repo.load_state_history(&named) .is_ok_and(|st| st.contains(&n)) }); let heads = if upto { gap.upto } else if forward { println!( " {} {}", ui::note(), ui::dim(format!( "{} builds on {name}'s newest head; keeping {} it holds that {0} does not depend on", changes.join(" "), plural(gap.earlier.len(), "change") )) ); gap.upto } else if only || gap.earlier.is_empty() { named } else { anyhow::bail!( "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\ A state is its heads and what they depend on, not everything recorded before them.\n\ Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\ or --only for just {0} and what it depends on.", changes.join(" "), plural(gap.earlier.len(), "change"), listed_changes(&repo, &gap.earlier) ); }; let heads = repo.bookmark_set(name, &heads)?; println!( "{} bookmark {} {} {}", ui::done("Moved"), ui::bookmark(name), ui::dim(ui::glyph("→", "->")), ui::dim(plural(heads.len(), "head")) ); Ok(0) } pub fn bookmark_delete(name: &str) -> Result { let repo = open()?; repo.bookmark_delete(name)?; println!( "{} bookmark {} {}", ui::done("Deleted"), ui::bookmark(name), ui::dim("(its changes stay until unreachable)") ); Ok(0) } /// Heads with their metadata, newest first. fn heads_newest_first( repo: &Repo, heads: &[oxy_core::hash::ChangeHash], ) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> { let mut out: Vec<_> = heads .iter() .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m))) .collect(); out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc)); out } /// One head as a line: id, hash, author, when, subject. fn print_head( repo: &Repo, indent: &str, h: &oxy_core::hash::ChangeHash, m: &oxy_core::state::ChangeMeta, ) { println!( "{indent}{} {} {}{}{}{}{}", ui::id(m.change_id.short(8)), ui::dim(format!("#{}", &h.to_hex()[..8])), author_name(repo, m), ui::sep(), ui::dim(ui::ago(m.hlc.wall_ms)), ui::sep(), ui::subject(subject_of(&m.message)) ); } pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result { let repo = open()?; let name = name.unwrap_or(&repo.config.bookmark).to_string(); let view = repo.view()?; let st = match view.bookmarks.get(&name) { Some(st) => *st, None => match oxy_core::repo::remote_bookmark(&view, &name) { Some((_, _, st)) => st, None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"), }, }; let heads = repo.store().get_state(&st)?.heads; let shown = heads_newest_first(&repo, &heads); if as_json { println!( "{}", json::obj([ ("name", json::s(&name)), ("current", json::b(name == repo.config.bookmark)), ( "heads", json::arr(shown.iter().map(|(h, m)| { json::obj([ ("hash", json::s(&h.to_hex())), ("id", json::s(&m.change_id.to_string())), ("author", json::s(&author_name(&repo, m))), ("time_ms", json::n(m.hlc.wall_ms)), ("subject", json::s(subject_of(&m.message))), ]) })) ), ]) ); return Ok(0); } println!( "{} {}{}{}", ui::ok(ui::glyph("●", "*")), ui::bookmark(&name), ui::sep(), ui::dim(plural(heads.len(), "head")) ); for (h, m) in &shown { print_head(&repo, " ", h, m); } if heads.len() > 1 { println!( " {}", ui::dim("None depends on another: the bookmark is all of them and their dependencies.") ); } Ok(0) } pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result { let repo = open()?; let remote_only = repo.remote_only_bookmarks()?; if as_json { let mut items: Vec = repo .bookmarks()? .into_iter() .map(|b| { json::obj([ ("name", json::s(&b.name)), ("heads", json::hashes(&b.heads)), ("current", json::b(b.current)), ("ahead", json::opt(b.ahead, json::n)), ("behind", json::opt(b.behind, json::n)), ("remote", json::opt(b.remote.as_deref(), json::s)), ]) }) .collect(); if all { items.extend(remote_only.iter().map(|b| { json::obj([ ("name", json::s(&format!("{}/{}", b.remote, b.name))), ("heads", json::hashes(&b.heads)), ("current", json::b(false)), ("ahead", "null".into()), ("behind", "null".into()), ("remote", json::s(&b.remote)), ]) })); } println!("{}", json::arr(items)); return Ok(0); } for b in repo.bookmarks()? { let mark = if b.current { ui::ok(ui::glyph("●", "*")) } else { ui::dim(ui::glyph("○", "o")) }; let mut tail = String::new(); if let Some(n) = b.ahead.filter(|n| *n > 0) { tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+"))); } if let Some(n) = b.behind.filter(|n| *n > 0) { tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-"))); } // Which remote, when there is a choice (oxygen#83). if !tail.is_empty() && repo.config.remotes.len() > 1 { if let Some(r) = &b.remote { tail += &ui::dim(format!(" {r}")); } } let shown = heads_newest_first(&repo, &b.heads); // The newest head's subject, so a busy bookmark shows its latest work. let head = match shown.first() { Some(_) if verbose => String::new(), Some((_, m)) if b.heads.len() > 1 => format!( "{} {}", ui::dim("newest"), ui::subject(subject_of(&m.message)) ), Some((_, m)) => ui::subject(subject_of(&m.message)), None => ui::dim("(empty)"), }; let head = if head.is_empty() { head } else { format!(" {head}") }; println!( "{mark} {}{}{}{tail}{head}", ui::bookmark(&b.name), ui::sep(), ui::dim(plural(b.heads.len(), "head")) ); if verbose { for (h, m) in &shown { print_head(&repo, " ", h, m); } } } if remote_only.is_empty() { return Ok(0); } if !all { println!( "{}", ui::dim(format!( " and {} only on a remote: oxy bookmark list --all", plural(remote_only.len(), "bookmark") )) ); return Ok(0); } for b in &remote_only { println!( "{} {}{}{}", ui::dim(ui::glyph("◌", ".")), ui::dim(format!("{}/{}", b.remote, b.name)), ui::sep(), ui::dim(plural(b.heads.len(), "head")) ); } println!( " {} {}", ui::note(), ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's") ); Ok(0) } pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result { let mut repo = open()?; let from = repo.config.bookmark.clone(); let (local, created_from) = repo.local_bookmark_for(name)?; if let Some(remote) = created_from { println!( "{} {} from {}", ui::done("Created"), ui::bookmark(&local), ui::dim(format!("{remote}/{local}")) ); } let name = local.as_str(); // Only behind its remote: take the remote's state, so the switch does // not check out a stale one (oxygen#74). if let Some(n) = repo.catch_up_bookmark(name)? { println!( "{} {} with {}: {} it lacked", ui::done("Caught up"), ui::bookmark(name), ui::dim(format!("{}/{name}", repo.default_remote())), plural(n, "change") ); } let sp = ui::spinner(&format!("Switching to {name}…")); let (r, carried) = if carry { repo.bookmark_switch_carry(name)? } else { (repo.bookmark_switch(name, discard)?, vec![]) }; sp.done(&format!( "{} to {}: {} written, {} removed{}", ui::done("Switched"), ui::bookmark(name), plural(r.written, "file"), r.removed, if carried.is_empty() { String::new() } else { format!("; carried {}", plural(carried.len(), "changed path")) } )); print_removed(&r); if r.conflicted { println!( " {} {}", ui::caution(), ui::warn("this state has conflicts; see oxy status") ); } // Say when the new state leaves out work the old one had: a state is // its heads and what they depend on, which can be far less than a Git // user expects. if r.lacks > 0 { println!( " {} {}", ui::note(), ui::dim(format!( "{name} lacks {} that {from} has", plural(r.lacks, "change") )) ); } super::sync::subrepos_behind(&repo); where_now(&repo); Ok(0) } pub fn merge(bookmark: &str) -> Result { let repo = open()?; let sp = ui::spinner(&format!("Merging {bookmark}…")); let r = repo.merge(bookmark)?; if !r.changed { sp.done(&format!( "{} {}", ui::ok(ui::glyph("✔", "*")), ui::dim(format!( "{} already contains {bookmark}", repo.config.bookmark )) )); return Ok(0); } sp.done(&format!( "{} {} into {}: now {}{}", ui::done("Merged"), ui::bookmark(bookmark), ui::bookmark(&repo.config.bookmark), plural(r.heads.len(), "head"), ui::dim(if r.checked_out { "; working copy updated" } else { "; run oxy checkout to update the working copy" }) )); let snap = repo.snapshot("oxy merge")?; if snap.base_snapshot.is_conflicted() { println!( " {} {}", ui::caution(), ui::warn("the result has conflicts; see oxy status") ); } where_now(&repo); Ok(0) } pub fn squash(change: &str, into: &str) -> Result { let repo = open()?; let c = repo.resolve_change(change)?; let d = repo.resolve_change(into)?; let sp = ui::spinner("Squashing…"); let h = repo.squash(&c, &d)?; let new = repo.store().get_change_meta(&h)?; sp.done(&format!( "{} into {} {} {}", ui::done("Squashed"), ui::id(new.change_id.short(8)), ui::hash(format!("#{}", h.short(12))), ui::subject(subject_of(&new.message)) )); Ok(0) } pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result { let repo = open()?; let c = repo.resolve_change(change)?; let mut heads = Vec::new(); for o in onto { heads.extend(repo.resolve_heads(o)?); } let sp = ui::spinner("Rebasing…"); let h = match repo.rebase(&c, &heads) { Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => { let r = repo.rebase_into_working_copy(&c, &heads)?; sp.done(&format!( "{} {} into {}: now {}", ui::done("Merged"), onto.join(" "), ui::bookmark(&repo.config.bookmark), plural(r.heads.len(), "head"), )); if r.checked_out { println!( " {} {}", ui::caution(), ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit") ); } else { println!( " {} {}", ui::caution(), ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in") ); } where_now(&repo); return Ok(0); } other => other?, }; let new = repo.store().get_change_meta(&h)?; sp.done(&format!( "{} {} {} {}", ui::done("Rebased"), ui::id(new.change_id.short(8)), ui::hash(format!("#{}", h.short(12))), ui::dim(format!( "now depends on {}", plural(new.deps.len(), "change") )) )); where_now(&repo); Ok(0) } #[cfg(test)] mod tests { use super::*; #[test] fn id_prefixes_agree_with_the_whole_list() { // Ids that share long prefixes, and some that differ only in a // half byte, from a fixed sequence. let mut x: u64 = 0x9e37_79b9_7f4a_7c15; let mut next = || { x ^= x << 13; x ^= x >> 7; x ^= x << 17; x }; let mut ids: Vec<[u8; 16]> = Vec::new(); for _ in 0..2000 { let mut id = [0u8; 16]; id[..8].copy_from_slice(&next().to_le_bytes()); id[8..].copy_from_slice(&next().to_le_bytes()); let share = (next() % 4) as usize; if let Some(prev) = ids.last() { id[..share].copy_from_slice(&prev[..share]); if next() % 2 == 0 { id[share] = (prev[share] & 0xf0) | (id[share] & 0x0f); } } ids.push(id); } let hex = |id: &[u8; 16]| oxy_core::ids::ChangeId(*id).to_hex(); let whole = unique_prefixes(ids.iter().map(hex)); let some = id_prefixes(ids.clone(), ids.iter().copied()); for id in &ids { assert_eq!(some[id], whole[&hex(id)], "{}", hex(id)); } } }