OXYGENHUB

Coverage / src/cli/workspace.rs 37.9%

842 of 2222 lines run, 75 of 313 functions · run #254 on main · run missed

1
//! Commands that act on the local repository and working copy.
2
3
use super::format::{
4
    author_name, deps_line, deps_of, plural, short_id, signature_line, signature_mark_of,
5
    subject_of, via, when,
6
};
7
use super::json;
8
use super::open;
9
use super::ui;
10
use anyhow::Result;
11
use oxy_core::objects::ChangeKind;
12
use oxy_core::repo::SignatureStatus;
13
use oxy_core::repo::{render_change, ChangeStatus, Repo};
14
use std::io::Write;
15
use std::path::PathBuf;
16
1711×
pub fn init(path: Option<PathBuf>, bare: bool, store: Option<&str>) -> Result<i32> {
1811×
    let path = path.unwrap_or(std::env::current_dir()?);
1911×
    let repo = Repo::init_new(&path, bare, store)?;
2011×
    println!(
21
        "{} {}oxy repository in {}",
2211×
        ui::done("Initialized"),
2311×
        if bare { "bare " } else { "" },
2411×
        ui::path(repo.root().display())
25
    );
2611×
    println!(
27
        "{}",
2811×
        ui::kv("bookmark", ui::bookmark(&repo.config.bookmark))
29
    );
3011×
    if let Some(url) = &repo.config.storage_url {
310×
        println!(
320×
            "{}",
330×
            ui::kv(
340×
                "store",
350×
                format!(
360×
                    "{url} (cache in {}, up to {} MiB)",
370×
                    ui::path(repo.root().join(".oxy/cache").display()),
380×
                    repo.config.storage_cache >> 20
390×
                )
400×
            )
410×
        );
4211×
    }
4311×
    println!(
44
        "{}",
4511×
        ui::kv(
4611×
            "author",
4711×
            format!(
48
                "{} <{}>",
4911×
                ui::author(&repo.config.author_name),
50
                repo.config.author_email
51
            )
52
        )
53
    );
5411×
    Ok(0)
5511×
}
56
572×
fn status_tag(s: ChangeStatus) -> &'static str {
582×
    match s {
591×
        ChangeStatus::Added => "A",
600×
        ChangeStatus::Modified => "M",
610×
        ChangeStatus::Removed => "D",
620×
        ChangeStatus::Renamed => "R",
631×
        ChangeStatus::ModeChanged => "X",
640×
        ChangeStatus::ConflictEdited => "C!",
650×
        ChangeStatus::Resolved => "V",
66
    }
672×
}
68
69
/// Folders holding a repository of their own, which oxy leaves out (oxygen#43):
70
/// named, with how to track them.
7127×
fn print_untracked_nested(repo: &Repo, nested: &[String]) {
7227×
    if nested.is_empty() {
7325×
        return;
742×
    }
752×
    println!();
762×
    println!(
77
        "{} {}",
782×
        ui::section(ui::warn("Not tracked")),
792×
        ui::dim("folders holding a repository of their own")
80
    );
812×
    for p in nested {
822×
        let kind = if repo.root().join(p).join(".git").exists() {
832×
            "Git"
84
        } else {
850×
            "Oxygen"
86
        };
872×
        println!(
88
            "  {} {}  {}",
892×
            ui::caution(),
902×
            ui::path(format!("{p}/")),
912×
            ui::dim(format!("a nested {kind} repository"))
92
        );
93
    }
942×
    println!(
95
        "  {} {}",
962×
        ui::note(),
972×
        ui::dim(
98
            "to track one's files, remove its .git (or .oxy); to keep it a repository of its own, \
99
             oxy submodule add URL PATH; to leave it out quietly, list it in .oxyignore"
100
        )
101
    );
10227×
}
103
104
/// The working copy's changed paths, or that it is clean.
1054×
fn print_statuses(statuses: &[oxy_core::repo::PathStatus]) {
1064×
    if statuses.is_empty() {
1072×
        println!(
108
            "  {} {}",
1092×
            ui::ok(ui::glyph("✔", "*")),
1102×
            ui::dim("nothing to commit, working copy clean")
111
        );
1122×
        return;
1132×
    }
1142×
    println!();
1152×
    for s in statuses {
1162×
        println!(
1172×
            "  {} {}",
1182×
            ui::status_mark(status_tag(s.status)),
1192×
            ui::path(&s.path)
1202×
        );
1212×
    }
1224×
}
123
1247×
pub fn status(json: bool) -> Result<i32> {
1257×
    let repo = open()?;
126
    // Answered by the manifest alone, with no history to load (oxygen#35,
127
    // #41): a clean working copy, or one as the last snapshot left it.
1287×
    let known = if json {
1293×
        None
130
    } else {
1314×
        repo.status_by_manifest()?
132
    };
1337×
    if let Some(statuses) = known {
1342×
        let (_, wc) = repo.working_copy()?;
1352×
        let heads = repo.bookmark_heads()?;
1362×
        println!(
137
            "{} {}{}working copy {}{}{}",
1382×
            ui::dim("On"),
1392×
            ui::bookmark(&repo.config.bookmark),
1402×
            ui::sep(),
1412×
            ui::id(wc.change_id.short(8)),
1422×
            ui::sep(),
1432×
            ui::dim(plural(heads.len(), "head"))
144
        );
1452×
        print_statuses(&statuses);
1462×
        print_untracked_nested(&repo, &repo.untracked_nested());
1472×
        return Ok(0);
1485×
    }
1495×
    let sp = ui::spinner("Snapshotting the working copy…");
1505×
    let snap = repo.snapshot_status("oxy status")?;
1515×
    let heads = {
1525×
        let _t = oxy_core::timing::phase("status: heads");
1535×
        repo.bookmark_heads()?
154
    };
1555×
    let _drop = oxy_core::timing::phase("status: print and drop");
1565×
    sp.clear();
1575×
    if json {
1583×
        println!("{}", repo.status_json(&snap)?);
1593×
        return Ok(if snap.base_snapshot.is_conflicted() {
1600×
            2
161
        } else {
1623×
            0
163
        });
1642×
    }
1652×
    println!(
166
        "{} {}{}working copy {}{}{}",
1672×
        ui::dim("On"),
1682×
        ui::bookmark(&repo.config.bookmark),
1692×
        ui::sep(),
1702×
        ui::id(snap.wc.change_id.short(8)),
1712×
        ui::sep(),
1722×
        ui::dim(plural(heads.len(), "head"))
173
    );
1742×
    print_statuses(&snap.statuses);
1752×
    print_untracked_nested(&repo, &snap.untracked_nested);
1762×
    if !snap.base_snapshot.is_conflicted() {
1772×
        return Ok(0);
1780×
    }
1790×
    println!();
1800×
    println!(
181
        "{} {}",
1820×
        ui::section(ui::err("Conflicts")),
1830×
        ui::dim("edit the marked files, or the .oxy-conflict-N candidates, then commit")
184
    );
1850×
    for c in &snap.base_snapshot.tree.conflicts {
1860×
        println!("  {} tree: {c:?}", ui::err(ui::glyph("✱", "!")));
1870×
    }
1880×
    for (p, f) in &snap.base_snapshot.files {
1890×
        if f.is_conflicted() {
1900×
            let state = match snap
1910×
                .statuses
1920×
                .iter()
1930×
                .find(|s| s.path == *p)
1940×
                .map(|s| s.status)
195
            {
196
                Some(ChangeStatus::Resolved) => {
1970×
                    ui::ok(format!("{} resolved in working copy", ui::glyph("✔", "*")))
198
                }
199
                Some(ChangeStatus::ConflictEdited) => {
2000×
                    ui::warn(format!("{} markers remain", ui::glyph("‼", "!")))
201
                }
2020×
                _ => ui::err(format!("{} unresolved", ui::glyph("✱", "!"))),
203
            };
2040×
            println!("  {}  {state}", ui::path(p));
2050×
        }
206
    }
2070×
    Ok(2)
2087×
}
209
21023×
pub fn commit(
21123×
    message: &str,
21223×
    depends_on: &[String],
21323×
    paths: &[String],
21423×
    interactive: bool,
21523×
    hunks: &[usize],
21623×
) -> Result<i32> {
21723×
    let repo = open()?;
21823×
    let mut deps = Vec::new();
21923×
    for d in depends_on {
2200×
        deps.push(repo.resolve_change(d)?);
221
    }
22223×
    let selection = if !hunks.is_empty() {
2231×
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
22422×
    } else if interactive {
2250×
        let (_, hunks) = repo.hunks()?;
2260×
        if hunks.is_empty() {
2270×
            anyhow::bail!("nothing to commit: the working copy matches its base");
2280×
        }
2290×
        let hunks: Vec<_> = hunks
2300×
            .into_iter()
2310×
            .filter(|h| {
2320×
                paths.is_empty()
2330×
                    || paths.iter().any(|p| {
2340×
                        h.path == *p || h.path.starts_with(&format!("{}/", p.trim_end_matches('/')))
2350×
                    })
2360×
            })
2370×
            .collect();
2380×
        let mut chosen = Vec::new();
2390×
        let stdin = std::io::stdin();
2400×
        let mut take_rest = false;
2410×
        for (n, h) in hunks.iter().enumerate() {
2420×
            if take_rest {
2430×
                chosen.push(h.index);
2440×
                continue;
2450×
            }
2460×
            println!(
247
                "{} {} {}",
2480×
                ui::section(format!("hunk {} of {}", n + 1, hunks.len())),
2490×
                ui::path(&h.path),
2500×
                ui::dim(format!("(#{})", h.index))
251
            );
2520×
            for line in h.text.lines() {
2530×
                let styled = if line.starts_with('+') {
2540×
                    ui::ok(line)
2550×
                } else if line.starts_with('-') {
2560×
                    ui::err(line)
257
                } else {
2580×
                    ui::dim(line)
259
                };
2600×
                println!("  {styled}");
261
            }
262
            loop {
2630×
                print!(
264
                    "{} ",
2650×
                    ui::warn("Commit this hunk? [y]es [n]o [a]ll remaining [q]uit:")
266
                );
267
                use std::io::Write as _;
2680×
                std::io::stdout().flush()?;
2690×
                let mut answer = String::new();
2700×
                if stdin.read_line(&mut answer)? == 0 {
2710×
                    anyhow::bail!("aborted");
2720×
                }
2730×
                match answer.trim() {
2740×
                    "y" | "Y" => {
2750×
                        chosen.push(h.index);
2760×
                        break;
277
                    }
2780×
                    "n" | "N" | "" => break,
2790×
                    "a" | "A" => {
2800×
                        chosen.push(h.index);
2810×
                        take_rest = true;
2820×
                        break;
283
                    }
2840×
                    "q" | "Q" => anyhow::bail!("aborted; nothing committed"),
2850×
                    _ => continue,
286
                }
287
            }
288
        }
2890×
        if chosen.is_empty() {
2900×
            anyhow::bail!("no hunks chosen; nothing committed");
2910×
        }
2920×
        oxy_core::repo::Selection::Hunks(chosen)
29322×
    } else if paths.is_empty() {
29422×
        oxy_core::repo::Selection::All
295
    } else {
2960×
        oxy_core::repo::Selection::Paths(paths.to_vec())
297
    };
29823×
    let sp = ui::spinner("Committing…");
29923×
    let h = repo.commit_selection(message, &deps, &selection)?;
300
    // The metadata only: a first commit's change holds the whole tree.
30123×
    let meta = repo.store().get_change_meta(&h)?;
30223×
    sp.done(&format!(
30323×
        "{} {} {}  {}",
30423×
        ui::done("Committed"),
30523×
        ui::id(meta.change_id.short(8)),
30623×
        ui::hash(format!("#{}", h.short(12))),
30723×
        ui::subject(subject_of(message))
30823×
    ));
30923×
    print_untracked_nested(&repo, &repo.untracked_nested());
31023×
    if !matches!(selection, oxy_core::repo::Selection::All) {
3111×
        let rest = repo.snapshot_status("oxy commit")?;
3121×
        if !rest.statuses.is_empty() {
3131×
            println!(
3141×
                "  {} {}",
3151×
                ui::note(),
3161×
                ui::dim(format!(
3171×
                    "{} left uncommitted",
3181×
                    plural(rest.statuses.len(), "path")
3191×
                ))
3201×
            );
3211×
        }
32222×
    }
32323×
    where_now(&repo);
32423×
    Ok(0)
32523×
}
326
3270×
pub fn blame(path: &str, json: bool) -> Result<i32> {
3280×
    let repo = open()?;
3290×
    let lines = repo.blame(path)?;
3300×
    if json {
3310×
        let items = lines.iter().map(|l| {
3320×
            format!(
333
                "{{\"line\":{},\"change_id\":{},\"hash\":{},\"index\":{},\"author\":{},\"when_ms\":{}}}",
334
                l.line,
3350×
                oxy_core::repo::json_str(&l.change_id.to_hex()),
3360×
                oxy_core::repo::json_str(&l.hash.to_hex()),
337
                l.index,
3380×
                oxy_core::repo::json_str(&l.author),
339
                l.when_ms
340
            )
3410×
        });
3420×
        println!("{}", oxy_core::repo::json_array(items));
3430×
        return Ok(0);
3440×
    }
3450×
    let width = lines
3460×
        .iter()
3470×
        .map(|l| l.author.chars().count())
3480×
        .max()
3490×
        .unwrap_or(0)
3500×
        .min(20);
3510×
    let digits = lines.len().to_string().len();
3520×
    let _t = oxy_core::timing::phase("blame: print");
353
    // Most lines share their change with many others: each change's id,
354
    // author and age are formatted once, and the lines go out through one
355
    // buffered lock on stdout.
3560×
    let mut prefix: std::collections::HashMap<oxy_core::hash::ChangeHash, String> =
3570×
        std::collections::HashMap::new();
3580×
    let bar = ui::dim(ui::glyph("│", "|"));
3590×
    let mut out = std::io::BufWriter::with_capacity(1 << 16, std::io::stdout().lock());
3600×
    for l in &lines {
3610×
        let p = prefix.entry(l.hash).or_insert_with(|| {
3620×
            let author: String = l.author.chars().take(20).collect();
3630×
            format!(
364
                "{} {} {}",
3650×
                ui::id(l.change_id.short(8)),
3660×
                ui::author(format!("{author:<width$}")),
3670×
                ui::dim(ui::ago(l.when_ms))
368
            )
3690×
        });
3700×
        let text = String::from_utf8_lossy(&l.text);
3710×
        if writeln!(
3720×
            out,
373
            "{p} {:>digits$}{bar} {}",
374
            l.line,
3750×
            text.trim_end_matches('\n')
376
        )
3770×
        .is_err()
378
        {
379
            // A closed pipe (blame | head): stop quietly.
3800×
            return Ok(0);
3810×
        }
382
    }
3830×
    let _ = out.flush();
3840×
    Ok(0)
3850×
}
386
3870×
fn bisect_report(repo: &Repo, step: &oxy_core::repo::BisectStep) -> Result<i32> {
388
    use oxy_core::repo::BisectStep::*;
3890×
    match step {
3900×
        NeedMarks { good, bad } => {
3910×
            println!(
392
                "{} {} {}",
3930×
                ui::note(),
3940×
                ui::dim(format!("{good} good, {bad} bad;")),
3950×
                ui::dim(if *good == 0 {
3960×
                    "mark a known-good change or bookmark: oxy bisect good CHANGE"
397
                } else {
3980×
                    "mark a known-bad change or bookmark: oxy bisect bad CHANGE"
399
                })
400
            );
4010×
            Ok(0)
402
        }
403
        Testing {
4040×
            heads,
4050×
            remaining,
4060×
            steps_left,
407
        } => {
4080×
            println!(
409
                "{} {} {}",
4100×
                ui::done("Testing"),
4110×
                ui::dim(format!(
412
                    "{} in the state under test;",
4130×
                    plural(heads.len(), "head")
414
                )),
4150×
                ui::dim(format!(
416
                    "{remaining} candidates left, about {steps_left} more steps"
417
                ))
418
            );
4190×
            println!(
420
                "  {} {}",
4210×
                ui::note(),
4220×
                ui::dim("run your test, then oxy bisect good | bad | skip")
423
            );
4240×
            Ok(0)
425
        }
4260×
        Found { culprit } => {
4270×
            let c = repo.store().get_change(culprit)?;
4280×
            println!(
429
                "{} {} {}  {}",
4300×
                ui::done("Found"),
4310×
                ui::id(short_id(&c)),
4320×
                ui::hash(format!("#{}", culprit.short(12))),
4330×
                ui::subject(subject_of(&c.message))
434
            );
4350×
            println!("  {} {}", ui::note(), ui::dim("the first change whose inclusion makes the state bad; oxy bisect reset to return"));
4360×
            Ok(0)
437
        }
4380×
        Inconclusive { candidates } => {
4390×
            println!(
440
                "{} {}",
4410×
                ui::caution(),
4420×
                ui::warn(format!(
443
                    "every remaining candidate was skipped ({}); oxy bisect reset to return",
4440×
                    plural(candidates.len(), "change")
445
                ))
446
            );
4470×
            Ok(1)
448
        }
449
    }
4500×
}
451
4520×
pub fn bisect_start() -> Result<i32> {
4530×
    let repo = open()?;
4540×
    repo.bisect_start()?;
4550×
    println!(
456
        "{} bisect; {}",
4570×
        ui::done("Started"),
4580×
        ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE")
459
    );
4600×
    Ok(0)
4610×
}
462
4630×
pub fn bisect_mark(good: Option<bool>, changes: &[String]) -> Result<i32> {
4640×
    let repo = open()?;
4650×
    let mut heads = Vec::new();
4660×
    for c in changes {
4670×
        heads.extend(repo.resolve_heads(c)?);
468
    }
4690×
    let step = repo.bisect_mark(good, &heads)?;
4700×
    bisect_report(&repo, &step)
4710×
}
472
4730×
pub fn bisect_run(command: &[String]) -> Result<i32> {
4740×
    let repo = open()?;
4750×
    let step = repo.bisect_run(command)?;
4760×
    bisect_report(&repo, &step)
4770×
}
478
4791×
pub fn bisect_status(as_json: bool) -> Result<i32> {
4801×
    let repo = open()?;
4811×
    if as_json {
482
        use oxy_core::repo::BisectStep::*;
4831×
        let v = match repo.bisect_status()? {
4841×
            None => "null".to_string(),
4850×
            Some(NeedMarks { good, bad }) => json::obj([
4860×
                ("state", json::s("need-marks")),
4870×
                ("good", json::n(good)),
4880×
                ("bad", json::n(bad)),
4890×
            ]),
490
            Some(Testing {
4910×
                heads,
4920×
                remaining,
4930×
                steps_left,
4940×
            }) => json::obj([
4950×
                ("state", json::s("testing")),
4960×
                ("heads", json::hashes(&heads)),
4970×
                ("remaining", json::n(remaining)),
4980×
                ("steps_left", json::n(steps_left)),
4990×
            ]),
5000×
            Some(Found { culprit }) => json::obj([
5010×
                ("state", json::s("found")),
5020×
                ("culprit", json::s(&culprit.to_hex())),
5030×
            ]),
5040×
            Some(Inconclusive { candidates }) => json::obj([
5050×
                ("state", json::s("inconclusive")),
5060×
                ("candidates", json::hashes(&candidates)),
5070×
            ]),
508
        };
5091×
        println!("{v}");
5101×
        return Ok(0);
5110×
    }
5120×
    match repo.bisect_status()? {
513
        None => {
5140×
            println!("{}", ui::dim("No bisect in progress."));
5150×
            Ok(0)
516
        }
5170×
        Some(step) => bisect_report(&repo, &step),
518
    }
5191×
}
520
5210×
pub fn bisect_reset() -> Result<i32> {
5220×
    let repo = open()?;
5230×
    repo.bisect_reset()?;
5240×
    println!("{} bisect; working copy restored", ui::done("Reset"));
5250×
    Ok(0)
5260×
}
527
528
/// The log: one entry per change, newest first, joined by a rail. The
529
/// default view is the subject and a metadata line; `verbose` adds the full
530
/// message, dependencies, and the authenticating key.
53114×
fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
53214×
    Ok(match repo.authenticate_change(h)? {
5339×
        SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]),
534
        SignatureStatus::Valid {
5355×
            key,
5365×
            name,
5375×
            email,
5385×
            sealed,
5395×
            revoked,
5405×
        } => json::obj([
5415×
            ("status", json::s(if sealed { "sealed" } else { "signed" })),
5425×
            ("key", json::s(&key.to_hex())),
5435×
            ("name", json::s(&name)),
5445×
            ("email", json::s(&email)),
5455×
            ("revoked", json::b(revoked)),
546
        ]),
5470×
        SignatureStatus::Invalid(why) => {
5480×
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
549
        }
550
    })
55114×
}
552
55318×
fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result<String> {
55418×
    let c = &e.change;
55518×
    Ok(json::obj([
55618×
        ("hash", json::s(&e.hash.to_hex())),
55718×
        ("change_id", json::s(&c.change_id.to_hex())),
55818×
        ("author", json::s(&author_name(repo, c))),
55918×
        ("author_key", json::s(&c.author.to_hex())),
560
        (
56118×
            "via",
56218×
            match via(
56318×
                repo,
56418×
                &repo.authenticate_change_known(&e.hash, Some(c))?,
56518×
                &c.author,
566
            ) {
5670×
                Some(v) => json::obj([
5680×
                    ("name", json::s(&v.name)),
5690×
                    ("email", json::s(&v.email)),
5700×
                    ("key", json::s(&v.key.to_hex())),
5710×
                    ("scope", json::opt(v.scope.as_deref(), json::s)),
5720×
                    ("expires_ms", json::opt(v.expires, json::n)),
5730×
                    ("revoked", json::b(v.revoked)),
5740×
                ]),
57518×
                None => "null".to_string(),
576
            },
577
        ),
57818×
        ("when_ms", json::n(c.hlc.wall_ms)),
57918×
        ("message", json::s(&c.message)),
58018×
        ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())),
58118×
        ("deps", json::hashes(&c.deps)),
58218×
        ("head", json::b(e.is_head)),
58318×
        ("working_copy", json::b(e.is_working_copy)),
584
        (
58518×
            "signature",
58618×
            if e.is_working_copy {
5874×
                "null".into()
588
            } else {
58914×
                signature_json(repo, &e.hash)?
590
            },
591
        ),
592
    ]))
59318×
}
594
595
/// `START,END:PATH` for `oxy log -L`.
5962×
fn parse_line_range(spec: &str) -> Result<(usize, usize, &str)> {
5972×
    let bad = || anyhow::anyhow!("-L {spec}: expected START,END:PATH, as 10,24:src/lib.rs");
5982×
    let (range, path) = spec.split_once(':').ok_or_else(bad)?;
5992×
    let (a, b) = range.split_once(',').ok_or_else(bad)?;
600
    Ok((
6011×
        a.trim().parse().map_err(|_| bad())?,
6021×
        b.trim().parse().map_err(|_| bad())?,
6031×
        path,
604
    ))
6052×
}
606
6078×
pub fn log(
6088×
    revset: Option<&str>,
6098×
    limit: Option<usize>,
6108×
    verbose: bool,
6118×
    path: Option<&str>,
6128×
    lines: Option<&str>,
6138×
    as_json: bool,
6148×
) -> Result<i32> {
6158×
    let repo = open()?;
616
    // Whether the working copy is clean and conflicted: from the manifest
617
    // when it proves the working copy clean, else from a snapshot.
618
    // The working copy as last recorded, without looking at the files (as
619
    // Git's log does not): whether its change holds edits, and whether its
620
    // base was conflicted. `oxy status` is what checks the disk.
6218×
    let conflicted = !repo.is_at_op() && repo.recorded_conflicted()?;
6228×
    let listing = oxy_core::timing::phase("log: entries");
6238×
    let entries = match (path, lines) {
6248×
        _ if revset.is_some() => repo.log_revset(revset.unwrap_or_default())?,
6252×
        (_, Some(spec)) => {
6262×
            let (first, last, p) = parse_line_range(spec)?;
6271×
            let (_, wc) = repo.working_copy()?;
6281×
            let base = repo.load_state_history(&wc.deps)?.maximal(&wc.deps);
6291×
            repo.line_history(&base, p, first, last)?
630
        }
6311×
        (Some(p), None) => repo.log_for_path(p)?,
6325×
        (None, None) => repo.log()?,
633
    };
6347×
    drop(listing);
6357×
    let _print = oxy_core::timing::phase("log: print");
6367×
    if as_json {
6376×
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
6386×
        let mut items = Vec::new();
63917×
        for e in entries.iter().take(shown) {
64017×
            items.push(log_entry_json(&repo, e)?);
641
        }
6426×
        println!(
643
            "{}",
6446×
            json::obj([
6456×
                ("bookmark", json::s(&repo.config.bookmark)),
6466×
                ("total", json::n(entries.len())),
6476×
                ("changes", json::arr(items))
6486×
            ])
649
        );
6506×
        return Ok(0);
6511×
    }
6521×
    let total = entries.len();
6531×
    let shown = limit.unwrap_or(total).min(total);
654
    // Lay out a little past what is shown, so edges into the cut are drawn.
6551×
    let window: Vec<(ChangeHash, Vec<ChangeHash>)> = entries
6561×
        .iter()
6571×
        .take((shown + MAX_EDGE).min(total))
6584×
        .map(|e| (e.hash, e.change.deps.clone()))
6591×
        .collect();
6601×
    let rows = oxy_core::lanes::graph(&window, MAX_EDGE);
661
    // Highlight the shortest prefix that names each change: against the
662
    // whole log, which is what `resolve_change` searches.
663
    let everything;
6641×
    let all = if path.is_some() || lines.is_some() || revset.is_some() {
6650×
        everything = repo.log()?;
6660×
        &everything
667
    } else {
6681×
        &entries
669
    };
6704×
    let id_prefix = unique_prefixes(all.iter().map(|e| e.change.change_id.to_hex()));
6711×
    let labels = reference_labels(&repo)?;
6724×
    for (e, row) in entries.iter().take(shown).zip(&rows) {
6734×
        let c = &e.change;
6744×
        let bullet = ui::log_bullet(
6754×
            e.is_working_copy,
6764×
            e.is_head,
6774×
            e.is_working_copy && conflicted,
678
        );
6794×
        let id = c.change_id.to_hex();
6804×
        let n = id_prefix.get(&id).copied().unwrap_or(8).min(8);
6814×
        let mut head = vec![format!("{}{}", ui::id(&id[..n]), ui::dim(&id[n..8]))];
6824×
        head.push(ui::author(author_name(&repo, c)));
6834×
        head.push(ui::dim(ui::ago(c.hlc.wall_ms)));
6844×
        if let Some(names) = labels.get(&e.hash) {
6852×
            head.push(names.join(" "));
6862×
        }
6874×
        if c.kind == ChangeKind::Resolution {
6880×
            head.push(ui::warn("resolution"));
6894×
        }
6904×
        if !e.is_working_copy {
6913×
            head.push(ui::hash(format!("#{}", e.hash.short(8))));
6923×
            let status = repo.authenticate_change_known(&e.hash, Some(c))?;
6933×
            if let Some(agent) = via(&repo, &status, &c.author) {
6940×
                head.push(ui::dim(format!("via {}", agent.name)));
6953×
            }
6963×
            head.push(signature_mark_of(&status));
6971×
        }
6984×
        println!("{}{}", node_line(row, &bullet), head.join(" "));
6994×
        let subject = if e.is_working_copy && c.message.is_empty() {
7001×
            let edited = repo
7011×
                .store()
7021×
                .get_change(&e.hash)
7031×
                .is_ok_and(|w| !w.tree_ops.is_empty() || !w.edits.is_empty());
7041×
            ui::dim(if edited {
7050×
                "(working copy, uncommitted changes)"
706
            } else {
7071×
                "(working copy)"
708
            })
7093×
        } else if c.message.trim().is_empty() {
7100×
            ui::dim("(no description)")
711
        } else {
7123×
            subject_of(&c.message).to_string()
713
        };
7144×
        println!("{}{subject}", below_line(row));
7154×
        if verbose {
7160×
            let rail = continuation(row);
7170×
            if !e.is_working_copy {
7180×
                println!(
719
                    "{rail}{}",
7200×
                    ui::dim(format!(
721
                        "{} {}",
7220×
                        when(c.hlc.wall_ms),
7230×
                        signature_line(&repo, &e.hash)?
724
                    ))
725
                );
7260×
            }
7270×
            if !c.deps.is_empty() {
7280×
                println!(
7290×
                    "{rail}{} {}",
7300×
                    ui::dim(ui::glyph("↳", "->")),
7310×
                    ui::dim(deps_of(&c.deps))
7320×
                );
7330×
            }
7340×
            let body: Vec<&str> = c
7350×
                .message
7360×
                .lines()
7370×
                .skip(1)
7380×
                .skip_while(|l| l.trim().is_empty())
7390×
                .collect();
7400×
            for line in body {
7410×
                println!("{rail}  {line}");
7420×
            }
7434×
        }
744
    }
7451×
    if shown < total {
7460×
        if let Some(last) = rows.get(shown.saturating_sub(1)) {
7470×
            let cut: String = last
7480×
                .below
7490×
                .iter()
7500×
                .map(|c| match c {
7510×
                    Cell::Blank | Cell::Elided | Cell::JoinRight => "  ",
7520×
                    _ => "~ ",
7530×
                })
7540×
                .collect();
7550×
            if cut.trim().is_empty() {
7560×
                println!("{}", ui::dim("~"));
7570×
            } else {
7580×
                println!("{}", ui::dim(cut.trim_end()));
7590×
            }
7600×
        }
7610×
        println!(
762
            "{}",
7630×
            ui::dim(format!(
764
                "{} {} more; pass -n to see them",
7650×
                ui::glyph("…", "..."),
7660×
                total - shown
767
            ))
768
        );
7691×
    }
7701×
    Ok(0)
7718×
}
772
773
/// Rows a drawn edge may span in `oxy log`; a longer one is elided (`~`).
774
const MAX_EDGE: usize = 12;
775
776
use oxy_core::hash::ChangeHash;
777
use oxy_core::lanes::{Cell, GraphRow};
778
779
/// A graph cell, two columns wide.
7806×
fn cell(c: Cell) -> &'static str {
7816×
    match c {
7821×
        Cell::Blank => "  ",
7833×
        Cell::Line => ui::glyph("│ ", "| "),
7840×
        Cell::Elided => "~ ",
7851×
        Cell::JoinLeft => ui::glyph("├─", "|-"),
7860×
        Cell::JoinPass => ui::glyph("──", "--"),
7870×
        Cell::JoinCross => ui::glyph("┼─", "+-"),
7881×
        Cell::JoinRight => ui::glyph("╯ ", "' "),
789
    }
7906×
}
791
792
/// The graph part of a change's own line, its bullet in its column.
7934×
fn node_line(row: &GraphRow, bullet: &str) -> String {
7944×
    let width = row
7954×
        .passing
7964×
        .iter()
7974×
        .copied()
7984×
        .max()
7994×
        .unwrap_or(0)
8004×
        .max(row.column)
8014×
        + 1;
8024×
    let mut out = String::new();
8035×
    for c in 0..width {
8045×
        if c == row.column {
8054×
            out.push_str(bullet);
8064×
            out.push(' ');
8074×
        } else if row.passing.contains(&c) {
8081×
            out.push_str(&ui::dim(cell(Cell::Line)));
8091×
        } else {
8100×
            out.push_str("  ");
8110×
        }
812
    }
8134×
    out.push(' ');
8144×
    out
8154×
}
816
817
/// The graph part of the line under a change: lanes carrying on, a join,
818
/// or `~` for an elided edge.
8194×
fn below_line(row: &GraphRow) -> String {
8205×
    let g: String = row.below.iter().map(|c| cell(*c)).collect();
8214×
    format!("{} ", ui::dim(g))
8224×
}
823
824
/// The graph part of any further line of a change (`-v`).
8250×
fn continuation(row: &GraphRow) -> String {
8260×
    let g: String = row
8270×
        .below
8280×
        .iter()
8290×
        .map(|c| match c {
8300×
            Cell::Line | Cell::JoinLeft | Cell::JoinCross => cell(Cell::Line),
8310×
            _ => "  ",
8320×
        })
8330×
        .collect();
8340×
    format!("{} ", ui::dim(g))
8350×
}
836
837
/// For each hex ID, the length of its shortest prefix no other ID shares.
8381×
fn unique_prefixes(ids: impl Iterator<Item = String>) -> std::collections::HashMap<String, usize> {
8391×
    let mut v: Vec<String> = ids.collect();
8401×
    v.sort();
8411×
    v.dedup();
8426×
    let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
8431×
    let mut out = std::collections::HashMap::with_capacity(v.len());
8444×
    for i in 0..v.len() {
8454×
        let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 };
8464×
        let after = if i + 1 < v.len() {
8473×
            common(&v[i], &v[i + 1])
848
        } else {
8491×
            0
850
        };
8514×
        out.insert(v[i].clone(), before.max(after) + 1);
852
    }
8531×
    out
8541×
}
855
856
/// Bookmark, remote bookmark and tag names to show beside the changes they
857
/// point at. A name is shown on each head of its state; one with more than
858
/// three heads names too much of the log to help, so it is left out (oxy
859
/// bookmark list shows it). A remote bookmark at the same state as the
860
/// local one of that name is not repeated.
8611×
fn reference_labels(repo: &Repo) -> Result<std::collections::HashMap<ChangeHash, Vec<String>>> {
862
    const MAX_HEADS: usize = 3;
8631×
    let view = repo.view()?;
8641×
    let mut out: std::collections::HashMap<ChangeHash, Vec<String>> = Default::default();
8651×
    let mut add = |heads: Vec<ChangeHash>, label: String| {
8661×
        if heads.len() <= MAX_HEADS {
8672×
            for h in heads {
8682×
                out.entry(h).or_default().push(label.clone());
8692×
            }
8700×
        }
8711×
    };
8721×
    for (name, st) in &view.bookmarks {
8731×
        add(repo.store().get_state(st)?.heads, ui::bookmark(name));
874
    }
8751×
    for (remote, bookmarks) in &view.remotes {
8760×
        for (name, st) in bookmarks {
8770×
            if view.bookmarks.get(name) == Some(st) {
8780×
                continue;
8790×
            }
8800×
            add(
8810×
                repo.store().get_state(st)?.heads,
8820×
                ui::dim(format!("{remote}/{name}")),
883
            );
884
        }
885
    }
8861×
    for t in repo.tags()? {
8870×
        add(t.heads.clone(), ui::warn(&t.name));
8880×
    }
8891×
    Ok(out)
8901×
}
891
8921×
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
8931×
    let repo = open()?;
8941×
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
8951×
    if as_json {
8961×
        let files = repo.diff_files(hash.as_ref())?;
8973×
        let items = files.iter().map(|f| {
8983×
            json::obj([
8993×
                ("path", json::s(&f.path)),
9003×
                ("kind", json::s(&f.kind)),
9013×
                ("from", json::opt(f.from.as_deref(), json::s)),
902
                (
9033×
                    "hunks",
9043×
                    json::arr(f.hunks.iter().map(|h| {
9053×
                        json::obj([
9063×
                            ("base_line", json::n(h.base_line)),
907
                            (
9083×
                                "added",
9093×
                                json::arr(
9103×
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
911
                                ),
912
                            ),
913
                            (
9143×
                                "removed",
9153×
                                json::arr(h.removed.iter().map(|(n, l)| {
9160×
                                    json::obj([
9170×
                                        ("line", json::n(*n)),
9180×
                                        ("text", json::s(&String::from_utf8_lossy(l))),
9190×
                                    ])
9200×
                                })),
921
                            ),
922
                        ])
9233×
                    })),
924
                ),
925
            ])
9263×
        });
9271×
        println!(
928
            "{}",
9291×
            json::obj([
9301×
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
9311×
                ("files", json::arr(items))
932
            ])
933
        );
9341×
        return Ok(0);
9350×
    }
9360×
    match hash {
9370×
        Some(h) => {
9380×
            let c = repo.store().get_change(&h)?;
9390×
            let (base, snapshot) = repo.change_base(&c)?;
9400×
            print!("{}", render_change(&c, &base, &snapshot));
941
        }
942
        None => {
9430×
            let (wc, base, snapshot) = repo.working_copy_with_base()?;
9440×
            let text = {
9450×
                let _t = oxy_core::timing::phase("diff: render the change");
9460×
                render_change(&wc, &base, &snapshot)
947
            };
9480×
            print!("{text}");
949
            // The process ends here: freeing the base's tree and graphs
950
            // one by one would only cost time (about 27 ms on Linux).
9510×
            std::mem::forget((wc, base, snapshot));
952
        }
953
    }
9540×
    Ok(0)
9551×
}
956
9572×
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
9582×
    let repo = open()?;
9592×
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
9602×
    let bytes = match repo.file_at(path, heads.as_deref()) {
9612×
        Ok(b) => b,
962
        // -r CHANGE reads that change's dependency closure, not the
963
        // bookmark it is on: say so when the bookmark has the file
964
        // (oxygen#76).
9650×
        Err(e) => match change {
9660×
            Some(c)
9670×
                if !repo.view()?.bookmarks.contains_key(c)
9680×
                    && repo.tag_heads(c)?.is_none()
9690×
                    && repo.file_at(path, None).is_ok() =>
970
            {
9710×
                anyhow::bail!(
972
                    "{path} is not in {c}'s dependency closure (the change and what it \
973
                     depends on); it is on the bookmark: try -r {}, or --at-op OP for the \
974
                     state at an operation",
975
                    repo.config.bookmark
976
                )
977
            }
9780×
            _ => return Err(e.into()),
979
        },
980
    };
981
    use std::io::Write as _;
9822×
    std::io::stdout().write_all(&bytes)?;
9832×
    Ok(0)
9842×
}
985
9861×
pub fn root(as_json: bool) -> Result<i32> {
9871×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
9880×
        if as_json {
9890×
            println!("null");
9900×
        }
9910×
        return Ok(1);
992
    };
9931×
    if as_json {
9941×
        println!(
9951×
            "{}",
9961×
            json::obj([
9971×
                ("root", json::s(&repo.root().to_string_lossy())),
9981×
                ("workspace", json::s(&repo.workspace().to_hex())),
9991×
                ("bookmark", json::s(&repo.config.bookmark))
10001×
            ])
10011×
        );
10021×
    } else {
10030×
        println!("{}", repo.root().display());
10040×
    }
10051×
    Ok(0)
10061×
}
1007
10081×
pub fn version(as_json: bool) -> Result<i32> {
10091×
    if as_json {
10101×
        println!(
10111×
            "{}",
10121×
            json::obj([
10131×
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
10141×
                // What was built: a release's or install's `oxy describe`,
10151×
                // a Flow build's heads, or "local build".
10161×
                ("build", json::s(env!("OXY_BUILD_ID"))),
10171×
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
10181×
                ("format", json::n(2))
10191×
            ])
10201×
        );
10211×
    } else {
10220×
        println!(
10230×
            "oxy {} (repository format 2, protocol {})",
10240×
            env!("OXY_VERSION_LONG"),
10250×
            oxy_core::protocol::PROTOCOL_VERSION
10260×
        );
10270×
    }
10281×
    Ok(0)
10291×
}
1030
10312×
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
10322×
    let repo = open()?;
10332×
    if paths.is_empty() && hunks.is_empty() {
10340×
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
10352×
    }
10362×
    let mut n = 0;
10372×
    if !hunks.is_empty() {
10381×
        n += repo.discard_hunks(hunks)?;
10391×
    }
10402×
    if !paths.is_empty() {
10411×
        n += repo.discard(paths)?;
10421×
    }
10432×
    println!(
1044
        "{} {} restored to the working copy's base",
10452×
        ui::done("Discarded"),
10462×
        plural(n, "path")
1047
    );
10482×
    Ok(0)
10492×
}
1050
10512×
pub fn hunks(as_json: bool) -> Result<i32> {
10522×
    let repo = open()?;
10532×
    let (_, hunks) = repo.hunks()?;
10542×
    if as_json {
10552×
        println!(
1056
            "{}",
10575×
            json::arr(hunks.iter().map(|h| json::obj([
10585×
                ("index", json::n(h.index)),
10595×
                ("path", json::s(&h.path)),
10605×
                ("text", json::s(&h.text))
10615×
            ])))
1062
        );
10632×
        return Ok(0);
10640×
    }
10650×
    if hunks.is_empty() {
10660×
        println!(
10670×
            "{}",
10680×
            ui::dim("No hunks: the working copy matches its base.")
10690×
        );
10700×
    }
10710×
    for h in &hunks {
10720×
        println!(
1073
            "{} {}",
10740×
            ui::section(format!("hunk {}", h.index)),
10750×
            ui::path(&h.path)
1076
        );
10770×
        for line in h.text.lines() {
10780×
            let styled = if line.starts_with('+') {
10790×
                ui::ok(line)
10800×
            } else if line.starts_with('-') {
10810×
                ui::err(line)
1082
            } else {
10830×
                ui::dim(line)
1084
            };
10850×
            println!("  {styled}");
1086
        }
1087
    }
10880×
    Ok(0)
10892×
}
1090
10912×
pub fn show(change: Option<&str>, revset: Option<&str>, as_json: bool) -> Result<i32> {
10922×
    let repo = open()?;
10932×
    repo.snapshot_status("oxy show")?;
10942×
    let Some(r) = revset else {
10952×
        let h = repo.resolve_change(change.unwrap_or("@"))?;
10962×
        return show_one(&repo, h, as_json, false);
1097
    };
1098
    // Several changes: a JSON array, or the changes one after another.
10990×
    let hashes = repo.revset(r)?.hashes;
11000×
    if as_json {
11010×
        print!("[");
11020×
        for (i, h) in hashes.iter().enumerate() {
11030×
            if i > 0 {
11040×
                print!(",");
11050×
            }
11060×
            show_one(&repo, *h, true, true)?;
1107
        }
11080×
        println!("]");
11090×
        return Ok(0);
11100×
    }
11110×
    if hashes.is_empty() {
11120×
        println!("{}", ui::dim(format!("No change matches {r:?}.")));
11130×
        return Ok(0);
11140×
    }
11150×
    for (i, h) in hashes.iter().enumerate() {
11160×
        if i > 0 {
11170×
            println!();
11180×
        }
11190×
        show_one(&repo, *h, false, false)?;
1120
    }
11210×
    Ok(0)
11222×
}
1123
1124
/// One change, as `oxy show` prints it; `inline` JSON goes without its
1125
/// newline, for an array.
11262×
fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool) -> Result<i32> {
11272×
    let c = repo.store().get_change(&h)?;
11282×
    if as_json {
11291×
        let files = repo.diff_files(Some(&h))?;
11301×
        let heads = repo.bookmark_heads()?;
11311×
        let entry = oxy_core::repo::LogEntry {
11321×
            hash: h,
11331×
            change: oxy_core::state::ChangeMeta::of(&c),
11341×
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
11351×
            is_head: heads.contains(&h),
11361×
        };
11371×
        let mut body = log_entry_json(repo, &entry)?;
11381×
        body.pop();
11391×
        body.push_str(&format!(
1140
            ",{}:{}}}",
11411×
            json::s("files"),
11421×
            json::arr(files.iter().map(|f| json::obj([
11431×
                ("path", json::s(&f.path)),
11441×
                ("kind", json::s(&f.kind)),
11451×
                ("from", json::opt(f.from.as_deref(), json::s))
11461×
            ])))
1147
        ));
11481×
        if inline {
11490×
            print!("{body}");
11501×
        } else {
11511×
            println!("{body}");
11521×
        }
11531×
        return Ok(0);
11541×
    }
11551×
    println!(
1156
        "{} {} {}",
11571×
        ui::section("change"),
11581×
        ui::id(short_id(&c)),
11591×
        ui::hash(format!("#{h}"))
1160
    );
11611×
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1162
    // Fetched but not pulled (oxygen#56): say where it is.
11631×
    if let Some(at) = repo.remote_only_location(&h)? {
11640×
        println!(
11650×
            "{}",
11660×
            ui::kv(
11670×
                "only in",
11680×
                ui::warn(format!(
11690×
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
11700×
                ))
11710×
            )
11720×
        );
11731×
    }
11741×
    let meta = oxy_core::state::ChangeMeta::of(&c);
11751×
    let status = repo.authenticate_change_known(&h, Some(&meta))?;
11761×
    println!("{}", ui::kv("author", ui::author(author_name(repo, &meta))));
11771×
    if let Some(agent) = via(repo, &status, &meta.author) {
11780×
        println!("{}", ui::kv("via", agent.line()));
11791×
    }
11801×
    println!(
1181
        "{}",
11821×
        ui::kv(
11831×
            "date",
11841×
            format!(
1185
                "{} {}",
11861×
                when(c.hlc.wall_ms),
11871×
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1188
            )
1189
        )
1190
    );
11911×
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
11921×
    println!("{}", ui::kv("sig", signature_line(repo, &h)?));
11931×
    println!();
11944×
    for line in (if c.message.is_empty() {
11950×
        "(no description)"
1196
    } else {
11971×
        &c.message
1198
    })
11991×
    .lines()
12004×
    {
12014×
        println!("    {line}");
12024×
    }
12031×
    println!();
12041×
    print!("{}", repo.describe_change(&h)?);
12051×
    Ok(0)
12062×
}
1207
12080×
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
12090×
    let repo = open()?;
1210
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1211
    // BRANCH` is: checking its files out under another bookmark's name
1212
    // made the next commit move the wrong bookmark (oxygen#60).
12130×
    if let [name] = changes {
12140×
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
12150×
            drop(repo);
12160×
            return bookmark_switch(name, discard, carry);
12170×
        }
12180×
    }
12190×
    let heads = if changes.is_empty() {
12200×
        repo.bookmark_heads()?
1221
    } else {
12220×
        let mut heads = Vec::new();
12230×
        for c in changes {
12240×
            heads.extend(repo.resolve_heads(c)?);
1225
        }
12260×
        heads
1227
    };
12280×
    let spec = if changes.is_empty() {
12290×
        repo.config.bookmark.clone()
1230
    } else {
12310×
        changes.join(" ")
1232
    };
12330×
    let sp = ui::spinner(&format!("Checking out {spec}…"));
12340×
    let command = format!("oxy checkout {spec}");
12350×
    let (r, carried) = if carry {
12360×
        repo.checkout_carry(&heads, &spec, &command)?
1237
    } else {
12380×
        (repo.checkout(&heads, discard, &command)?, vec![])
1239
    };
12400×
    sp.done(&format!(
1241
        "{} on {}: {} written, {} removed{}",
12420×
        ui::done("Working copy"),
12430×
        ui::bookmark(&spec),
12440×
        plural(r.written, "file"),
1245
        r.removed,
12460×
        if carried.is_empty() {
12470×
            String::new()
1248
        } else {
12490×
            format!("; carried {}", plural(carried.len(), "changed path"))
1250
        }
1251
    ));
12520×
    for n in &r.notes {
12530×
        println!("  {} {n}", ui::note());
12540×
    }
12550×
    if r.conflicted {
12560×
        println!(
12570×
            "  {} {}",
12580×
            ui::caution(),
12590×
            ui::warn("this state has conflicts; see oxy status")
12600×
        );
12610×
    }
12620×
    where_now(&repo);
12630×
    Ok(0)
12640×
}
1265
12661×
pub fn resolve(as_json: bool) -> Result<i32> {
12671×
    let repo = open()?;
12681×
    let snap = repo.snapshot("oxy resolve")?;
12691×
    if as_json {
12701×
        println!("{}", repo.status_json(&snap)?);
12711×
        return Ok(if snap.base_snapshot.is_conflicted() {
12720×
            2
1273
        } else {
12741×
            0
1275
        });
12760×
    }
12770×
    if !snap.base_snapshot.is_conflicted() {
12780×
        println!("The working copy's base has no conflicts.");
12790×
        return Ok(0);
12800×
    }
12810×
    let mut remaining = 0;
12820×
    for (p, f) in &snap.base_snapshot.files {
12830×
        if !f.is_conflicted() {
12840×
            continue;
12850×
        }
12860×
        match snap
12870×
            .statuses
12880×
            .iter()
12890×
            .find(|s| s.path == *p)
12900×
            .map(|s| s.status)
1291
        {
12920×
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
12930×
            Some(ChangeStatus::ConflictEdited) => {
12940×
                remaining += 1;
12950×
                println!("markers    {p}");
12960×
            }
12970×
            _ => {
12980×
                remaining += 1;
12990×
                println!("unresolved {p}");
13000×
            }
1301
        }
1302
    }
13030×
    for c in &snap.base_snapshot.tree.conflicts {
13040×
        remaining += 1;
13050×
        println!("tree       {c:?}");
13060×
    }
13070×
    if remaining == 0 {
13080×
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
13090×
        Ok(0)
1310
    } else {
13110×
        Ok(2)
1312
    }
13131×
}
1314
13150×
pub fn undo() -> Result<i32> {
13160×
    let repo = open()?;
13170×
    let op = repo.undo()?;
13180×
    println!("{} now at: {}", ui::done("Undone;"), ui::dim(&op.command));
13190×
    where_now(&repo);
13200×
    Ok(0)
13210×
}
1322
13231×
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
13241×
    let repo = open()?;
13251×
    let ops = repo.op_log()?;
1326
    // What each operation changed, against the one before it.
132711×
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
132811×
        match ops.get(i + 1) {
132910×
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
13301×
            None => Ok(vec![]),
1331
        }
133211×
    };
13331×
    if as_json {
13341×
        let mut items = Vec::new();
133511×
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
133611×
            let summary: Vec<String> = changes_of(i)?
133711×
                .iter()
133811×
                .map(|c| change_words(&repo, c))
133911×
                .collect();
134011×
            items.push(json::obj([
134111×
                ("id", json::s(&r.to_hex())),
134211×
                ("when_ms", json::n(op.hlc.wall_ms)),
134311×
                ("command", json::s(&op.command)),
134411×
                ("snapshot", json::b(op.is_snapshot())),
134511×
                ("current", json::b(i == 0)),
134611×
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1347
            ]));
1348
        }
13491×
        println!("{}", json::arr(items));
13501×
        return Ok(0);
13510×
    }
13520×
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
13530×
    let id = |r: &oxy_core::hash::ObjectRef| {
13540×
        let hex = r.to_hex();
13550×
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
13560×
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
13570×
    };
13580×
    let rail = ui::dim(ui::glyph("│", "|"));
13590×
    let (mut i, mut shown) = (0, 0);
13600×
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
13610×
        let (r, op) = &ops[i];
13620×
        let bullet = if i == 0 {
13630×
            ui::ok(ui::glyph("@", "@"))
1364
        } else {
13650×
            ui::dim(ui::glyph("○", "o"))
1366
        };
1367
        // A run of snapshots folds into one entry.
13680×
        let mut run = 1;
13690×
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
13700×
            run += 1;
13710×
        }
13720×
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
13730×
        if op.is_snapshot() {
13740×
            let span = if run > 1 {
13750×
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1376
            } else {
13770×
                String::new()
1378
            };
13790×
            println!(
1380
                "{bullet}  {}{} {when}",
13810×
                id(r),
13820×
                if span.is_empty() {
13830×
                    String::new()
1384
                } else {
13850×
                    format!(" {span}")
1386
                }
1387
            );
13880×
            println!(
1389
                "{rail}  {}",
13900×
                ui::dim(if run == 1 {
13910×
                    "working-copy snapshot".to_string()
1392
                } else {
13930×
                    format!("{run} working-copy snapshots")
1394
                })
1395
            );
1396
        } else {
13970×
            println!("{bullet}  {} {when}", id(r));
13980×
            let words: Vec<String> = changes_of(i)?
13990×
                .iter()
14000×
                .map(|c| change_words(&repo, c))
14010×
                .collect();
14020×
            let summary = if words.is_empty() {
14030×
                if i + 1 == ops.len() {
14040×
                    "created the repository".to_string()
1405
                } else {
14060×
                    "no bookmark or working-copy change".to_string()
1407
                }
1408
            } else {
14090×
                words.join("; ")
1410
            };
14110×
            println!(
1412
                "{rail}  {}",
14130×
                if i == 0 {
14140×
                    ui::subject(&summary)
1415
                } else {
14160×
                    summary
1417
                }
1418
            );
14190×
            let cmd = op.command.lines().next().unwrap_or("");
14200×
            let cmd: String = cmd.chars().take(100).collect();
14210×
            println!("{rail}  {}", ui::dim(cmd));
1422
        }
14230×
        i += run;
14240×
        shown += 1;
1425
    }
14260×
    if i < ops.len() {
14270×
        println!(
14280×
            "{}",
14290×
            ui::dim(format!(
14300×
                "{} {} older; pass -n to see more",
14310×
                ui::glyph("…", "..."),
14320×
                plural(ops.len() - i, "operation")
14330×
            ))
14340×
        );
14350×
    }
14360×
    Ok(0)
14371×
}
1438
1439
/// One change an operation made, in words.
144011×
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1441
    use oxy_core::repo::ViewChange::*;
14422×
    match c {
14430×
        BookmarkCreated { name, heads } => {
14440×
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1445
        }
14460×
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
14472×
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
14481×
        BookmarkMoved { name, from, to } => format!(
1449
            "{name}: {from} {} {}",
14501×
            ui::glyph("→", "->"),
14511×
            plural(*to, "head")
1452
        ),
14531×
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
14540×
        TagCreated { name } => format!("tagged {name}"),
14550×
        TagDeleted { name } => format!("removed tag {name}"),
14560×
        Policy => "trust policy changed".to_string(),
14578×
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
14588×
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
14590×
            Err(_) => "working copy moved".to_string(),
1460
        },
1461
    }
146211×
}
1463
14640×
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
14650×
    let repo = open()?;
14660×
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
14670×
    let r = repo.op_restore(op, discard)?;
14680×
    sp.done(&format!(
14690×
        "{} to operation {} {}",
14700×
        ui::done("Restored"),
14710×
        ui::hash(r.op.short(12)),
14720×
        ui::dim(r.command.lines().next().unwrap_or(""))
14730×
    ));
14740×
    println!(
1475
        "  {} {}",
14760×
        ui::note(),
14770×
        ui::dim(format!(
1478
            "{} written, {} removed; oxy undo goes back again",
14790×
            plural(r.checkout.written, "file"),
1480
            r.checkout.removed
1481
        ))
1482
    );
14830×
    where_now(&repo);
14840×
    Ok(0)
14850×
}
1486
14870×
pub fn op_revert(op: &str) -> Result<i32> {
14880×
    let repo = open()?;
14890×
    let r = repo.op_revert(op)?;
14900×
    let view = repo.view()?;
14910×
    let names: Vec<String> = r
14920×
        .reverted
14930×
        .iter()
14940×
        .map(|n| {
14950×
            if view.bookmarks.contains_key(n) {
14960×
                ui::bookmark(n)
1497
            } else {
14980×
                format!("{} (removed)", ui::bookmark(n))
1499
            }
15000×
        })
15010×
        .collect();
15020×
    println!(
1503
        "{} operation {} {}",
15040×
        ui::done("Reverted"),
15050×
        ui::hash(r.op.short(12)),
15060×
        ui::dim(r.command.lines().next().unwrap_or(""))
1507
    );
15080×
    println!(
1509
        "  {} {}",
15100×
        ui::note(),
15110×
        ui::dim(format!("as before it: {}", names.join(", ")))
1512
    );
15130×
    if !r.kept.is_empty() {
15140×
        println!(
15150×
            "  {} {}",
15160×
            ui::caution(),
15170×
            ui::warn(format!(
15180×
                "left as they are, having moved again since: {}",
15190×
                r.kept.join(", ")
15200×
            ))
15210×
        );
15220×
    }
15230×
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
15240×
        println!(
15250×
            "  {} {}",
15260×
            ui::note(),
15270×
            ui::dim("the working copy has work of its own: oxy checkout to move it")
15280×
        );
15290×
    }
15300×
    where_now(&repo);
15310×
    Ok(0)
15320×
}
1533
1534
/// Where the working copy and bookmark are now, after a command moved
1535
/// them (as jj says "Working copy now at").
153628×
pub fn where_now(repo: &Repo) {
153728×
    let Ok((_, wc)) = repo.working_copy() else {
15380×
        return;
1539
    };
154028×
    let heads = repo.bookmark_heads().unwrap_or_default();
154128×
    let newest = heads
154228×
        .iter()
154339×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
154428×
        .max_by_key(|(m, _)| m.hlc);
154528×
    println!(
1546
        "  {} {}",
154728×
        ui::dim(format!("{:<13}", "Working copy")),
154828×
        ui::id(wc.change_id.short(8))
1549
    );
155028×
    let tail = match newest {
155128×
        Some((m, _)) => format!(
1552
            ", newest {} {}",
155328×
            ui::id(m.change_id.short(8)),
155428×
            subject_of(&m.message)
1555
        ),
15560×
        None => String::new(),
1557
    };
155828×
    println!(
1559
        "  {} {}: {}{tail}",
156028×
        ui::dim(format!("{:<13}", "Bookmark")),
156128×
        ui::bookmark(&repo.config.bookmark),
156228×
        plural(heads.len(), "head")
1563
    );
156428×
}
1565
15660×
pub fn gc(now: bool) -> Result<i32> {
15670×
    let repo = open()?;
15680×
    let sp = ui::spinner("Packing and pruning…");
15690×
    let r = repo.gc_with(now, &mut |phase| sp.set(&format!("{phase}…")))?;
15700×
    sp.clear();
15710×
    if r.packed.objects > 0 {
15720×
        println!(
15730×
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
15740×
            plural(r.packed.objects, "object"),
15750×
            r.packed.raw_bytes,
15760×
            r.packed.packed_bytes,
15770×
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
15780×
        );
15790×
    }
15800×
    println!(
1581
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
15820×
        plural(r.reachable, "object"),
15830×
        plural(r.pruned.objects, "unreachable object"),
1584
        r.pruned.bytes,
15850×
        if r.pruned.deferred > 0 {
15860×
            format!(
1587
                "; {} deferred by the grace period (use --now)",
15880×
                plural(r.pruned.deferred, "object")
1589
            )
1590
        } else {
15910×
            String::new()
1592
        },
15930×
        if r.merged_packs > 0 {
15940×
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1595
        } else {
15960×
            String::new()
1597
        },
15980×
        plural(repo.store().pack_count(), "pack")
1599
    );
16000×
    Ok(0)
16010×
}
1602
1603
/// `oxy gc --remote NAME`: fold a store remote's bundles into one.
16042×
pub fn gc_remote(name: &str, now: bool) -> Result<i32> {
16052×
    let repo = open()?;
16062×
    let sp = ui::spinner(&format!("Folding {name}'s bundles…"));
16072×
    let r = repo.gc_remote(name, now)?;
16081×
    sp.clear();
16091×
    if r.merged > 0 {
16101×
        println!(
16111×
            "{} {} into one of {} bytes ({})",
16121×
            ui::done("Folded"),
16131×
            plural(r.merged, "bundle"),
16141×
            r.bundle_bytes,
16151×
            plural(r.changes, "change")
16161×
        );
16171×
    } else {
16180×
        println!(
16190×
            "{} {}",
16200×
            ui::note(),
16210×
            ui::dim("nothing to fold: one bundle holds everything")
16220×
        );
16230×
    }
16241×
    println!(
1625
        "  {} {}",
16261×
        ui::note(),
16271×
        ui::dim(format!(
1628
            "removed {}{}",
16291×
            plural(r.deleted, "superseded bundle"),
16301×
            if r.deferred > 0 {
16310×
                format!(
1632
                    "; {} kept for readers that may still fetch them (use --now)",
16330×
                    plural(r.deferred, "bundle")
1634
                )
1635
            } else {
16361×
                String::new()
1637
            }
1638
        ))
1639
    );
16401×
    Ok(0)
16412×
}
1642
1643
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
16440×
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1645
    use oxy_core::repo::Health;
16460×
    let repo = open()?;
16470×
    let sp = ui::spinner(if offline {
16480×
        "Checking…"
1649
    } else {
16500×
        "Checking, and contacting remotes…"
1651
    });
16520×
    let r = repo.doctor(!offline);
16530×
    sp.clear();
16540×
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
16550×
    let word = |h: Health| match h {
16560×
        Health::Ok => "ok",
16570×
        Health::Warn => "warning",
16580×
        Health::Fail => "fail",
16590×
    };
16600×
    if as_json {
16610×
        let checks: Vec<String> = r
16620×
            .checks
16630×
            .iter()
16640×
            .map(|c| {
16650×
                json::obj([
16660×
                    ("area", json::s(&c.area)),
16670×
                    ("health", json::s(word(c.health))),
16680×
                    ("message", json::s(&c.message)),
16690×
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
16700×
                ])
16710×
            })
16720×
            .collect();
16730×
        println!(
1674
            "{}",
16750×
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1676
        );
16770×
        return Ok(code);
16780×
    }
16790×
    let mut last = "";
16800×
    for c in &r.checks {
16810×
        if c.area != last {
16820×
            println!("{}", ui::section(&c.area));
16830×
            last = &c.area;
16840×
        }
16850×
        let mark = match c.health {
16860×
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
16870×
            Health::Warn => ui::caution(),
16880×
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1689
        };
16900×
        println!("  {mark} {}", c.message);
16910×
        if let Some(h) = &c.hint {
16920×
            println!("    {} {}", ui::dim("→"), ui::dim(h));
16930×
        }
1694
    }
16950×
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
16960×
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
16970×
    if fails + warns == 0 {
16980×
        println!("{}", ui::done("Everything looks right."));
16990×
    } else {
17000×
        println!(
1701
            "{} {}, {}.",
17020×
            if fails > 0 {
17030×
                ui::err(ui::glyph("✖", "x"))
1704
            } else {
17050×
                ui::caution()
1706
            },
17070×
            plural(fails, "problem"),
17080×
            plural(warns, "warning")
1709
        );
1710
    }
17110×
    Ok(code)
17120×
}
1713
1714
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
17150×
pub fn fsck(as_json: bool) -> Result<i32> {
1716
    use oxy_core::repo::Severity;
17170×
    let repo = open()?;
17180×
    let sp = ui::spinner("Checking every object…");
17190×
    let r = repo.fsck()?;
17200×
    sp.clear();
17210×
    let code = if r.errors() > 0 { 1 } else { 0 };
17220×
    if as_json {
17230×
        let problems: Vec<String> = r
17240×
            .problems
17250×
            .iter()
17260×
            .map(|p| {
17270×
                json::obj([
1728
                    (
1729
                        "severity",
17300×
                        json::s(match p.severity {
17310×
                            Severity::Error => "error",
17320×
                            Severity::Warning => "warning",
1733
                        }),
1734
                    ),
1735
                    (
17360×
                        "object",
17370×
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1738
                    ),
17390×
                    ("what", json::s(&p.what)),
1740
                ])
17410×
            })
17420×
            .collect();
17430×
        println!(
1744
            "{}",
17450×
            json::obj([
17460×
                ("ok", json::b(code == 0)),
17470×
                ("objects", json::n(r.objects)),
17480×
                ("ops", json::n(r.ops)),
17490×
                ("changes", json::n(r.changes)),
17500×
                ("signed", json::n(r.signed)),
17510×
                ("unsigned", json::n(r.unsigned)),
17520×
                ("checkpoints", json::n(r.checkpoints)),
17530×
                ("attestations", json::n(r.attestations)),
17540×
                ("errors", json::n(r.errors())),
17550×
                ("warnings", json::n(r.warnings())),
17560×
                ("problems", json::arr(problems)),
17570×
            ])
1758
        );
17590×
        return Ok(code);
17600×
    }
17610×
    println!(
1762
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
17630×
        plural(r.objects, "object"),
17640×
        plural(r.ops, "operation"),
17650×
        plural(r.changes, "change"),
1766
        r.signed,
1767
        r.unsigned,
17680×
        plural(r.checkpoints, "checkpoint"),
17690×
        plural(r.attestations, "attestation"),
1770
    );
17710×
    for p in &r.problems {
17720×
        let obj = p
17730×
            .object
17740×
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
17750×
            .unwrap_or_default();
17760×
        match p.severity {
17770×
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
17780×
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1779
        }
1780
    }
17810×
    if r.problems.is_empty() {
17820×
        println!("{}", ui::done("No problems found."));
17830×
    } else if code == 0 {
17840×
        println!(
17850×
            "{}",
17860×
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
17870×
        );
17880×
    } else {
17890×
        println!(
17900×
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
17910×
            ui::err(ui::glyph("✖", "x")),
17920×
            plural(r.errors(), "error"),
17930×
            plural(r.warnings(), "warning")
17940×
        );
17950×
    }
17960×
    Ok(code)
17970×
}
1798
1799
/// The head the working copy sits on, for commands that default to it. With
1800
/// several heads beneath the working copy, the most recently made one is
1801
/// chosen and announced.
18020×
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
18030×
    let snap = repo.snapshot_status("oxy")?;
18040×
    let base = snap.base.maximal(&snap.wc.deps);
18050×
    match base.as_slice() {
18060×
        [] => anyhow::bail!("the working copy sits on no change yet"),
18070×
        [h] => Ok(*h),
18080×
        many => {
18090×
            let latest = many
18100×
                .iter()
18110×
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
18120×
                .copied()
18130×
                .unwrap();
18140×
            let c = repo.store().get_change(&latest)?;
18150×
            println!(
1816
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
18170×
                short_id(&c),
18180×
                latest.short(12),
18190×
                many.len()
1820
            );
18210×
            Ok(latest)
1822
        }
1823
    }
18240×
}
1825
1826
/// `oxy describe` without -m: the working copy's name for a build.
18274×
pub fn describe_name(as_json: bool) -> Result<i32> {
18284×
    let repo = open()?;
18294×
    let d = repo.describe_working_copy()?;
18304×
    if as_json {
18313×
        println!(
1832
            "{}",
18333×
            json::obj([
18343×
                ("describe", json::s(&d.line())),
18353×
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
18363×
                ("distance", json::n(d.distance)),
18373×
                ("bookmark", json::s(&d.bookmark)),
18383×
                ("change", json::s(&d.change.to_hex())),
18393×
                ("hash", json::s(&d.hash.to_hex())),
18403×
                ("dirty", json::b(d.dirty)),
1841
            ])
1842
        );
18431×
    } else {
18441×
        println!("{}", d.line());
18451×
    }
18464×
    Ok(0)
18474×
}
1848
18490×
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
18500×
    let repo = open()?;
18510×
    let h = match change {
18520×
        Some(c) => repo.resolve_change(c)?,
18530×
        None => current_head(&repo)?,
1854
    };
18550×
    let new = repo.describe(&h, message)?;
18560×
    let c = repo.store().get_change_meta(&new)?;
18570×
    println!(
1858
        "{} {} {}  {}",
18590×
        ui::done("Described"),
18600×
        ui::id(c.change_id.short(8)),
18610×
        ui::hash(format!("#{}", new.short(12))),
18620×
        ui::subject(subject_of(message))
1863
    );
18640×
    Ok(0)
18650×
}
1866
18670×
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
18680×
    let repo = open()?;
18690×
    let new = match into {
18700×
        Some(spec) => {
18710×
            let target = repo.resolve_change(spec)?;
18720×
            repo.amend_into(&target, message)?
1873
        }
18740×
        None => repo.amend(message)?,
1875
    };
18760×
    let c = repo.store().get_change_meta(&new)?;
18770×
    println!(
1878
        "{} {} {}  {}",
18790×
        ui::done("Amended"),
18800×
        ui::id(c.change_id.short(8)),
18810×
        ui::hash(format!("#{}", new.short(12))),
18820×
        ui::subject(subject_of(&c.message))
1883
    );
18840×
    where_now(&repo);
18850×
    Ok(0)
18860×
}
1887
18880×
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
18890×
    let repo = open()?;
18900×
    let Some(r) = revset else {
18910×
        let h = repo.resolve_change(change.unwrap_or_default())?;
18920×
        abandon_one(&repo, h)?;
18930×
        where_now(&repo);
18940×
        return Ok(0);
1895
    };
1896
    // A revset: say what it selects, refuse an empty set, ask above a few.
18970×
    let selected = repo.revset(r)?;
18980×
    let wc = repo.working_copy().ok().map(|(h, _)| h);
18990×
    let hashes: Vec<ChangeHash> = selected
19000×
        .hashes
19010×
        .iter()
19020×
        .copied()
19030×
        .filter(|h| Some(*h) != wc)
19040×
        .collect();
19050×
    if hashes.is_empty() {
19060×
        anyhow::bail!("{r:?} selects no change to abandon");
19070×
    }
19080×
    println!(
1909
        "{} {} selects {}:",
19100×
        ui::section("abandon"),
19110×
        ui::id(r),
19120×
        plural(hashes.len(), "change")
1913
    );
19140×
    for h in &hashes {
19150×
        if let Some(m) = selected.metas.get(h) {
19160×
            println!(
19170×
                "  {} {}  {}",
19180×
                ui::id(m.change_id.short(8)),
19190×
                ui::hash(format!("#{}", h.short(12))),
19200×
                subject_of(&m.message)
19210×
            );
19220×
        }
1923
    }
1924
    const ASK_ABOVE: usize = 5;
19250×
    if hashes.len() > ASK_ABOVE && !yes {
19260×
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
19270×
    }
1928
    // Newest first: abandoning a change rewrites what depends on it, so a
1929
    // later member is found again by its ChangeId.
19300×
    let mut done = 0;
19310×
    for h in &hashes {
19320×
        let Some(m) = selected.metas.get(h) else {
19330×
            continue;
1934
        };
19350×
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
19360×
            Ok(h) => h,
19370×
            Err(_) => continue,
1938
        };
19390×
        abandon_one(&repo, now)?;
19400×
        done += 1;
1941
    }
19420×
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
19430×
    where_now(&repo);
19440×
    Ok(0)
19450×
}
1946
19470×
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
19480×
    let c = repo.store().get_change_meta(&h)?;
19490×
    let notes = repo.abandon(&h)?;
19500×
    println!(
1951
        "{} {} {}  {}",
19520×
        ui::done("Abandoned"),
19530×
        ui::id(c.change_id.short(8)),
19540×
        ui::hash(format!("#{}", h.short(12))),
19550×
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
1956
    );
19570×
    for n in notes {
19580×
        println!("  {} {n}", ui::note());
19590×
    }
19600×
    Ok(())
19610×
}
1962
19630×
pub fn checkpoint() -> Result<i32> {
19640×
    let repo = open()?;
19650×
    let sp = ui::spinner("Writing checkpoint…");
19660×
    let (r, changes, bytes) = repo.checkpoint()?;
19670×
    sp.done(&format!(
19680×
        "{} {} of {} ({} bytes) for {}",
19690×
        ui::done("Checkpoint"),
19700×
        ui::hash(format!("#{}", r.short(12))),
19710×
        plural(changes, "change"),
19720×
        bytes,
19730×
        ui::id(&repo.config.bookmark)
19740×
    ));
19750×
    Ok(0)
19760×
}
1977
1978
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
19790×
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
19800×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
19810×
        return Ok(1);
1982
    };
19830×
    let info = repo.quick_status()?;
19840×
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
19850×
        oxy_core::repo::GLYPH_PROMPT_FORMAT
1986
    } else {
19870×
        format
1988
    };
19890×
    let line = match color {
19900×
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
19910×
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
19920×
        Some(_) => info.format_colored(fmt, ("", "")),
19930×
        None => info.format(fmt),
1994
    };
19950×
    println!("{line}");
19960×
    Ok(0)
19970×
}
1998
19990×
pub fn sparse(paths: &[String]) -> Result<i32> {
20000×
    let mut repo = open()?;
20010×
    if paths.is_empty() {
20020×
        if repo.config.sparse_paths.is_empty() {
20030×
            println!("No sparse filter: the whole tree is materialized.");
20040×
        } else {
20050×
            println!("{}", ui::heading("Sparse filter"));
20060×
            for p in &repo.config.sparse_paths {
20070×
                println!("  {}", ui::path(p));
20080×
            }
2009
        }
20100×
        return Ok(0);
20110×
    }
20120×
    let snap = repo.snapshot("oxy sparse")?;
20130×
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
20140×
        anyhow::bail!(
2015
            "the working copy has changes; commit them before changing the sparse filter"
2016
        );
20170×
    }
20180×
    repo.config.set("filter.paths", &paths.join(","))?;
20190×
    repo.save_config()?;
20200×
    let heads = repo.bookmark_heads()?;
20210×
    let sp = ui::spinner("Re-checking out with the new filter…");
20220×
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
20230×
    sp.done(&format!(
20240×
        "{} {}: {} written, {} removed",
20250×
        ui::done("Sparse filter set to"),
20260×
        ui::path(paths.join(",")),
20270×
        plural(r.written, "file"),
20280×
        r.removed
20290×
    ));
20300×
    Ok(0)
20310×
}
2032
20332×
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
20342×
    let repo = open()?;
20352×
    repo.snapshot_status("oxy tag")?;
20362×
    let heads = if changes.is_empty() {
20372×
        repo.bookmark_heads()?
2038
    } else {
20390×
        let mut heads = Vec::new();
20400×
        for c in changes {
20410×
            heads.extend(repo.resolve_heads(c)?);
2042
        }
20430×
        heads
2044
    };
20452×
    let t = repo.tag_create(name, &heads, message)?;
20462×
    println!(
2047
        "{} {} {} {} ({}){}",
20482×
        ui::done("Tagged"),
20492×
        ui::bookmark(&t.name),
20502×
        ui::dim(ui::glyph("→", "->")),
20512×
        ui::hash(format!("#{}", t.state.short(12))),
20522×
        plural(t.heads.len(), "head"),
20532×
        t.signer
20542×
            .map(|s| format!(", signed by {s}"))
20552×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2056
    );
20572×
    Ok(0)
20582×
}
2059
20601×
pub fn tag_list(as_json: bool) -> Result<i32> {
20611×
    let repo = open()?;
20621×
    let tags = repo.tags()?;
20631×
    if as_json {
20641×
        println!(
2065
            "{}",
20661×
            json::arr(tags.iter().map(|t| {
20671×
                json::obj([
20681×
                    ("name", json::s(&t.name)),
20691×
                    ("state", json::s(&t.state.to_hex())),
20701×
                    ("heads", json::hashes(&t.heads)),
20711×
                    ("message", json::s(&t.message)),
2072
                    (
20731×
                        "signer",
20741×
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2075
                    ),
2076
                ])
20771×
            }))
2078
        );
20791×
        return Ok(0);
20800×
    }
20810×
    if tags.is_empty() {
20820×
        println!("{}", ui::dim("No tags."));
20830×
    }
20840×
    for t in tags {
20850×
        println!(
2086
            "{} {} {}{}{}{}",
20870×
            ui::ok(ui::glyph("⚑", "#")),
20880×
            ui::bookmark(&t.name),
2089
            // The heads, as `oxy log` shows changes, not the state hash.
20900×
            ui::hash(
20910×
                t.heads
20920×
                    .iter()
20930×
                    .map(|h| format!("#{}", h.short(12)))
20940×
                    .collect::<Vec<_>>()
20950×
                    .join(" ")
2096
            ),
20970×
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
20980×
            if t.message.is_empty() {
20990×
                String::new()
2100
            } else {
21010×
                format!("  {}", ui::subject(subject_of(&t.message)))
2102
            },
21030×
            t.signer
21040×
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
21050×
                .unwrap_or_default()
2106
        );
2107
    }
21080×
    Ok(0)
21091×
}
2110
2111
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2112
/// and workspace add take as "be on this bookmark" (oxygen#60).
21130×
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
21140×
    Ok(repo.view()?.bookmarks.contains_key(name)
21150×
        || repo
21160×
            .remote_only_bookmarks()?
21170×
            .iter()
21180×
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
21190×
}
2120
21210×
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
21220×
    let repo = open()?;
2123
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2124
    // this workspace's bookmark with that one's files.
21250×
    if let [name] = changes {
21260×
        if names_bookmark(&repo, name)? {
21270×
            let (local, _) = repo.local_bookmark_for(name)?;
21280×
            let heads = repo.resolve_heads(&local)?;
21290×
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
21300×
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
21310×
            sp.done(&format!(
21320×
                "{} {} (workspace {}) on {}",
21330×
                ui::done("Workspace created at"),
21340×
                ui::path(ws.root().display()),
21350×
                ui::id(ws.workspace().short(8)),
21360×
                ui::bookmark(&local)
21370×
            ));
21380×
            return Ok(0);
21390×
        }
21400×
    }
21410×
    let heads = if changes.is_empty() {
21420×
        None
2143
    } else {
21440×
        let mut heads = Vec::new();
21450×
        for c in changes {
21460×
            heads.extend(repo.resolve_heads(c)?);
2147
        }
21480×
        Some(heads)
2149
    };
21500×
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
21510×
    let ws = repo.workspace_add(path, heads.as_deref())?;
21520×
    sp.done(&format!(
21530×
        "{} {} (workspace {})",
21540×
        ui::done("Workspace created at"),
21550×
        ui::path(ws.root().display()),
21560×
        ui::id(ws.workspace().short(8))
21570×
    ));
21580×
    Ok(0)
21590×
}
2160
21611×
pub fn workspace_list(as_json: bool) -> Result<i32> {
21621×
    let repo = open()?;
21631×
    if as_json {
21641×
        println!(
2165
            "{}",
21661×
            json::arr(repo.workspaces()?.iter().map(|w| {
21671×
                json::obj([
21681×
                    ("id", json::s(&w.id.to_hex())),
21691×
                    ("path", json::s(&w.path.to_string_lossy())),
21701×
                    ("current", json::b(w.current)),
2171
                    (
21721×
                        "working_copy",
21731×
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2174
                    ),
2175
                ])
21761×
            }))
2177
        );
21781×
        return Ok(0);
21790×
    }
21800×
    for w in repo.workspaces()? {
21810×
        println!(
2182
            "{} {} {}{}",
21830×
            if w.current {
21840×
                ui::ok(ui::glyph("●", "*"))
2185
            } else {
21860×
                ui::dim(ui::glyph("○", "o"))
2187
            },
21880×
            ui::id(w.id.short(8)),
21890×
            ui::path(w.path.display()),
21900×
            w.working_copy
21910×
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
21920×
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2193
        );
2194
    }
21950×
    Ok(0)
21961×
}
2197
21980×
pub fn workspace_forget(spec: &str) -> Result<i32> {
21990×
    let repo = open()?;
22000×
    let all = repo.workspaces()?;
22010×
    let target = std::fs::canonicalize(spec).ok();
22020×
    let matches: Vec<_> = all
22030×
        .iter()
22040×
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
22050×
        .collect();
22060×
    let w = match matches.as_slice() {
22070×
        [w] => *w,
22080×
        [] => anyhow::bail!("no workspace matches {spec:?}"),
22090×
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2210
    };
22110×
    repo.workspace_forget(&w.id)?;
22120×
    println!(
2213
        "{} workspace {} at {}; its files were left in place.",
22140×
        ui::done("Forgot"),
22150×
        ui::id(w.id.short(8)),
22160×
        ui::path(w.path.display())
2217
    );
22180×
    Ok(0)
22190×
}
2220
22210×
pub fn lock(path: &str) -> Result<i32> {
22220×
    let repo = open()?;
22230×
    repo.lock_path(path)?;
22240×
    println!(
2225
        "{} {} {}",
22260×
        ui::done("Locked"),
22270×
        ui::path(path),
22280×
        ui::dim("(advisory, local)")
2229
    );
22300×
    Ok(0)
22310×
}
2232
22330×
pub fn unlock(path: &str) -> Result<i32> {
22340×
    let repo = open()?;
22350×
    repo.unlock_path(path)?;
22360×
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
22370×
    Ok(0)
22380×
}
2239
22400×
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
22410×
    let repo = open()?;
22420×
    let h = repo.resolve_change(change)?;
22430×
    let (h1, h2) = repo.split(&h, paths)?;
22440×
    let c1 = repo.store().get_change_meta(&h1)?;
22450×
    let c2 = repo.store().get_change_meta(&h2)?;
22460×
    println!(
2247
        "{} into {} {} and {} {}",
22480×
        ui::done("Split"),
22490×
        ui::id(c1.change_id.short(8)),
22500×
        ui::hash(format!("#{}", h1.short(12))),
22510×
        ui::id(c2.change_id.short(8)),
22520×
        ui::hash(format!("#{}", h2.short(12)))
2253
    );
22540×
    Ok(0)
22550×
}
2256
22576×
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
22586×
    let mut heads = Vec::new();
22596×
    for c in changes {
22606×
        heads.extend(repo.resolve_heads(c)?);
2261
    }
22626×
    Ok(heads)
22636×
}
2264
22656×
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
22666×
    let repo = open()?;
22676×
    repo.snapshot_status("oxy bookmark create")?;
22686×
    let heads = if changes.is_empty() {
22693×
        None
2270
    } else {
22713×
        let named = heads_from(&repo, changes)?;
22723×
        let (_, wc) = repo.working_copy()?;
22733×
        let gap = repo.state_gap(&wc.deps, &named)?;
22743×
        if upto {
22751×
            Some(gap.upto)
22762×
        } else if only || gap.earlier.is_empty() {
22771×
            Some(named)
2278
        } else {
22791×
            anyhow::bail!(
2280
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2281
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2282
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2283
                 or --only for just {0} and what it depends on.",
22841×
                changes.join(" "),
22851×
                plural(gap.earlier.len(), "change"),
22861×
                listed_changes(&repo, &gap.earlier)
2287
            );
2288
        }
2289
    };
22905×
    let heads = repo.bookmark_create(name, heads.as_deref())?;
22915×
    println!(
2292
        "{} bookmark {} {} {}",
22935×
        ui::done("Created"),
22945×
        ui::bookmark(name),
22955×
        ui::dim(ui::glyph("→", "->")),
22965×
        ui::dim(plural(heads.len(), "head"))
2297
    );
22985×
    println!(
2299
        "  {} {}",
23005×
        ui::note(),
23015×
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2302
    );
23035×
    Ok(0)
23046×
}
2305
2306
/// Up to five changes, newest last, as `  #hash subject` lines.
23072×
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
23082×
    let shown = changes.len().min(5);
23092×
    let mut lines: Vec<String> = changes[changes.len() - shown..]
23102×
        .iter()
23112×
        .map(|h| {
23122×
            let subject = repo
23132×
                .store()
23142×
                .get_change(h)
23152×
                .map(|c| subject_of(&c.message).to_string())
23162×
                .unwrap_or_default();
23172×
            format!("  #{} {subject}", h.short(12))
23182×
        })
23192×
        .collect();
23202×
    if changes.len() > shown {
23210×
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
23222×
    }
23232×
    lines.join("\n")
23242×
}
2325
23263×
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
23273×
    let repo = open()?;
23283×
    repo.snapshot_status("oxy bookmark set")?;
23293×
    let named = heads_from(&repo, changes)?;
2330
    // What the bookmark holds now and the new heads would leave out.
23313×
    let current = repo
23323×
        .bookmarks()?
23333×
        .into_iter()
23346×
        .find(|b| b.name == name)
23353×
        .map(|b| b.heads)
23363×
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
23373×
    let gap = repo.state_gap(&current, &named)?;
2338
    // A fast-forward: the new heads hold the bookmark's newest head, so
2339
    // what they leave out is older work nothing since has built on, such
2340
    // as an early change no later one depends on (oxygen#78). Keep it, as
2341
    // --upto does, and say so.
23423×
    let newest = current
23433×
        .iter()
23448×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m.hlc, *h)))
23453×
        .max()
23463×
        .map(|(_, h)| h);
2347
    // Ahead, too: a head the bookmark holds already (it would only drop
2348
    // the others) is not a move forward.
23493×
    let ahead = repo
23503×
        .load_state_history(&current)
23513×
        .is_ok_and(|st| named.iter().any(|h| !st.contains(h)));
23523×
    let forward = !only
23533×
        && ahead
23541×
        && !gap.earlier.is_empty()
23551×
        && newest.is_some_and(|n| {
23561×
            repo.load_state_history(&named)
23571×
                .is_ok_and(|st| st.contains(&n))
23581×
        });
23593×
    let heads = if upto {
23601×
        gap.upto
23612×
    } else if forward {
23621×
        println!(
2363
            "  {} {}",
23641×
            ui::note(),
23651×
            ui::dim(format!(
2366
                "{} builds on {name}'s newest head; keeping {} it holds that {0} does not depend on",
23671×
                changes.join(" "),
23681×
                plural(gap.earlier.len(), "change")
2369
            ))
2370
        );
23711×
        gap.upto
23721×
    } else if only || gap.earlier.is_empty() {
23730×
        named
2374
    } else {
23751×
        anyhow::bail!(
2376
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2377
             A state is its heads and what they depend on, not everything recorded before them.\n\
2378
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2379
             or --only for just {0} and what it depends on.",
23801×
            changes.join(" "),
23811×
            plural(gap.earlier.len(), "change"),
23821×
            listed_changes(&repo, &gap.earlier)
2383
        );
2384
    };
23852×
    let heads = repo.bookmark_set(name, &heads)?;
23862×
    println!(
2387
        "{} bookmark {} {} {}",
23882×
        ui::done("Moved"),
23892×
        ui::bookmark(name),
23902×
        ui::dim(ui::glyph("→", "->")),
23912×
        ui::dim(plural(heads.len(), "head"))
2392
    );
23932×
    Ok(0)
23943×
}
2395
23960×
pub fn bookmark_delete(name: &str) -> Result<i32> {
23970×
    let repo = open()?;
23980×
    repo.bookmark_delete(name)?;
23990×
    println!(
2400
        "{} bookmark {} {}",
24010×
        ui::done("Deleted"),
24020×
        ui::bookmark(name),
24030×
        ui::dim("(its changes stay until unreachable)")
2404
    );
24050×
    Ok(0)
24060×
}
2407
2408
/// Heads with their metadata, newest first.
24090×
fn heads_newest_first(
24100×
    repo: &Repo,
24110×
    heads: &[oxy_core::hash::ChangeHash],
24120×
) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> {
24130×
    let mut out: Vec<_> = heads
24140×
        .iter()
24150×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m)))
24160×
        .collect();
24170×
    out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc));
24180×
    out
24190×
}
2420
2421
/// One head as a line: id, hash, author, when, subject.
24220×
fn print_head(
24230×
    repo: &Repo,
24240×
    indent: &str,
24250×
    h: &oxy_core::hash::ChangeHash,
24260×
    m: &oxy_core::state::ChangeMeta,
24270×
) {
24280×
    println!(
2429
        "{indent}{} {} {}{}{}{}{}",
24300×
        ui::id(m.change_id.short(8)),
24310×
        ui::dim(format!("#{}", &h.to_hex()[..8])),
24320×
        author_name(repo, m),
24330×
        ui::sep(),
24340×
        ui::dim(ui::ago(m.hlc.wall_ms)),
24350×
        ui::sep(),
24360×
        ui::subject(subject_of(&m.message))
2437
    );
24380×
}
2439
24400×
pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result<i32> {
24410×
    let repo = open()?;
24420×
    let name = name.unwrap_or(&repo.config.bookmark).to_string();
24430×
    let view = repo.view()?;
24440×
    let st = match view.bookmarks.get(&name) {
24450×
        Some(st) => *st,
24460×
        None => match oxy_core::repo::remote_bookmark(&view, &name) {
24470×
            Some((_, _, st)) => st,
24480×
            None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"),
2449
        },
2450
    };
24510×
    let heads = repo.store().get_state(&st)?.heads;
24520×
    let shown = heads_newest_first(&repo, &heads);
24530×
    if as_json {
24540×
        println!(
2455
            "{}",
24560×
            json::obj([
24570×
                ("name", json::s(&name)),
24580×
                ("current", json::b(name == repo.config.bookmark)),
2459
                (
24600×
                    "heads",
24610×
                    json::arr(shown.iter().map(|(h, m)| {
24620×
                        json::obj([
24630×
                            ("hash", json::s(&h.to_hex())),
24640×
                            ("id", json::s(&m.change_id.to_string())),
24650×
                            ("author", json::s(&author_name(&repo, m))),
24660×
                            ("time_ms", json::n(m.hlc.wall_ms)),
24670×
                            ("subject", json::s(subject_of(&m.message))),
24680×
                        ])
24690×
                    }))
2470
                ),
2471
            ])
2472
        );
24730×
        return Ok(0);
24740×
    }
24750×
    println!(
2476
        "{} {}{}{}",
24770×
        ui::ok(ui::glyph("●", "*")),
24780×
        ui::bookmark(&name),
24790×
        ui::sep(),
24800×
        ui::dim(plural(heads.len(), "head"))
2481
    );
24820×
    for (h, m) in &shown {
24830×
        print_head(&repo, "  ", h, m);
24840×
    }
24850×
    if heads.len() > 1 {
24860×
        println!(
24870×
            "  {}",
24880×
            ui::dim("None depends on another: the bookmark is all of them and their dependencies.")
24890×
        );
24900×
    }
24910×
    Ok(0)
24920×
}
2493
24945×
pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result<i32> {
24955×
    let repo = open()?;
24965×
    let remote_only = repo.remote_only_bookmarks()?;
24975×
    if as_json {
24985×
        let mut items: Vec<String> = repo
24995×
            .bookmarks()?
25005×
            .into_iter()
250113×
            .map(|b| {
250213×
                json::obj([
250313×
                    ("name", json::s(&b.name)),
250413×
                    ("heads", json::hashes(&b.heads)),
250513×
                    ("current", json::b(b.current)),
250613×
                    ("ahead", json::opt(b.ahead, json::n)),
250713×
                    ("behind", json::opt(b.behind, json::n)),
250813×
                    ("remote", json::opt(b.remote.as_deref(), json::s)),
250913×
                ])
251013×
            })
25115×
            .collect();
25125×
        if all {
25130×
            items.extend(remote_only.iter().map(|b| {
25140×
                json::obj([
25150×
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
25160×
                    ("heads", json::hashes(&b.heads)),
25170×
                    ("current", json::b(false)),
25180×
                    ("ahead", "null".into()),
25190×
                    ("behind", "null".into()),
25200×
                    ("remote", json::s(&b.remote)),
25210×
                ])
25220×
            }));
25235×
        }
25245×
        println!("{}", json::arr(items));
25255×
        return Ok(0);
25260×
    }
25270×
    for b in repo.bookmarks()? {
25280×
        let mark = if b.current {
25290×
            ui::ok(ui::glyph("●", "*"))
2530
        } else {
25310×
            ui::dim(ui::glyph("○", "o"))
2532
        };
25330×
        let mut tail = String::new();
25340×
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
25350×
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
25360×
        }
25370×
        if let Some(n) = b.behind.filter(|n| *n > 0) {
25380×
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
25390×
        }
2540
        // Which remote, when there is a choice (oxygen#83).
25410×
        if !tail.is_empty() && repo.config.remotes.len() > 1 {
25420×
            if let Some(r) = &b.remote {
25430×
                tail += &ui::dim(format!(" {r}"));
25440×
            }
25450×
        }
25460×
        let shown = heads_newest_first(&repo, &b.heads);
2547
        // The newest head's subject, so a busy bookmark shows its latest work.
25480×
        let head = match shown.first() {
25490×
            Some(_) if verbose => String::new(),
25500×
            Some((_, m)) if b.heads.len() > 1 => format!(
2551
                "{} {}",
25520×
                ui::dim("newest"),
25530×
                ui::subject(subject_of(&m.message))
2554
            ),
25550×
            Some((_, m)) => ui::subject(subject_of(&m.message)),
25560×
            None => ui::dim("(empty)"),
2557
        };
25580×
        let head = if head.is_empty() {
25590×
            head
2560
        } else {
25610×
            format!("  {head}")
2562
        };
25630×
        println!(
2564
            "{mark} {}{}{}{tail}{head}",
25650×
            ui::bookmark(&b.name),
25660×
            ui::sep(),
25670×
            ui::dim(plural(b.heads.len(), "head"))
2568
        );
25690×
        if verbose {
25700×
            for (h, m) in &shown {
25710×
                print_head(&repo, "    ", h, m);
25720×
            }
25730×
        }
2574
    }
25750×
    if remote_only.is_empty() {
25760×
        return Ok(0);
25770×
    }
25780×
    if !all {
25790×
        println!(
2580
            "{}",
25810×
            ui::dim(format!(
2582
                "  and {} only on a remote: oxy bookmark list --all",
25830×
                plural(remote_only.len(), "bookmark")
2584
            ))
2585
        );
25860×
        return Ok(0);
25870×
    }
25880×
    for b in &remote_only {
25890×
        println!(
25900×
            "{} {}{}{}",
25910×
            ui::dim(ui::glyph("◌", ".")),
25920×
            ui::dim(format!("{}/{}", b.remote, b.name)),
25930×
            ui::sep(),
25940×
            ui::dim(plural(b.heads.len(), "head"))
25950×
        );
25960×
    }
25970×
    println!(
2598
        "  {} {}",
25990×
        ui::note(),
26000×
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2601
    );
26020×
    Ok(0)
26035×
}
2604
26053×
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
26063×
    let mut repo = open()?;
26073×
    let from = repo.config.bookmark.clone();
26083×
    let (local, created_from) = repo.local_bookmark_for(name)?;
26093×
    if let Some(remote) = created_from {
26100×
        println!(
26110×
            "{} {} from {}",
26120×
            ui::done("Created"),
26130×
            ui::bookmark(&local),
26140×
            ui::dim(format!("{remote}/{local}"))
26150×
        );
26163×
    }
26173×
    let name = local.as_str();
2618
    // Only behind its remote: take the remote's state, so the switch does
2619
    // not check out a stale one (oxygen#74).
26203×
    if let Some(n) = repo.catch_up_bookmark(name)? {
26210×
        println!(
26220×
            "{} {} with {}: {} it lacked",
26230×
            ui::done("Caught up"),
26240×
            ui::bookmark(name),
26250×
            ui::dim(format!("{}/{name}", repo.default_remote())),
26260×
            plural(n, "change")
26270×
        );
26283×
    }
26293×
    let sp = ui::spinner(&format!("Switching to {name}…"));
26303×
    let (r, carried) = if carry {
26310×
        repo.bookmark_switch_carry(name)?
2632
    } else {
26333×
        (repo.bookmark_switch(name, discard)?, vec![])
2634
    };
26353×
    sp.done(&format!(
2636
        "{} to {}: {} written, {} removed{}",
26373×
        ui::done("Switched"),
26383×
        ui::bookmark(name),
26393×
        plural(r.written, "file"),
2640
        r.removed,
26413×
        if carried.is_empty() {
26423×
            String::new()
2643
        } else {
26440×
            format!("; carried {}", plural(carried.len(), "changed path"))
2645
        }
2646
    ));
26473×
    if r.conflicted {
26480×
        println!(
26490×
            "  {} {}",
26500×
            ui::caution(),
26510×
            ui::warn("this state has conflicts; see oxy status")
26520×
        );
26533×
    }
2654
    // Say when the new state leaves out work the old one had: a state is
2655
    // its heads and what they depend on, which can be far less than a Git
2656
    // user expects.
26573×
    if r.lacks > 0 {
26581×
        println!(
26591×
            "  {} {}",
26601×
            ui::note(),
26611×
            ui::dim(format!(
26621×
                "{name} lacks {} that {from} has",
26631×
                plural(r.lacks, "change")
26641×
            ))
26651×
        );
26662×
    }
26673×
    super::sync::subrepos_behind(&repo);
26683×
    where_now(&repo);
26693×
    Ok(0)
26703×
}
2671
26720×
pub fn merge(bookmark: &str) -> Result<i32> {
26730×
    let repo = open()?;
26740×
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
26750×
    let r = repo.merge(bookmark)?;
26760×
    if !r.changed {
26770×
        sp.done(&format!(
26780×
            "{} {}",
26790×
            ui::ok(ui::glyph("✔", "*")),
26800×
            ui::dim(format!(
26810×
                "{} already contains {bookmark}",
26820×
                repo.config.bookmark
26830×
            ))
26840×
        ));
26850×
        return Ok(0);
26860×
    }
26870×
    sp.done(&format!(
2688
        "{} {} into {}: now {}{}",
26890×
        ui::done("Merged"),
26900×
        ui::bookmark(bookmark),
26910×
        ui::bookmark(&repo.config.bookmark),
26920×
        plural(r.heads.len(), "head"),
26930×
        ui::dim(if r.checked_out {
26940×
            "; working copy updated"
2695
        } else {
26960×
            "; run oxy checkout to update the working copy"
2697
        })
2698
    ));
26990×
    let snap = repo.snapshot("oxy merge")?;
27000×
    if snap.base_snapshot.is_conflicted() {
27010×
        println!(
27020×
            "  {} {}",
27030×
            ui::caution(),
27040×
            ui::warn("the result has conflicts; see oxy status")
27050×
        );
27060×
    }
27070×
    where_now(&repo);
27080×
    Ok(0)
27090×
}
2710
27110×
pub fn squash(change: &str, into: &str) -> Result<i32> {
27120×
    let repo = open()?;
27130×
    let c = repo.resolve_change(change)?;
27140×
    let d = repo.resolve_change(into)?;
27150×
    let sp = ui::spinner("Squashing…");
27160×
    let h = repo.squash(&c, &d)?;
27170×
    let new = repo.store().get_change_meta(&h)?;
27180×
    sp.done(&format!(
27190×
        "{} into {} {}  {}",
27200×
        ui::done("Squashed"),
27210×
        ui::id(new.change_id.short(8)),
27220×
        ui::hash(format!("#{}", h.short(12))),
27230×
        ui::subject(subject_of(&new.message))
27240×
    ));
27250×
    Ok(0)
27260×
}
2727
27280×
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
27290×
    let repo = open()?;
27300×
    let c = repo.resolve_change(change)?;
27310×
    let mut heads = Vec::new();
27320×
    for o in onto {
27330×
        heads.extend(repo.resolve_heads(o)?);
2734
    }
27350×
    let sp = ui::spinner("Rebasing…");
27360×
    let h = match repo.rebase(&c, &heads) {
27370×
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
27380×
            let r = repo.rebase_into_working_copy(&c, &heads)?;
27390×
            sp.done(&format!(
27400×
                "{} {} into {}: now {}",
27410×
                ui::done("Merged"),
27420×
                onto.join(" "),
27430×
                ui::bookmark(&repo.config.bookmark),
27440×
                plural(r.heads.len(), "head"),
27450×
            ));
27460×
            if r.checked_out {
27470×
                println!(
27480×
                    "  {} {}",
27490×
                    ui::caution(),
27500×
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
27510×
                );
27520×
            } else {
27530×
                println!(
27540×
                    "  {} {}",
27550×
                    ui::caution(),
27560×
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
27570×
                );
27580×
            }
27590×
            where_now(&repo);
27600×
            return Ok(0);
2761
        }
27620×
        other => other?,
2763
    };
27640×
    let new = repo.store().get_change_meta(&h)?;
27650×
    sp.done(&format!(
27660×
        "{} {} {}  {}",
27670×
        ui::done("Rebased"),
27680×
        ui::id(new.change_id.short(8)),
27690×
        ui::hash(format!("#{}", h.short(12))),
27700×
        ui::dim(format!(
27710×
            "now depends on {}",
27720×
            plural(new.deps.len(), "change")
27730×
        ))
27740×
    ));
27750×
    where_now(&repo);
27760×
    Ok(0)
27770×
}