//! Commands that act on the local repository and working copy. use super::format::{ author_name, deps_line, deps_of, plural, short_id, short_meta_id, signature_line, signature_mark, subject_of, 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::path::PathBuf; pub fn init(path: Option, bare: bool) -> Result { let path = path.unwrap_or(std::env::current_dir()?); let repo = if bare { Repo::init_bare(&path)? } else { Repo::init(&path)? }; 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)) ); 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", } } pub fn status(json: bool) -> Result { let repo = open()?; // Clean by the manifest alone: no history to load (oxygen#35). if !json && repo.clean_by_manifest()? { 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")) ); println!( " {} {}", ui::ok(ui::glyph("✔", "*")), ui::dim("nothing to commit, working copy clean") ); return Ok(0); } let sp = ui::spinner("Snapshotting the working copy…"); let snap = repo.snapshot_status("oxy status")?; let heads = repo.bookmark_heads()?; 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")) ); if snap.statuses.is_empty() { println!( " {} {}", ui::ok(ui::glyph("✔", "*")), ui::dim("nothing to commit, working copy clean") ); } else { println!(); for s in &snap.statuses { println!( " {} {}", ui::status_mark(status_tag(s.status)), ui::path(&s.path) ); } } 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 = repo.commit_selection(message, &deps, &selection)?; let c = repo.store().get_change(&h)?; sp.done(&format!( "{} {} {} {}", ui::done("Committed"), ui::id(short_id(&c)), ui::hash(format!("#{}", h.short(12))), ui::subject(subject_of(message)) )); if !matches!(selection, oxy_core::repo::Selection::All) { 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") )) ); } } 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(); for l in &lines { let author: String = l.author.chars().take(20).collect(); let text = String::from_utf8_lossy(&l.text); println!( "{} {} {} {:>digits$}{} {}", ui::id(l.change_id.short(8)), ui::author(format!("{author: 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())), ("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( 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. let (conflicted, clean) = if repo.clean_by_manifest()? { (false, true) } else { let snap = repo.snapshot_status("oxy log")?; (snap.base_snapshot.is_conflicted(), snap.statuses.is_empty()) }; let entries = match (path, lines) { (_, 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()?, }; 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); let rail = ui::rail(); for (i, e) in entries.iter().take(shown).enumerate() { let c = &e.change; let bullet = ui::log_bullet( e.is_working_copy, e.is_head, e.is_working_copy && conflicted, ); let mut labels = Vec::new(); if e.is_working_copy { labels.push(ui::warn("working copy")); } if c.kind == ChangeKind::Resolution { labels.push(ui::warn("resolution")); } let labels = if labels.is_empty() { String::new() } else { format!( " {}{}{}", ui::dim("("), labels.join(ui::dim(", ").as_str()), ui::dim(")") ) }; let subject = if e.is_working_copy && c.message.is_empty() { ui::dim(if clean { "(clean)" } else { "(uncommitted changes)" }) } else { ui::subject(subject_of(&c.message)) }; println!("{bullet} {}{labels} {subject}", ui::id(short_meta_id(c))); let meta = format!( "{}{}{}{}{}{}{}", ui::hash(format!("#{}", e.hash.short(12))), ui::sep(), ui::author(author_name(&repo, c)), ui::sep(), ui::dim(ui::ago(c.hlc.wall_ms)), ui::sep(), if e.is_working_copy { ui::dim("not yet committed") } else { signature_mark(&repo, &e.hash)? } ); println!("{rail} {meta}"); if verbose { 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(); if !body.is_empty() { println!("{rail}"); for line in body { println!("{rail} {line}"); } } } if i + 1 < shown { println!("{rail}"); } } if shown < total { println!( "{}", ui::dim(format!( "{} {} more; pass -n to see them", ui::glyph("…", "..."), total - shown )) ); } Ok(0) } 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 => { let snap = repo.snapshot_status("oxy diff")?; print!( "{}", render_change(&snap.wc, &snap.base, &snap.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 = repo.file_at(path, heads.as_deref())?; 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"))), ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)), ("format", json::n(2)) ]) ); } else { println!( "oxy {} (repository format 2, protocol {})", env!("CARGO_PKG_VERSION"), 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: &str, as_json: bool) -> Result { let repo = open()?; repo.snapshot_status("oxy show")?; let h = repo.resolve_change(change)?; 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)) ]))) )); 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())); println!( "{}", ui::kv( "author", ui::author(author_name(&repo, &oxy_core::state::ChangeMeta::of(&c))) ) ); 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()?; 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")) } )); for n in &r.notes { println!(" {} {n}", ui::note()); } if r.conflicted { println!( " {} {}", ui::caution(), ui::warn("this state has conflicts; see oxy status") ); } 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 op = repo.undo()?; println!("{} now at: {}", ui::done("Undone;"), ui::dim(&op.command)); Ok(0) } pub fn op_log(as_json: bool) -> Result { let repo = open()?; if as_json { let ops = repo.op_log()?; println!( "{}", json::arr(ops.iter().enumerate().map(|(i, (r, op))| { 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.command.ends_with("(snapshot)"))), ("current", json::b(i == 0)), ]) })) ); return Ok(0); } for (i, (r, op)) in repo.op_log()?.into_iter().enumerate() { let bullet = if i == 0 { ui::ok(ui::glyph("●", "@")) } else { ui::dim(ui::glyph("○", "o")) }; let cmd = subject_of(&op.command).split("\\n").next().unwrap_or(""); println!( "{bullet} {}{}{} {}", ui::hash(r.short(12)), ui::sep(), ui::dim(format!("{:<16}", ui::ago(op.hlc.wall_ms))), if i == 0 { ui::subject(cmd) } else { cmd.to_string() } ); } Ok(0) } pub fn gc(now: bool) -> Result { let repo = open()?; 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") ); 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(&new)?; println!( "{} {} {} {}", ui::done("Described"), ui::id(short_id(&c)), 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 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(&new)?; println!( "{} {} {} {}", ui::done("Amended"), ui::id(short_id(&c)), ui::hash(format!("#{}", new.short(12))), ui::subject(subject_of(&c.message)) ); Ok(0) } pub fn abandon(change: &str) -> Result { let repo = open()?; let h = repo.resolve_change(change)?; let c = repo.store().get_change(&h)?; let notes = repo.abandon(&h)?; println!( "{} {} {} {}", ui::done("Abandoned"), ui::id(short_id(&c)), 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(0) } 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::ok("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) } pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result { let repo = open()?; 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(&h1)?; let c2 = repo.store().get_change(&h2)?; println!( "{} into {} {} and {} {}", ui::done("Split"), ui::id(short_id(&c1)), ui::hash(format!("#{}", h1.short(12))), ui::id(short_id(&c2)), 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]) -> Result { let repo = open()?; repo.snapshot_status("oxy bookmark set")?; let heads = heads_from(&repo, changes)?; 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) } pub fn bookmark_list(as_json: bool) -> Result { let repo = open()?; if as_json { let items = 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)), ]) }); 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("↓", "-"))); } let head = b .heads .first() .map(|h| { repo.store() .get_change(h) .map(|c| ui::subject(subject_of(&c.message))) .unwrap_or_default() }) .unwrap_or_else(|| ui::dim("(empty)")); println!( "{mark} {}{}{}{tail} {head}", ui::bookmark(&b.name), ui::sep(), ui::dim(plural(b.heads.len(), "head")) ); } Ok(0) } pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result { let mut repo = open()?; let from = repo.config.bookmark.clone(); let before = repo .working_copy() .map(|(_, wc)| wc.deps) .unwrap_or_default(); 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")) } )); 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. let after = repo .working_copy() .map(|(_, wc)| wc.deps) .unwrap_or_default(); if let Ok(gap) = repo.state_gap(&before, &after) { if gap.lacks > 0 { println!( " {} {}", ui::note(), ui::dim(format!( "{name} lacks {} that {from} has", plural(gap.lacks, "change") )) ); } } 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") ); } 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(&h)?; sp.done(&format!( "{} into {} {} {}", ui::done("Squashed"), ui::id(short_id(&new)), ui::hash(format!("#{}", h.short(12))), ui::subject(subject_of(&new.message)) )); Ok(0) } pub fn rebase(change: &str, onto: &[String]) -> 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 = repo.rebase(&c, &heads)?; let new = repo.store().get_change(&h)?; sp.done(&format!( "{} {} {} {}", ui::done("Rebased"), ui::id(short_id(&new)), ui::hash(format!("#{}", h.short(12))), ui::dim(format!( "now depends on {}", plural(new.deps.len(), "change") )) )); Ok(0) }