OXYGENHUB

Coverage / src/cli/workspace.rs 38.0%

849 of 2237 lines run, 76 of 315 functions · run #257 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
1712×
pub fn init(path: Option<PathBuf>, bare: bool, store: Option<&str>) -> Result<i32> {
1812×
    let path = path.unwrap_or(std::env::current_dir()?);
1912×
    let repo = Repo::init_new(&path, bare, store)?;
2012×
    println!(
21
        "{} {}oxy repository in {}",
2212×
        ui::done("Initialized"),
2312×
        if bare { "bare " } else { "" },
2412×
        ui::path(repo.root().display())
25
    );
2612×
    println!(
27
        "{}",
2812×
        ui::kv("bookmark", ui::bookmark(&repo.config.bookmark))
29
    );
3012×
    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×
        );
4212×
    }
4312×
    println!(
44
        "{}",
4512×
        ui::kv(
4612×
            "author",
4712×
            format!(
48
                "{} <{}>",
4912×
                ui::author(&repo.config.author_name),
50
                repo.config.author_email
51
            )
52
        )
53
    );
5412×
    Ok(0)
5512×
}
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.
7131×
fn print_untracked_nested(repo: &Repo, nested: &[String]) {
7231×
    if nested.is_empty() {
7329×
        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
    );
10231×
}
103
104
/// The working copy's changed paths, or that it is clean.
1055×
fn print_statuses(statuses: &[oxy_core::repo::PathStatus]) {
1065×
    if statuses.is_empty() {
1073×
        println!(
108
            "  {} {}",
1093×
            ui::ok(ui::glyph("✔", "*")),
1103×
            ui::dim("nothing to commit, working copy clean")
111
        );
1123×
        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×
    }
1225×
}
123
124
/// Say when the working copy has fallen behind its own bookmark: a
125
/// "clean" status there hid a pull that left it on old code (oxygen#89).
1265×
fn print_behind(repo: &Repo) {
1275×
    if let Ok(Some(n)) = repo.working_copy_behind() {
1280×
        println!(
1290×
            "  {} {}",
1300×
            ui::caution(),
1310×
            ui::warn(format!(
1320×
                "the working copy is behind {}: it lacks {} the bookmark has; oxy checkout brings it up",
1330×
                repo.config.bookmark,
1340×
                plural(n, "change")
1350×
            ))
1360×
        );
1375×
    }
1385×
}
139
1408×
pub fn status(json: bool) -> Result<i32> {
1418×
    let repo = open()?;
142
    // Answered by the manifest alone, with no history to load (oxygen#35,
143
    // #41): a clean working copy, or one as the last snapshot left it.
1448×
    let known = if json {
1453×
        None
146
    } else {
1475×
        repo.status_by_manifest()?
148
    };
1498×
    if let Some(statuses) = known {
1503×
        let (_, wc) = repo.working_copy()?;
1513×
        let heads = repo.bookmark_heads()?;
1523×
        println!(
153
            "{} {}{}working copy {}{}{}",
1543×
            ui::dim("On"),
1553×
            ui::bookmark(&repo.config.bookmark),
1563×
            ui::sep(),
1573×
            ui::id(wc.change_id.short(8)),
1583×
            ui::sep(),
1593×
            ui::dim(plural(heads.len(), "head"))
160
        );
1613×
        print_behind(&repo);
1623×
        print_statuses(&statuses);
1633×
        print_untracked_nested(&repo, &repo.untracked_nested());
1643×
        return Ok(0);
1655×
    }
1665×
    let sp = ui::spinner("Snapshotting the working copy…");
1675×
    let snap = repo.snapshot_status("oxy status")?;
1685×
    let heads = {
1695×
        let _t = oxy_core::timing::phase("status: heads");
1705×
        repo.bookmark_heads()?
171
    };
1725×
    let _drop = oxy_core::timing::phase("status: print and drop");
1735×
    sp.clear();
1745×
    if json {
1753×
        println!("{}", repo.status_json(&snap)?);
1763×
        return Ok(if snap.base_snapshot.is_conflicted() {
1770×
            2
178
        } else {
1793×
            0
180
        });
1812×
    }
1822×
    println!(
183
        "{} {}{}working copy {}{}{}",
1842×
        ui::dim("On"),
1852×
        ui::bookmark(&repo.config.bookmark),
1862×
        ui::sep(),
1872×
        ui::id(snap.wc.change_id.short(8)),
1882×
        ui::sep(),
1892×
        ui::dim(plural(heads.len(), "head"))
190
    );
1912×
    print_behind(&repo);
1922×
    print_statuses(&snap.statuses);
1932×
    print_untracked_nested(&repo, &snap.untracked_nested);
1942×
    if !snap.base_snapshot.is_conflicted() {
1952×
        return Ok(0);
1960×
    }
1970×
    println!();
1980×
    println!(
199
        "{} {}",
2000×
        ui::section(ui::err("Conflicts")),
2010×
        ui::dim("edit the marked files, or the .oxy-conflict-N candidates, then commit")
202
    );
2030×
    for c in &snap.base_snapshot.tree.conflicts {
2040×
        println!("  {} tree: {c:?}", ui::err(ui::glyph("✱", "!")));
2050×
    }
2060×
    for (p, f) in &snap.base_snapshot.files {
2070×
        if f.is_conflicted() {
2080×
            let state = match snap
2090×
                .statuses
2100×
                .iter()
2110×
                .find(|s| s.path == *p)
2120×
                .map(|s| s.status)
213
            {
214
                Some(ChangeStatus::Resolved) => {
2150×
                    ui::ok(format!("{} resolved in working copy", ui::glyph("✔", "*")))
216
                }
217
                Some(ChangeStatus::ConflictEdited) => {
2180×
                    ui::warn(format!("{} markers remain", ui::glyph("‼", "!")))
219
                }
2200×
                _ => ui::err(format!("{} unresolved", ui::glyph("✱", "!"))),
221
            };
2220×
            println!("  {}  {state}", ui::path(p));
2230×
        }
224
    }
2250×
    Ok(2)
2268×
}
227
22826×
pub fn commit(
22926×
    message: &str,
23026×
    depends_on: &[String],
23126×
    paths: &[String],
23226×
    interactive: bool,
23326×
    hunks: &[usize],
23426×
) -> Result<i32> {
23526×
    let repo = open()?;
23626×
    let mut deps = Vec::new();
23726×
    for d in depends_on {
2380×
        deps.push(repo.resolve_change(d)?);
239
    }
24026×
    let selection = if !hunks.is_empty() {
2411×
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
24225×
    } else if interactive {
2430×
        let (_, hunks) = repo.hunks()?;
2440×
        if hunks.is_empty() {
2450×
            anyhow::bail!("nothing to commit: the working copy matches its base");
2460×
        }
2470×
        let hunks: Vec<_> = hunks
2480×
            .into_iter()
2490×
            .filter(|h| {
2500×
                paths.is_empty()
2510×
                    || paths.iter().any(|p| {
2520×
                        h.path == *p || h.path.starts_with(&format!("{}/", p.trim_end_matches('/')))
2530×
                    })
2540×
            })
2550×
            .collect();
2560×
        let mut chosen = Vec::new();
2570×
        let stdin = std::io::stdin();
2580×
        let mut take_rest = false;
2590×
        for (n, h) in hunks.iter().enumerate() {
2600×
            if take_rest {
2610×
                chosen.push(h.index);
2620×
                continue;
2630×
            }
2640×
            println!(
265
                "{} {} {}",
2660×
                ui::section(format!("hunk {} of {}", n + 1, hunks.len())),
2670×
                ui::path(&h.path),
2680×
                ui::dim(format!("(#{})", h.index))
269
            );
2700×
            for line in h.text.lines() {
2710×
                let styled = if line.starts_with('+') {
2720×
                    ui::ok(line)
2730×
                } else if line.starts_with('-') {
2740×
                    ui::err(line)
275
                } else {
2760×
                    ui::dim(line)
277
                };
2780×
                println!("  {styled}");
279
            }
280
            loop {
2810×
                print!(
282
                    "{} ",
2830×
                    ui::warn("Commit this hunk? [y]es [n]o [a]ll remaining [q]uit:")
284
                );
285
                use std::io::Write as _;
2860×
                std::io::stdout().flush()?;
2870×
                let mut answer = String::new();
2880×
                if stdin.read_line(&mut answer)? == 0 {
2890×
                    anyhow::bail!("aborted");
2900×
                }
2910×
                match answer.trim() {
2920×
                    "y" | "Y" => {
2930×
                        chosen.push(h.index);
2940×
                        break;
295
                    }
2960×
                    "n" | "N" | "" => break,
2970×
                    "a" | "A" => {
2980×
                        chosen.push(h.index);
2990×
                        take_rest = true;
3000×
                        break;
301
                    }
3020×
                    "q" | "Q" => anyhow::bail!("aborted; nothing committed"),
3030×
                    _ => continue,
304
                }
305
            }
306
        }
3070×
        if chosen.is_empty() {
3080×
            anyhow::bail!("no hunks chosen; nothing committed");
3090×
        }
3100×
        oxy_core::repo::Selection::Hunks(chosen)
31125×
    } else if paths.is_empty() {
31223×
        oxy_core::repo::Selection::All
313
    } else {
3142×
        oxy_core::repo::Selection::Paths(paths.to_vec())
315
    };
31626×
    let sp = ui::spinner("Committing…");
31726×
    let (h, partial) = repo.commit_selection_partial(message, &deps, &selection)?;
318
    // The metadata only: a first commit's change holds the whole tree.
31926×
    let meta = repo.store().get_change_meta(&h)?;
32026×
    sp.done(&format!(
32126×
        "{} {} {}  {}",
32226×
        ui::done("Committed"),
32326×
        ui::id(meta.change_id.short(8)),
32426×
        ui::hash(format!("#{}", h.short(12))),
32526×
        ui::subject(subject_of(message))
32626×
    ));
32726×
    print_untracked_nested(&repo, &repo.untracked_nested());
328
    // Only a commit that took part of the working copy leaves anything.
32926×
    if partial {
3302×
        let rest = repo.snapshot_status("oxy commit")?;
3312×
        if !rest.statuses.is_empty() {
3322×
            println!(
3332×
                "  {} {}",
3342×
                ui::note(),
3352×
                ui::dim(format!(
3362×
                    "{} left uncommitted",
3372×
                    plural(rest.statuses.len(), "path")
3382×
                ))
3392×
            );
3402×
        }
34124×
    }
34226×
    where_now(&repo);
34326×
    Ok(0)
34426×
}
345
3460×
pub fn blame(path: &str, json: bool) -> Result<i32> {
3470×
    let repo = open()?;
3480×
    let lines = repo.blame(path)?;
3490×
    if json {
3500×
        let items = lines.iter().map(|l| {
3510×
            format!(
352
                "{{\"line\":{},\"change_id\":{},\"hash\":{},\"index\":{},\"author\":{},\"when_ms\":{}}}",
353
                l.line,
3540×
                oxy_core::repo::json_str(&l.change_id.to_hex()),
3550×
                oxy_core::repo::json_str(&l.hash.to_hex()),
356
                l.index,
3570×
                oxy_core::repo::json_str(&l.author),
358
                l.when_ms
359
            )
3600×
        });
3610×
        println!("{}", oxy_core::repo::json_array(items));
3620×
        return Ok(0);
3630×
    }
3640×
    let width = lines
3650×
        .iter()
3660×
        .map(|l| l.author.chars().count())
3670×
        .max()
3680×
        .unwrap_or(0)
3690×
        .min(20);
3700×
    let digits = lines.len().to_string().len();
3710×
    let _t = oxy_core::timing::phase("blame: print");
372
    // Most lines share their change with many others: each change's id,
373
    // author and age are formatted once, and the lines go out through one
374
    // buffered lock on stdout.
3750×
    let mut prefix: std::collections::HashMap<oxy_core::hash::ChangeHash, String> =
3760×
        std::collections::HashMap::new();
3770×
    let bar = ui::dim(ui::glyph("│", "|"));
3780×
    let mut out = std::io::BufWriter::with_capacity(1 << 16, std::io::stdout().lock());
3790×
    for l in &lines {
3800×
        let p = prefix.entry(l.hash).or_insert_with(|| {
3810×
            let author: String = l.author.chars().take(20).collect();
3820×
            format!(
383
                "{} {} {}",
3840×
                ui::id(l.change_id.short(8)),
3850×
                ui::author(format!("{author:<width$}")),
3860×
                ui::dim(ui::ago(l.when_ms))
387
            )
3880×
        });
3890×
        let text = String::from_utf8_lossy(&l.text);
3900×
        if writeln!(
3910×
            out,
392
            "{p} {:>digits$}{bar} {}",
393
            l.line,
3940×
            text.trim_end_matches('\n')
395
        )
3960×
        .is_err()
397
        {
398
            // A closed pipe (blame | head): stop quietly.
3990×
            return Ok(0);
4000×
        }
401
    }
4020×
    let _ = out.flush();
4030×
    Ok(0)
4040×
}
405
4060×
fn bisect_report(repo: &Repo, step: &oxy_core::repo::BisectStep) -> Result<i32> {
407
    use oxy_core::repo::BisectStep::*;
4080×
    match step {
4090×
        NeedMarks { good, bad } => {
4100×
            println!(
411
                "{} {} {}",
4120×
                ui::note(),
4130×
                ui::dim(format!("{good} good, {bad} bad;")),
4140×
                ui::dim(if *good == 0 {
4150×
                    "mark a known-good change or bookmark: oxy bisect good CHANGE"
416
                } else {
4170×
                    "mark a known-bad change or bookmark: oxy bisect bad CHANGE"
418
                })
419
            );
4200×
            Ok(0)
421
        }
422
        Testing {
4230×
            heads,
4240×
            remaining,
4250×
            steps_left,
426
        } => {
4270×
            println!(
428
                "{} {} {}",
4290×
                ui::done("Testing"),
4300×
                ui::dim(format!(
431
                    "{} in the state under test;",
4320×
                    plural(heads.len(), "head")
433
                )),
4340×
                ui::dim(format!(
435
                    "{remaining} candidates left, about {steps_left} more steps"
436
                ))
437
            );
4380×
            println!(
439
                "  {} {}",
4400×
                ui::note(),
4410×
                ui::dim("run your test, then oxy bisect good | bad | skip")
442
            );
4430×
            Ok(0)
444
        }
4450×
        Found { culprit } => {
4460×
            let c = repo.store().get_change(culprit)?;
4470×
            println!(
448
                "{} {} {}  {}",
4490×
                ui::done("Found"),
4500×
                ui::id(short_id(&c)),
4510×
                ui::hash(format!("#{}", culprit.short(12))),
4520×
                ui::subject(subject_of(&c.message))
453
            );
4540×
            println!("  {} {}", ui::note(), ui::dim("the first change whose inclusion makes the state bad; oxy bisect reset to return"));
4550×
            Ok(0)
456
        }
4570×
        Inconclusive { candidates } => {
4580×
            println!(
459
                "{} {}",
4600×
                ui::caution(),
4610×
                ui::warn(format!(
462
                    "every remaining candidate was skipped ({}); oxy bisect reset to return",
4630×
                    plural(candidates.len(), "change")
464
                ))
465
            );
4660×
            Ok(1)
467
        }
468
    }
4690×
}
470
4710×
pub fn bisect_start() -> Result<i32> {
4720×
    let repo = open()?;
4730×
    repo.bisect_start()?;
4740×
    println!(
475
        "{} bisect; {}",
4760×
        ui::done("Started"),
4770×
        ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE")
478
    );
4790×
    Ok(0)
4800×
}
481
4820×
pub fn bisect_mark(good: Option<bool>, changes: &[String]) -> Result<i32> {
4830×
    let repo = open()?;
4840×
    let mut heads = Vec::new();
4850×
    for c in changes {
4860×
        heads.extend(repo.resolve_heads(c)?);
487
    }
4880×
    let step = repo.bisect_mark(good, &heads)?;
4890×
    bisect_report(&repo, &step)
4900×
}
491
4920×
pub fn bisect_run(command: &[String]) -> Result<i32> {
4930×
    let repo = open()?;
4940×
    let step = repo.bisect_run(command)?;
4950×
    bisect_report(&repo, &step)
4960×
}
497
4981×
pub fn bisect_status(as_json: bool) -> Result<i32> {
4991×
    let repo = open()?;
5001×
    if as_json {
501
        use oxy_core::repo::BisectStep::*;
5021×
        let v = match repo.bisect_status()? {
5031×
            None => "null".to_string(),
5040×
            Some(NeedMarks { good, bad }) => json::obj([
5050×
                ("state", json::s("need-marks")),
5060×
                ("good", json::n(good)),
5070×
                ("bad", json::n(bad)),
5080×
            ]),
509
            Some(Testing {
5100×
                heads,
5110×
                remaining,
5120×
                steps_left,
5130×
            }) => json::obj([
5140×
                ("state", json::s("testing")),
5150×
                ("heads", json::hashes(&heads)),
5160×
                ("remaining", json::n(remaining)),
5170×
                ("steps_left", json::n(steps_left)),
5180×
            ]),
5190×
            Some(Found { culprit }) => json::obj([
5200×
                ("state", json::s("found")),
5210×
                ("culprit", json::s(&culprit.to_hex())),
5220×
            ]),
5230×
            Some(Inconclusive { candidates }) => json::obj([
5240×
                ("state", json::s("inconclusive")),
5250×
                ("candidates", json::hashes(&candidates)),
5260×
            ]),
527
        };
5281×
        println!("{v}");
5291×
        return Ok(0);
5300×
    }
5310×
    match repo.bisect_status()? {
532
        None => {
5330×
            println!("{}", ui::dim("No bisect in progress."));
5340×
            Ok(0)
535
        }
5360×
        Some(step) => bisect_report(&repo, &step),
537
    }
5381×
}
539
5400×
pub fn bisect_reset() -> Result<i32> {
5410×
    let repo = open()?;
5420×
    repo.bisect_reset()?;
5430×
    println!("{} bisect; working copy restored", ui::done("Reset"));
5440×
    Ok(0)
5450×
}
546
547
/// The log: one entry per change, newest first, joined by a rail. The
548
/// default view is the subject and a metadata line; `verbose` adds the full
549
/// message, dependencies, and the authenticating key.
55014×
fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
55114×
    Ok(match repo.authenticate_change(h)? {
5529×
        SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]),
553
        SignatureStatus::Valid {
5545×
            key,
5555×
            name,
5565×
            email,
5575×
            sealed,
5585×
            revoked,
5595×
        } => json::obj([
5605×
            ("status", json::s(if sealed { "sealed" } else { "signed" })),
5615×
            ("key", json::s(&key.to_hex())),
5625×
            ("name", json::s(&name)),
5635×
            ("email", json::s(&email)),
5645×
            ("revoked", json::b(revoked)),
565
        ]),
5660×
        SignatureStatus::Invalid(why) => {
5670×
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
568
        }
569
    })
57014×
}
571
57218×
fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result<String> {
57318×
    let c = &e.change;
57418×
    Ok(json::obj([
57518×
        ("hash", json::s(&e.hash.to_hex())),
57618×
        ("change_id", json::s(&c.change_id.to_hex())),
57718×
        ("author", json::s(&author_name(repo, c))),
57818×
        ("author_key", json::s(&c.author.to_hex())),
579
        (
58018×
            "via",
58118×
            match via(
58218×
                repo,
58318×
                &repo.authenticate_change_known(&e.hash, Some(c))?,
58418×
                &c.author,
585
            ) {
5860×
                Some(v) => json::obj([
5870×
                    ("name", json::s(&v.name)),
5880×
                    ("email", json::s(&v.email)),
5890×
                    ("key", json::s(&v.key.to_hex())),
5900×
                    ("scope", json::opt(v.scope.as_deref(), json::s)),
5910×
                    ("expires_ms", json::opt(v.expires, json::n)),
5920×
                    ("revoked", json::b(v.revoked)),
5930×
                ]),
59418×
                None => "null".to_string(),
595
            },
596
        ),
59718×
        ("when_ms", json::n(c.hlc.wall_ms)),
59818×
        ("message", json::s(&c.message)),
59918×
        ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())),
60018×
        ("deps", json::hashes(&c.deps)),
60118×
        ("head", json::b(e.is_head)),
60218×
        ("working_copy", json::b(e.is_working_copy)),
603
        (
60418×
            "signature",
60518×
            if e.is_working_copy {
6064×
                "null".into()
607
            } else {
60814×
                signature_json(repo, &e.hash)?
609
            },
610
        ),
611
    ]))
61218×
}
613
614
/// `START,END:PATH` for `oxy log -L`.
6152×
fn parse_line_range(spec: &str) -> Result<(usize, usize, &str)> {
6162×
    let bad = || anyhow::anyhow!("-L {spec}: expected START,END:PATH, as 10,24:src/lib.rs");
6172×
    let (range, path) = spec.split_once(':').ok_or_else(bad)?;
6182×
    let (a, b) = range.split_once(',').ok_or_else(bad)?;
619
    Ok((
6201×
        a.trim().parse().map_err(|_| bad())?,
6211×
        b.trim().parse().map_err(|_| bad())?,
6221×
        path,
623
    ))
6242×
}
625
6268×
pub fn log(
6278×
    revset: Option<&str>,
6288×
    limit: Option<usize>,
6298×
    verbose: bool,
6308×
    path: Option<&str>,
6318×
    lines: Option<&str>,
6328×
    as_json: bool,
6338×
) -> Result<i32> {
6348×
    let repo = open()?;
635
    // Whether the working copy is clean and conflicted: from the manifest
636
    // when it proves the working copy clean, else from a snapshot.
637
    // The working copy as last recorded, without looking at the files (as
638
    // Git's log does not): whether its change holds edits, and whether its
639
    // base was conflicted. `oxy status` is what checks the disk.
6408×
    let conflicted = !repo.is_at_op() && repo.recorded_conflicted()?;
6418×
    let listing = oxy_core::timing::phase("log: entries");
6428×
    let entries = match (path, lines) {
6438×
        _ if revset.is_some() => repo.log_revset(revset.unwrap_or_default())?,
6442×
        (_, Some(spec)) => {
6452×
            let (first, last, p) = parse_line_range(spec)?;
6461×
            let (_, wc) = repo.working_copy()?;
6471×
            let base = repo.load_state_history(&wc.deps)?.maximal(&wc.deps);
6481×
            repo.line_history(&base, p, first, last)?
649
        }
6501×
        (Some(p), None) => repo.log_for_path(p)?,
6515×
        (None, None) => repo.log()?,
652
    };
6537×
    drop(listing);
6547×
    let _print = oxy_core::timing::phase("log: print");
6557×
    if as_json {
6566×
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
6576×
        let mut items = Vec::new();
65817×
        for e in entries.iter().take(shown) {
65917×
            items.push(log_entry_json(&repo, e)?);
660
        }
6616×
        println!(
662
            "{}",
6636×
            json::obj([
6646×
                ("bookmark", json::s(&repo.config.bookmark)),
6656×
                ("total", json::n(entries.len())),
6666×
                ("changes", json::arr(items))
6676×
            ])
668
        );
6696×
        return Ok(0);
6701×
    }
6711×
    let total = entries.len();
6721×
    let shown = limit.unwrap_or(total).min(total);
673
    // Lay out a little past what is shown, so edges into the cut are drawn.
6741×
    let window: Vec<(ChangeHash, Vec<ChangeHash>)> = entries
6751×
        .iter()
6761×
        .take((shown + MAX_EDGE).min(total))
6774×
        .map(|e| (e.hash, e.change.deps.clone()))
6781×
        .collect();
6791×
    let rows = oxy_core::lanes::graph(&window, MAX_EDGE);
680
    // Highlight the shortest prefix that names each change: against the
681
    // whole log, which is what `resolve_change` searches.
682
    let everything;
6831×
    let all = if path.is_some() || lines.is_some() || revset.is_some() {
6840×
        everything = repo.log()?;
6850×
        &everything
686
    } else {
6871×
        &entries
688
    };
6894×
    let id_prefix = unique_prefixes(all.iter().map(|e| e.change.change_id.to_hex()));
6901×
    let labels = reference_labels(&repo)?;
6914×
    for (e, row) in entries.iter().take(shown).zip(&rows) {
6924×
        let c = &e.change;
6934×
        let bullet = ui::log_bullet(
6944×
            e.is_working_copy,
6954×
            e.is_head,
6964×
            e.is_working_copy && conflicted,
697
        );
6984×
        let id = c.change_id.to_hex();
6994×
        let n = id_prefix.get(&id).copied().unwrap_or(8).min(8);
7004×
        let mut head = vec![format!("{}{}", ui::id(&id[..n]), ui::dim(&id[n..8]))];
7014×
        head.push(ui::author(author_name(&repo, c)));
7024×
        head.push(ui::dim(ui::ago(c.hlc.wall_ms)));
7034×
        if let Some(names) = labels.get(&e.hash) {
7042×
            head.push(names.join(" "));
7052×
        }
7064×
        if c.kind == ChangeKind::Resolution {
7070×
            head.push(ui::warn("resolution"));
7084×
        }
7094×
        if !e.is_working_copy {
7103×
            head.push(ui::hash(format!("#{}", e.hash.short(8))));
7113×
            let status = repo.authenticate_change_known(&e.hash, Some(c))?;
7123×
            if let Some(agent) = via(&repo, &status, &c.author) {
7130×
                head.push(ui::dim(format!("via {}", agent.name)));
7143×
            }
7153×
            head.push(signature_mark_of(&status));
7161×
        }
7174×
        println!("{}{}", node_line(row, &bullet), head.join(" "));
7184×
        let subject = if e.is_working_copy && c.message.is_empty() {
7191×
            let edited = repo
7201×
                .store()
7211×
                .get_change(&e.hash)
7221×
                .is_ok_and(|w| !w.tree_ops.is_empty() || !w.edits.is_empty());
7231×
            ui::dim(if edited {
7240×
                "(working copy, uncommitted changes)"
725
            } else {
7261×
                "(working copy)"
727
            })
7283×
        } else if c.message.trim().is_empty() {
7290×
            ui::dim("(no description)")
730
        } else {
7313×
            subject_of(&c.message).to_string()
732
        };
7334×
        println!("{}{subject}", below_line(row));
7344×
        if verbose {
7350×
            let rail = continuation(row);
7360×
            if !e.is_working_copy {
7370×
                println!(
738
                    "{rail}{}",
7390×
                    ui::dim(format!(
740
                        "{} {}",
7410×
                        when(c.hlc.wall_ms),
7420×
                        signature_line(&repo, &e.hash)?
743
                    ))
744
                );
7450×
            }
7460×
            if !c.deps.is_empty() {
7470×
                println!(
7480×
                    "{rail}{} {}",
7490×
                    ui::dim(ui::glyph("↳", "->")),
7500×
                    ui::dim(deps_of(&c.deps))
7510×
                );
7520×
            }
7530×
            let body: Vec<&str> = c
7540×
                .message
7550×
                .lines()
7560×
                .skip(1)
7570×
                .skip_while(|l| l.trim().is_empty())
7580×
                .collect();
7590×
            for line in body {
7600×
                println!("{rail}  {line}");
7610×
            }
7624×
        }
763
    }
7641×
    if shown < total {
7650×
        if let Some(last) = rows.get(shown.saturating_sub(1)) {
7660×
            let cut: String = last
7670×
                .below
7680×
                .iter()
7690×
                .map(|c| match c {
7700×
                    Cell::Blank | Cell::Elided | Cell::JoinRight => "  ",
7710×
                    _ => "~ ",
7720×
                })
7730×
                .collect();
7740×
            if cut.trim().is_empty() {
7750×
                println!("{}", ui::dim("~"));
7760×
            } else {
7770×
                println!("{}", ui::dim(cut.trim_end()));
7780×
            }
7790×
        }
7800×
        println!(
781
            "{}",
7820×
            ui::dim(format!(
783
                "{} {} more; pass -n to see them",
7840×
                ui::glyph("…", "..."),
7850×
                total - shown
786
            ))
787
        );
7881×
    }
7891×
    Ok(0)
7908×
}
791
792
/// Rows a drawn edge may span in `oxy log`; a longer one is elided (`~`).
793
const MAX_EDGE: usize = 12;
794
795
use oxy_core::hash::ChangeHash;
796
use oxy_core::lanes::{Cell, GraphRow};
797
798
/// A graph cell, two columns wide.
7996×
fn cell(c: Cell) -> &'static str {
8006×
    match c {
8011×
        Cell::Blank => "  ",
8023×
        Cell::Line => ui::glyph("│ ", "| "),
8030×
        Cell::Elided => "~ ",
8041×
        Cell::JoinLeft => ui::glyph("├─", "|-"),
8050×
        Cell::JoinPass => ui::glyph("──", "--"),
8060×
        Cell::JoinCross => ui::glyph("┼─", "+-"),
8071×
        Cell::JoinRight => ui::glyph("╯ ", "' "),
808
    }
8096×
}
810
811
/// The graph part of a change's own line, its bullet in its column.
8124×
fn node_line(row: &GraphRow, bullet: &str) -> String {
8134×
    let width = row
8144×
        .passing
8154×
        .iter()
8164×
        .copied()
8174×
        .max()
8184×
        .unwrap_or(0)
8194×
        .max(row.column)
8204×
        + 1;
8214×
    let mut out = String::new();
8225×
    for c in 0..width {
8235×
        if c == row.column {
8244×
            out.push_str(bullet);
8254×
            out.push(' ');
8264×
        } else if row.passing.contains(&c) {
8271×
            out.push_str(&ui::dim(cell(Cell::Line)));
8281×
        } else {
8290×
            out.push_str("  ");
8300×
        }
831
    }
8324×
    out.push(' ');
8334×
    out
8344×
}
835
836
/// The graph part of the line under a change: lanes carrying on, a join,
837
/// or `~` for an elided edge.
8384×
fn below_line(row: &GraphRow) -> String {
8395×
    let g: String = row.below.iter().map(|c| cell(*c)).collect();
8404×
    format!("{} ", ui::dim(g))
8414×
}
842
843
/// The graph part of any further line of a change (`-v`).
8440×
fn continuation(row: &GraphRow) -> String {
8450×
    let g: String = row
8460×
        .below
8470×
        .iter()
8480×
        .map(|c| match c {
8490×
            Cell::Line | Cell::JoinLeft | Cell::JoinCross => cell(Cell::Line),
8500×
            _ => "  ",
8510×
        })
8520×
        .collect();
8530×
    format!("{} ", ui::dim(g))
8540×
}
855
856
/// For each hex ID, the length of its shortest prefix no other ID shares.
8571×
fn unique_prefixes(ids: impl Iterator<Item = String>) -> std::collections::HashMap<String, usize> {
8581×
    let mut v: Vec<String> = ids.collect();
8591×
    v.sort();
8601×
    v.dedup();
8618×
    let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
8621×
    let mut out = std::collections::HashMap::with_capacity(v.len());
8634×
    for i in 0..v.len() {
8644×
        let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 };
8654×
        let after = if i + 1 < v.len() {
8663×
            common(&v[i], &v[i + 1])
867
        } else {
8681×
            0
869
        };
8704×
        out.insert(v[i].clone(), before.max(after) + 1);
871
    }
8721×
    out
8731×
}
874
875
/// Bookmark, remote bookmark and tag names to show beside the changes they
876
/// point at. A name is shown on each head of its state; one with more than
877
/// three heads names too much of the log to help, so it is left out (oxy
878
/// bookmark list shows it). A remote bookmark at the same state as the
879
/// local one of that name is not repeated.
8801×
fn reference_labels(repo: &Repo) -> Result<std::collections::HashMap<ChangeHash, Vec<String>>> {
881
    const MAX_HEADS: usize = 3;
8821×
    let view = repo.view()?;
8831×
    let mut out: std::collections::HashMap<ChangeHash, Vec<String>> = Default::default();
8841×
    let mut add = |heads: Vec<ChangeHash>, label: String| {
8851×
        if heads.len() <= MAX_HEADS {
8862×
            for h in heads {
8872×
                out.entry(h).or_default().push(label.clone());
8882×
            }
8890×
        }
8901×
    };
8911×
    for (name, st) in &view.bookmarks {
8921×
        add(repo.store().get_state(st)?.heads, ui::bookmark(name));
893
    }
8941×
    for (remote, bookmarks) in &view.remotes {
8950×
        for (name, st) in bookmarks {
8960×
            if view.bookmarks.get(name) == Some(st) {
8970×
                continue;
8980×
            }
8990×
            add(
9000×
                repo.store().get_state(st)?.heads,
9010×
                ui::dim(format!("{remote}/{name}")),
902
            );
903
        }
904
    }
9051×
    for t in repo.tags()? {
9060×
        add(t.heads.clone(), ui::warn(&t.name));
9070×
    }
9081×
    Ok(out)
9091×
}
910
9111×
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
9121×
    let repo = open()?;
9131×
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
9141×
    if as_json {
9151×
        let files = repo.diff_files(hash.as_ref())?;
9163×
        let items = files.iter().map(|f| {
9173×
            json::obj([
9183×
                ("path", json::s(&f.path)),
9193×
                ("kind", json::s(&f.kind)),
9203×
                ("from", json::opt(f.from.as_deref(), json::s)),
921
                (
9223×
                    "hunks",
9233×
                    json::arr(f.hunks.iter().map(|h| {
9243×
                        json::obj([
9253×
                            ("base_line", json::n(h.base_line)),
926
                            (
9273×
                                "added",
9283×
                                json::arr(
9293×
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
930
                                ),
931
                            ),
932
                            (
9333×
                                "removed",
9343×
                                json::arr(h.removed.iter().map(|(n, l)| {
9350×
                                    json::obj([
9360×
                                        ("line", json::n(*n)),
9370×
                                        ("text", json::s(&String::from_utf8_lossy(l))),
9380×
                                    ])
9390×
                                })),
940
                            ),
941
                        ])
9423×
                    })),
943
                ),
944
            ])
9453×
        });
9461×
        println!(
947
            "{}",
9481×
            json::obj([
9491×
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
9501×
                ("files", json::arr(items))
951
            ])
952
        );
9531×
        return Ok(0);
9540×
    }
9550×
    match hash {
9560×
        Some(h) => {
9570×
            let c = repo.store().get_change(&h)?;
9580×
            let (base, snapshot) = repo.change_base(&c)?;
9590×
            print!("{}", render_change(&c, &base, &snapshot));
960
        }
961
        None => {
9620×
            let (wc, base, snapshot) = repo.working_copy_with_base()?;
9630×
            let text = {
9640×
                let _t = oxy_core::timing::phase("diff: render the change");
9650×
                render_change(&wc, &base, &snapshot)
966
            };
9670×
            print!("{text}");
968
            // The process ends here: freeing the base's tree and graphs
969
            // one by one would only cost time (about 27 ms on Linux).
9700×
            std::mem::forget((wc, base, snapshot));
971
        }
972
    }
9730×
    Ok(0)
9741×
}
975
9762×
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
9772×
    let repo = open()?;
9782×
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
9792×
    let bytes = match repo.file_at(path, heads.as_deref()) {
9802×
        Ok(b) => b,
981
        // -r CHANGE reads that change's dependency closure, not the
982
        // bookmark it is on: say so when the bookmark has the file
983
        // (oxygen#76).
9840×
        Err(e) => match change {
9850×
            Some(c)
9860×
                if !repo.view()?.bookmarks.contains_key(c)
9870×
                    && repo.tag_heads(c)?.is_none()
9880×
                    && repo.file_at(path, None).is_ok() =>
989
            {
9900×
                anyhow::bail!(
991
                    "{path} is not in {c}'s dependency closure (the change and what it \
992
                     depends on); it is on the bookmark: try -r {}, or --at-op OP for the \
993
                     state at an operation",
994
                    repo.config.bookmark
995
                )
996
            }
9970×
            _ => return Err(e.into()),
998
        },
999
    };
1000
    use std::io::Write as _;
10012×
    std::io::stdout().write_all(&bytes)?;
10022×
    Ok(0)
10032×
}
1004
10051×
pub fn root(as_json: bool) -> Result<i32> {
10061×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
10070×
        if as_json {
10080×
            println!("null");
10090×
        }
10100×
        return Ok(1);
1011
    };
10121×
    if as_json {
10131×
        println!(
10141×
            "{}",
10151×
            json::obj([
10161×
                ("root", json::s(&repo.root().to_string_lossy())),
10171×
                ("workspace", json::s(&repo.workspace().to_hex())),
10181×
                ("bookmark", json::s(&repo.config.bookmark))
10191×
            ])
10201×
        );
10211×
    } else {
10220×
        println!("{}", repo.root().display());
10230×
    }
10241×
    Ok(0)
10251×
}
1026
10271×
pub fn version(as_json: bool) -> Result<i32> {
10281×
    if as_json {
10291×
        println!(
10301×
            "{}",
10311×
            json::obj([
10321×
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
10331×
                // What was built: a release's or install's `oxy describe`,
10341×
                // a Flow build's heads, or "local build".
10351×
                ("build", json::s(env!("OXY_BUILD_ID"))),
10361×
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
10371×
                ("format", json::n(2))
10381×
            ])
10391×
        );
10401×
    } else {
10410×
        println!(
10420×
            "oxy {} (repository format 2, protocol {})",
10430×
            env!("OXY_VERSION_LONG"),
10440×
            oxy_core::protocol::PROTOCOL_VERSION
10450×
        );
10460×
    }
10471×
    Ok(0)
10481×
}
1049
10502×
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
10512×
    let repo = open()?;
10522×
    if paths.is_empty() && hunks.is_empty() {
10530×
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
10542×
    }
10552×
    let mut n = 0;
10562×
    if !hunks.is_empty() {
10571×
        n += repo.discard_hunks(hunks)?;
10581×
    }
10592×
    if !paths.is_empty() {
10601×
        n += repo.discard(paths)?;
10611×
    }
10622×
    println!(
1063
        "{} {} restored to the working copy's base",
10642×
        ui::done("Discarded"),
10652×
        plural(n, "path")
1066
    );
10672×
    Ok(0)
10682×
}
1069
10702×
pub fn hunks(as_json: bool) -> Result<i32> {
10712×
    let repo = open()?;
10722×
    let (_, hunks) = repo.hunks()?;
10732×
    if as_json {
10742×
        println!(
1075
            "{}",
10765×
            json::arr(hunks.iter().map(|h| json::obj([
10775×
                ("index", json::n(h.index)),
10785×
                ("path", json::s(&h.path)),
10795×
                ("text", json::s(&h.text))
10805×
            ])))
1081
        );
10822×
        return Ok(0);
10830×
    }
10840×
    if hunks.is_empty() {
10850×
        println!(
10860×
            "{}",
10870×
            ui::dim("No hunks: the working copy matches its base.")
10880×
        );
10890×
    }
10900×
    for h in &hunks {
10910×
        println!(
1092
            "{} {}",
10930×
            ui::section(format!("hunk {}", h.index)),
10940×
            ui::path(&h.path)
1095
        );
10960×
        for line in h.text.lines() {
10970×
            let styled = if line.starts_with('+') {
10980×
                ui::ok(line)
10990×
            } else if line.starts_with('-') {
11000×
                ui::err(line)
1101
            } else {
11020×
                ui::dim(line)
1103
            };
11040×
            println!("  {styled}");
1105
        }
1106
    }
11070×
    Ok(0)
11082×
}
1109
11102×
pub fn show(change: Option<&str>, revset: Option<&str>, as_json: bool) -> Result<i32> {
11112×
    let repo = open()?;
11122×
    repo.snapshot_status("oxy show")?;
11132×
    let Some(r) = revset else {
11142×
        let h = repo.resolve_change(change.unwrap_or("@"))?;
11152×
        return show_one(&repo, h, as_json, false);
1116
    };
1117
    // Several changes: a JSON array, or the changes one after another.
11180×
    let hashes = repo.revset(r)?.hashes;
11190×
    if as_json {
11200×
        print!("[");
11210×
        for (i, h) in hashes.iter().enumerate() {
11220×
            if i > 0 {
11230×
                print!(",");
11240×
            }
11250×
            show_one(&repo, *h, true, true)?;
1126
        }
11270×
        println!("]");
11280×
        return Ok(0);
11290×
    }
11300×
    if hashes.is_empty() {
11310×
        println!("{}", ui::dim(format!("No change matches {r:?}.")));
11320×
        return Ok(0);
11330×
    }
11340×
    for (i, h) in hashes.iter().enumerate() {
11350×
        if i > 0 {
11360×
            println!();
11370×
        }
11380×
        show_one(&repo, *h, false, false)?;
1139
    }
11400×
    Ok(0)
11412×
}
1142
1143
/// One change, as `oxy show` prints it; `inline` JSON goes without its
1144
/// newline, for an array.
11452×
fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool) -> Result<i32> {
11462×
    let c = repo.store().get_change(&h)?;
11472×
    if as_json {
11481×
        let files = repo.diff_files(Some(&h))?;
11491×
        let heads = repo.bookmark_heads()?;
11501×
        let entry = oxy_core::repo::LogEntry {
11511×
            hash: h,
11521×
            change: oxy_core::state::ChangeMeta::of(&c),
11531×
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
11541×
            is_head: heads.contains(&h),
11551×
        };
11561×
        let mut body = log_entry_json(repo, &entry)?;
11571×
        body.pop();
11581×
        body.push_str(&format!(
1159
            ",{}:{}}}",
11601×
            json::s("files"),
11611×
            json::arr(files.iter().map(|f| json::obj([
11621×
                ("path", json::s(&f.path)),
11631×
                ("kind", json::s(&f.kind)),
11641×
                ("from", json::opt(f.from.as_deref(), json::s))
11651×
            ])))
1166
        ));
11671×
        if inline {
11680×
            print!("{body}");
11691×
        } else {
11701×
            println!("{body}");
11711×
        }
11721×
        return Ok(0);
11731×
    }
11741×
    println!(
1175
        "{} {} {}",
11761×
        ui::section("change"),
11771×
        ui::id(short_id(&c)),
11781×
        ui::hash(format!("#{h}"))
1179
    );
11801×
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1181
    // Fetched but not pulled (oxygen#56): say where it is.
11821×
    if let Some(at) = repo.remote_only_location(&h)? {
11830×
        println!(
11840×
            "{}",
11850×
            ui::kv(
11860×
                "only in",
11870×
                ui::warn(format!(
11880×
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
11890×
                ))
11900×
            )
11910×
        );
11921×
    }
11931×
    let meta = oxy_core::state::ChangeMeta::of(&c);
11941×
    let status = repo.authenticate_change_known(&h, Some(&meta))?;
11951×
    println!("{}", ui::kv("author", ui::author(author_name(repo, &meta))));
11961×
    if let Some(agent) = via(repo, &status, &meta.author) {
11970×
        println!("{}", ui::kv("via", agent.line()));
11981×
    }
11991×
    println!(
1200
        "{}",
12011×
        ui::kv(
12021×
            "date",
12031×
            format!(
1204
                "{} {}",
12051×
                when(c.hlc.wall_ms),
12061×
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1207
            )
1208
        )
1209
    );
12101×
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
12111×
    println!("{}", ui::kv("sig", signature_line(repo, &h)?));
12121×
    println!();
12134×
    for line in (if c.message.is_empty() {
12140×
        "(no description)"
1215
    } else {
12161×
        &c.message
1217
    })
12181×
    .lines()
12194×
    {
12204×
        println!("    {line}");
12214×
    }
12221×
    println!();
12231×
    print!("{}", repo.describe_change(&h)?);
12241×
    Ok(0)
12252×
}
1226
12270×
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
12280×
    let repo = open()?;
1229
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1230
    // BRANCH` is: checking its files out under another bookmark's name
1231
    // made the next commit move the wrong bookmark (oxygen#60).
12320×
    if let [name] = changes {
12330×
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
12340×
            drop(repo);
12350×
            return bookmark_switch(name, discard, carry);
12360×
        }
12370×
    }
12380×
    let heads = if changes.is_empty() {
12390×
        repo.bookmark_heads()?
1240
    } else {
12410×
        let mut heads = Vec::new();
12420×
        for c in changes {
12430×
            heads.extend(repo.resolve_heads(c)?);
1244
        }
12450×
        heads
1246
    };
12470×
    let spec = if changes.is_empty() {
12480×
        repo.config.bookmark.clone()
1249
    } else {
12500×
        changes.join(" ")
1251
    };
12520×
    let sp = ui::spinner(&format!("Checking out {spec}…"));
12530×
    let command = format!("oxy checkout {spec}");
12540×
    let (r, carried) = if carry {
12550×
        repo.checkout_carry(&heads, &spec, &command)?
1256
    } else {
12570×
        (repo.checkout(&heads, discard, &command)?, vec![])
1258
    };
12590×
    sp.done(&format!(
1260
        "{} on {}: {} written, {} removed{}",
12610×
        ui::done("Working copy"),
12620×
        ui::bookmark(&spec),
12630×
        plural(r.written, "file"),
1264
        r.removed,
12650×
        if carried.is_empty() {
12660×
            String::new()
1267
        } else {
12680×
            format!("; carried {}", plural(carried.len(), "changed path"))
1269
        }
1270
    ));
12710×
    for n in &r.notes {
12720×
        println!("  {} {n}", ui::note());
12730×
    }
12740×
    if r.conflicted {
12750×
        println!(
12760×
            "  {} {}",
12770×
            ui::caution(),
12780×
            ui::warn("this state has conflicts; see oxy status")
12790×
        );
12800×
    }
12810×
    where_now(&repo);
12820×
    Ok(0)
12830×
}
1284
12851×
pub fn resolve(as_json: bool) -> Result<i32> {
12861×
    let repo = open()?;
12871×
    let snap = repo.snapshot("oxy resolve")?;
12881×
    if as_json {
12891×
        println!("{}", repo.status_json(&snap)?);
12901×
        return Ok(if snap.base_snapshot.is_conflicted() {
12910×
            2
1292
        } else {
12931×
            0
1294
        });
12950×
    }
12960×
    if !snap.base_snapshot.is_conflicted() {
12970×
        println!("The working copy's base has no conflicts.");
12980×
        return Ok(0);
12990×
    }
13000×
    let mut remaining = 0;
13010×
    for (p, f) in &snap.base_snapshot.files {
13020×
        if !f.is_conflicted() {
13030×
            continue;
13040×
        }
13050×
        match snap
13060×
            .statuses
13070×
            .iter()
13080×
            .find(|s| s.path == *p)
13090×
            .map(|s| s.status)
1310
        {
13110×
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
13120×
            Some(ChangeStatus::ConflictEdited) => {
13130×
                remaining += 1;
13140×
                println!("markers    {p}");
13150×
            }
13160×
            _ => {
13170×
                remaining += 1;
13180×
                println!("unresolved {p}");
13190×
            }
1320
        }
1321
    }
13220×
    for c in &snap.base_snapshot.tree.conflicts {
13230×
        remaining += 1;
13240×
        println!("tree       {c:?}");
13250×
    }
13260×
    if remaining == 0 {
13270×
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
13280×
        Ok(0)
1329
    } else {
13300×
        Ok(2)
1331
    }
13321×
}
1333
13340×
pub fn undo() -> Result<i32> {
13350×
    let repo = open()?;
13360×
    let op = repo.undo()?;
13370×
    println!("{} now at: {}", ui::done("Undone;"), ui::dim(&op.command));
13380×
    where_now(&repo);
13390×
    Ok(0)
13400×
}
1341
13421×
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
13431×
    let repo = open()?;
13441×
    let ops = repo.op_log()?;
1345
    // What each operation changed, against the one before it.
134611×
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
134711×
        match ops.get(i + 1) {
134810×
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
13491×
            None => Ok(vec![]),
1350
        }
135111×
    };
13521×
    if as_json {
13531×
        let mut items = Vec::new();
135411×
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
135511×
            let summary: Vec<String> = changes_of(i)?
135611×
                .iter()
135711×
                .map(|c| change_words(&repo, c))
135811×
                .collect();
135911×
            items.push(json::obj([
136011×
                ("id", json::s(&r.to_hex())),
136111×
                ("when_ms", json::n(op.hlc.wall_ms)),
136211×
                ("command", json::s(&op.command)),
136311×
                ("snapshot", json::b(op.is_snapshot())),
136411×
                ("current", json::b(i == 0)),
136511×
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1366
            ]));
1367
        }
13681×
        println!("{}", json::arr(items));
13691×
        return Ok(0);
13700×
    }
13710×
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
13720×
    let id = |r: &oxy_core::hash::ObjectRef| {
13730×
        let hex = r.to_hex();
13740×
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
13750×
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
13760×
    };
13770×
    let rail = ui::dim(ui::glyph("│", "|"));
13780×
    let (mut i, mut shown) = (0, 0);
13790×
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
13800×
        let (r, op) = &ops[i];
13810×
        let bullet = if i == 0 {
13820×
            ui::ok(ui::glyph("@", "@"))
1383
        } else {
13840×
            ui::dim(ui::glyph("○", "o"))
1385
        };
1386
        // A run of snapshots folds into one entry.
13870×
        let mut run = 1;
13880×
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
13890×
            run += 1;
13900×
        }
13910×
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
13920×
        if op.is_snapshot() {
13930×
            let span = if run > 1 {
13940×
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1395
            } else {
13960×
                String::new()
1397
            };
13980×
            println!(
1399
                "{bullet}  {}{} {when}",
14000×
                id(r),
14010×
                if span.is_empty() {
14020×
                    String::new()
1403
                } else {
14040×
                    format!(" {span}")
1405
                }
1406
            );
14070×
            println!(
1408
                "{rail}  {}",
14090×
                ui::dim(if run == 1 {
14100×
                    "working-copy snapshot".to_string()
1411
                } else {
14120×
                    format!("{run} working-copy snapshots")
1413
                })
1414
            );
1415
        } else {
14160×
            println!("{bullet}  {} {when}", id(r));
14170×
            let words: Vec<String> = changes_of(i)?
14180×
                .iter()
14190×
                .map(|c| change_words(&repo, c))
14200×
                .collect();
14210×
            let summary = if words.is_empty() {
14220×
                if i + 1 == ops.len() {
14230×
                    "created the repository".to_string()
1424
                } else {
14250×
                    "no bookmark or working-copy change".to_string()
1426
                }
1427
            } else {
14280×
                words.join("; ")
1429
            };
14300×
            println!(
1431
                "{rail}  {}",
14320×
                if i == 0 {
14330×
                    ui::subject(&summary)
1434
                } else {
14350×
                    summary
1436
                }
1437
            );
14380×
            let cmd = op.command.lines().next().unwrap_or("");
14390×
            let cmd: String = cmd.chars().take(100).collect();
14400×
            println!("{rail}  {}", ui::dim(cmd));
1441
        }
14420×
        i += run;
14430×
        shown += 1;
1444
    }
14450×
    if i < ops.len() {
14460×
        println!(
14470×
            "{}",
14480×
            ui::dim(format!(
14490×
                "{} {} older; pass -n to see more",
14500×
                ui::glyph("…", "..."),
14510×
                plural(ops.len() - i, "operation")
14520×
            ))
14530×
        );
14540×
    }
14550×
    Ok(0)
14561×
}
1457
1458
/// One change an operation made, in words.
145911×
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1460
    use oxy_core::repo::ViewChange::*;
14612×
    match c {
14620×
        BookmarkCreated { name, heads } => {
14630×
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1464
        }
14650×
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
14662×
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
14671×
        BookmarkMoved { name, from, to } => format!(
1468
            "{name}: {from} {} {}",
14691×
            ui::glyph("→", "->"),
14701×
            plural(*to, "head")
1471
        ),
14721×
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
14730×
        TagCreated { name } => format!("tagged {name}"),
14740×
        TagDeleted { name } => format!("removed tag {name}"),
14750×
        Policy => "trust policy changed".to_string(),
14768×
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
14778×
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
14780×
            Err(_) => "working copy moved".to_string(),
1479
        },
1480
    }
148111×
}
1482
14830×
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
14840×
    let repo = open()?;
14850×
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
14860×
    let r = repo.op_restore(op, discard)?;
14870×
    sp.done(&format!(
14880×
        "{} to operation {} {}",
14890×
        ui::done("Restored"),
14900×
        ui::hash(r.op.short(12)),
14910×
        ui::dim(r.command.lines().next().unwrap_or(""))
14920×
    ));
14930×
    println!(
1494
        "  {} {}",
14950×
        ui::note(),
14960×
        ui::dim(format!(
1497
            "{} written, {} removed; oxy undo goes back again",
14980×
            plural(r.checkout.written, "file"),
1499
            r.checkout.removed
1500
        ))
1501
    );
15020×
    where_now(&repo);
15030×
    Ok(0)
15040×
}
1505
15060×
pub fn op_revert(op: &str) -> Result<i32> {
15070×
    let repo = open()?;
15080×
    let r = repo.op_revert(op)?;
15090×
    let view = repo.view()?;
15100×
    let names: Vec<String> = r
15110×
        .reverted
15120×
        .iter()
15130×
        .map(|n| {
15140×
            if view.bookmarks.contains_key(n) {
15150×
                ui::bookmark(n)
1516
            } else {
15170×
                format!("{} (removed)", ui::bookmark(n))
1518
            }
15190×
        })
15200×
        .collect();
15210×
    println!(
1522
        "{} operation {} {}",
15230×
        ui::done("Reverted"),
15240×
        ui::hash(r.op.short(12)),
15250×
        ui::dim(r.command.lines().next().unwrap_or(""))
1526
    );
15270×
    println!(
1528
        "  {} {}",
15290×
        ui::note(),
15300×
        ui::dim(format!("as before it: {}", names.join(", ")))
1531
    );
15320×
    if !r.kept.is_empty() {
15330×
        println!(
15340×
            "  {} {}",
15350×
            ui::caution(),
15360×
            ui::warn(format!(
15370×
                "left as they are, having moved again since: {}",
15380×
                r.kept.join(", ")
15390×
            ))
15400×
        );
15410×
    }
15420×
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
15430×
        println!(
15440×
            "  {} {}",
15450×
            ui::note(),
15460×
            ui::dim("the working copy has work of its own: oxy checkout to move it")
15470×
        );
15480×
    }
15490×
    where_now(&repo);
15500×
    Ok(0)
15510×
}
1552
1553
/// Where the working copy and bookmark are now, after a command moved
1554
/// them (as jj says "Working copy now at").
155531×
pub fn where_now(repo: &Repo) {
155631×
    let Ok((_, wc)) = repo.working_copy() else {
15570×
        return;
1558
    };
155931×
    let heads = repo.bookmark_heads().unwrap_or_default();
156031×
    let newest = heads
156131×
        .iter()
156243×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
156331×
        .max_by_key(|(m, _)| m.hlc);
156431×
    println!(
1565
        "  {} {}",
156631×
        ui::dim(format!("{:<13}", "Working copy")),
156731×
        ui::id(wc.change_id.short(8))
1568
    );
156931×
    let tail = match newest {
157031×
        Some((m, _)) => format!(
1571
            ", newest {} {}",
157231×
            ui::id(m.change_id.short(8)),
157331×
            subject_of(&m.message)
1574
        ),
15750×
        None => String::new(),
1576
    };
157731×
    println!(
1578
        "  {} {}: {}{tail}",
157931×
        ui::dim(format!("{:<13}", "Bookmark")),
158031×
        ui::bookmark(&repo.config.bookmark),
158131×
        plural(heads.len(), "head")
1582
    );
158331×
}
1584
15850×
pub fn gc(now: bool) -> Result<i32> {
15860×
    let repo = open()?;
15870×
    let sp = ui::spinner("Packing and pruning…");
15880×
    let r = repo.gc_with(now, &mut |phase| sp.set(&format!("{phase}…")))?;
15890×
    sp.clear();
15900×
    if r.packed.objects > 0 {
15910×
        println!(
15920×
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
15930×
            plural(r.packed.objects, "object"),
15940×
            r.packed.raw_bytes,
15950×
            r.packed.packed_bytes,
15960×
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
15970×
        );
15980×
    }
15990×
    println!(
1600
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
16010×
        plural(r.reachable, "object"),
16020×
        plural(r.pruned.objects, "unreachable object"),
1603
        r.pruned.bytes,
16040×
        if r.pruned.deferred > 0 {
16050×
            format!(
1606
                "; {} deferred by the grace period (use --now)",
16070×
                plural(r.pruned.deferred, "object")
1608
            )
1609
        } else {
16100×
            String::new()
1611
        },
16120×
        if r.merged_packs > 0 {
16130×
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1614
        } else {
16150×
            String::new()
1616
        },
16170×
        plural(repo.store().pack_count(), "pack")
1618
    );
16190×
    Ok(0)
16200×
}
1621
1622
/// `oxy gc --remote NAME`: fold a store remote's bundles into one.
16232×
pub fn gc_remote(name: &str, now: bool) -> Result<i32> {
16242×
    let repo = open()?;
16252×
    let sp = ui::spinner(&format!("Folding {name}'s bundles…"));
16262×
    let r = repo.gc_remote(name, now)?;
16271×
    sp.clear();
16281×
    if r.merged > 0 {
16291×
        println!(
16301×
            "{} {} into one of {} bytes ({})",
16311×
            ui::done("Folded"),
16321×
            plural(r.merged, "bundle"),
16331×
            r.bundle_bytes,
16341×
            plural(r.changes, "change")
16351×
        );
16361×
    } else {
16370×
        println!(
16380×
            "{} {}",
16390×
            ui::note(),
16400×
            ui::dim("nothing to fold: one bundle holds everything")
16410×
        );
16420×
    }
16431×
    println!(
1644
        "  {} {}",
16451×
        ui::note(),
16461×
        ui::dim(format!(
1647
            "removed {}{}",
16481×
            plural(r.deleted, "superseded bundle"),
16491×
            if r.deferred > 0 {
16500×
                format!(
1651
                    "; {} kept for readers that may still fetch them (use --now)",
16520×
                    plural(r.deferred, "bundle")
1653
                )
1654
            } else {
16551×
                String::new()
1656
            }
1657
        ))
1658
    );
16591×
    Ok(0)
16602×
}
1661
1662
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
16630×
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1664
    use oxy_core::repo::Health;
16650×
    let repo = open()?;
16660×
    let sp = ui::spinner(if offline {
16670×
        "Checking…"
1668
    } else {
16690×
        "Checking, and contacting remotes…"
1670
    });
16710×
    let r = repo.doctor(!offline);
16720×
    sp.clear();
16730×
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
16740×
    let word = |h: Health| match h {
16750×
        Health::Ok => "ok",
16760×
        Health::Warn => "warning",
16770×
        Health::Fail => "fail",
16780×
    };
16790×
    if as_json {
16800×
        let checks: Vec<String> = r
16810×
            .checks
16820×
            .iter()
16830×
            .map(|c| {
16840×
                json::obj([
16850×
                    ("area", json::s(&c.area)),
16860×
                    ("health", json::s(word(c.health))),
16870×
                    ("message", json::s(&c.message)),
16880×
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
16890×
                ])
16900×
            })
16910×
            .collect();
16920×
        println!(
1693
            "{}",
16940×
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1695
        );
16960×
        return Ok(code);
16970×
    }
16980×
    let mut last = "";
16990×
    for c in &r.checks {
17000×
        if c.area != last {
17010×
            println!("{}", ui::section(&c.area));
17020×
            last = &c.area;
17030×
        }
17040×
        let mark = match c.health {
17050×
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
17060×
            Health::Warn => ui::caution(),
17070×
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1708
        };
17090×
        println!("  {mark} {}", c.message);
17100×
        if let Some(h) = &c.hint {
17110×
            println!("    {} {}", ui::dim("→"), ui::dim(h));
17120×
        }
1713
    }
17140×
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
17150×
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
17160×
    if fails + warns == 0 {
17170×
        println!("{}", ui::done("Everything looks right."));
17180×
    } else {
17190×
        println!(
1720
            "{} {}, {}.",
17210×
            if fails > 0 {
17220×
                ui::err(ui::glyph("✖", "x"))
1723
            } else {
17240×
                ui::caution()
1725
            },
17260×
            plural(fails, "problem"),
17270×
            plural(warns, "warning")
1728
        );
1729
    }
17300×
    Ok(code)
17310×
}
1732
1733
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
17340×
pub fn fsck(as_json: bool) -> Result<i32> {
1735
    use oxy_core::repo::Severity;
17360×
    let repo = open()?;
17370×
    let sp = ui::spinner("Checking every object…");
17380×
    let r = repo.fsck()?;
17390×
    sp.clear();
17400×
    let code = if r.errors() > 0 { 1 } else { 0 };
17410×
    if as_json {
17420×
        let problems: Vec<String> = r
17430×
            .problems
17440×
            .iter()
17450×
            .map(|p| {
17460×
                json::obj([
1747
                    (
1748
                        "severity",
17490×
                        json::s(match p.severity {
17500×
                            Severity::Error => "error",
17510×
                            Severity::Warning => "warning",
1752
                        }),
1753
                    ),
1754
                    (
17550×
                        "object",
17560×
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1757
                    ),
17580×
                    ("what", json::s(&p.what)),
1759
                ])
17600×
            })
17610×
            .collect();
17620×
        println!(
1763
            "{}",
17640×
            json::obj([
17650×
                ("ok", json::b(code == 0)),
17660×
                ("objects", json::n(r.objects)),
17670×
                ("ops", json::n(r.ops)),
17680×
                ("changes", json::n(r.changes)),
17690×
                ("signed", json::n(r.signed)),
17700×
                ("unsigned", json::n(r.unsigned)),
17710×
                ("checkpoints", json::n(r.checkpoints)),
17720×
                ("attestations", json::n(r.attestations)),
17730×
                ("errors", json::n(r.errors())),
17740×
                ("warnings", json::n(r.warnings())),
17750×
                ("problems", json::arr(problems)),
17760×
            ])
1777
        );
17780×
        return Ok(code);
17790×
    }
17800×
    println!(
1781
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
17820×
        plural(r.objects, "object"),
17830×
        plural(r.ops, "operation"),
17840×
        plural(r.changes, "change"),
1785
        r.signed,
1786
        r.unsigned,
17870×
        plural(r.checkpoints, "checkpoint"),
17880×
        plural(r.attestations, "attestation"),
1789
    );
17900×
    for p in &r.problems {
17910×
        let obj = p
17920×
            .object
17930×
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
17940×
            .unwrap_or_default();
17950×
        match p.severity {
17960×
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
17970×
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1798
        }
1799
    }
18000×
    if r.problems.is_empty() {
18010×
        println!("{}", ui::done("No problems found."));
18020×
    } else if code == 0 {
18030×
        println!(
18040×
            "{}",
18050×
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
18060×
        );
18070×
    } else {
18080×
        println!(
18090×
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
18100×
            ui::err(ui::glyph("✖", "x")),
18110×
            plural(r.errors(), "error"),
18120×
            plural(r.warnings(), "warning")
18130×
        );
18140×
    }
18150×
    Ok(code)
18160×
}
1817
1818
/// The head the working copy sits on, for commands that default to it. With
1819
/// several heads beneath the working copy, the most recently made one is
1820
/// chosen and announced.
18210×
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
18220×
    let snap = repo.snapshot_status("oxy")?;
18230×
    let base = snap.base.maximal(&snap.wc.deps);
18240×
    match base.as_slice() {
18250×
        [] => anyhow::bail!("the working copy sits on no change yet"),
18260×
        [h] => Ok(*h),
18270×
        many => {
18280×
            let latest = many
18290×
                .iter()
18300×
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
18310×
                .copied()
18320×
                .unwrap();
18330×
            let c = repo.store().get_change(&latest)?;
18340×
            println!(
1835
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
18360×
                short_id(&c),
18370×
                latest.short(12),
18380×
                many.len()
1839
            );
18400×
            Ok(latest)
1841
        }
1842
    }
18430×
}
1844
1845
/// `oxy describe` without -m: the working copy's name for a build.
18464×
pub fn describe_name(as_json: bool) -> Result<i32> {
18474×
    let repo = open()?;
18484×
    let d = repo.describe_working_copy()?;
18494×
    if as_json {
18503×
        println!(
1851
            "{}",
18523×
            json::obj([
18533×
                ("describe", json::s(&d.line())),
18543×
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
18553×
                ("distance", json::n(d.distance)),
18563×
                ("bookmark", json::s(&d.bookmark)),
18573×
                ("change", json::s(&d.change.to_hex())),
18583×
                ("hash", json::s(&d.hash.to_hex())),
18593×
                ("dirty", json::b(d.dirty)),
1860
            ])
1861
        );
18621×
    } else {
18631×
        println!("{}", d.line());
18641×
    }
18654×
    Ok(0)
18664×
}
1867
18680×
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
18690×
    let repo = open()?;
18700×
    let h = match change {
18710×
        Some(c) => repo.resolve_change(c)?,
18720×
        None => current_head(&repo)?,
1873
    };
18740×
    let new = repo.describe(&h, message)?;
18750×
    let c = repo.store().get_change_meta(&new)?;
18760×
    println!(
1877
        "{} {} {}  {}",
18780×
        ui::done("Described"),
18790×
        ui::id(c.change_id.short(8)),
18800×
        ui::hash(format!("#{}", new.short(12))),
18810×
        ui::subject(subject_of(message))
1882
    );
18830×
    Ok(0)
18840×
}
1885
18860×
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
18870×
    let repo = open()?;
18880×
    let new = match into {
18890×
        Some(spec) => {
18900×
            let target = repo.resolve_change(spec)?;
18910×
            repo.amend_into(&target, message)?
1892
        }
18930×
        None => repo.amend(message)?,
1894
    };
18950×
    let c = repo.store().get_change_meta(&new)?;
18960×
    println!(
1897
        "{} {} {}  {}",
18980×
        ui::done("Amended"),
18990×
        ui::id(c.change_id.short(8)),
19000×
        ui::hash(format!("#{}", new.short(12))),
19010×
        ui::subject(subject_of(&c.message))
1902
    );
19030×
    where_now(&repo);
19040×
    Ok(0)
19050×
}
1906
19070×
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
19080×
    let repo = open()?;
19090×
    let Some(r) = revset else {
19100×
        let h = repo.resolve_change(change.unwrap_or_default())?;
19110×
        abandon_one(&repo, h)?;
19120×
        where_now(&repo);
19130×
        return Ok(0);
1914
    };
1915
    // A revset: say what it selects, refuse an empty set, ask above a few.
19160×
    let selected = repo.revset(r)?;
19170×
    let wc = repo.working_copy().ok().map(|(h, _)| h);
19180×
    let hashes: Vec<ChangeHash> = selected
19190×
        .hashes
19200×
        .iter()
19210×
        .copied()
19220×
        .filter(|h| Some(*h) != wc)
19230×
        .collect();
19240×
    if hashes.is_empty() {
19250×
        anyhow::bail!("{r:?} selects no change to abandon");
19260×
    }
19270×
    println!(
1928
        "{} {} selects {}:",
19290×
        ui::section("abandon"),
19300×
        ui::id(r),
19310×
        plural(hashes.len(), "change")
1932
    );
19330×
    for h in &hashes {
19340×
        if let Some(m) = selected.metas.get(h) {
19350×
            println!(
19360×
                "  {} {}  {}",
19370×
                ui::id(m.change_id.short(8)),
19380×
                ui::hash(format!("#{}", h.short(12))),
19390×
                subject_of(&m.message)
19400×
            );
19410×
        }
1942
    }
1943
    const ASK_ABOVE: usize = 5;
19440×
    if hashes.len() > ASK_ABOVE && !yes {
19450×
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
19460×
    }
1947
    // Newest first: abandoning a change rewrites what depends on it, so a
1948
    // later member is found again by its ChangeId.
19490×
    let mut done = 0;
19500×
    for h in &hashes {
19510×
        let Some(m) = selected.metas.get(h) else {
19520×
            continue;
1953
        };
19540×
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
19550×
            Ok(h) => h,
19560×
            Err(_) => continue,
1957
        };
19580×
        abandon_one(&repo, now)?;
19590×
        done += 1;
1960
    }
19610×
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
19620×
    where_now(&repo);
19630×
    Ok(0)
19640×
}
1965
19660×
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
19670×
    let c = repo.store().get_change_meta(&h)?;
19680×
    let notes = repo.abandon(&h)?;
19690×
    println!(
1970
        "{} {} {}  {}",
19710×
        ui::done("Abandoned"),
19720×
        ui::id(c.change_id.short(8)),
19730×
        ui::hash(format!("#{}", h.short(12))),
19740×
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
1975
    );
19760×
    for n in notes {
19770×
        println!("  {} {n}", ui::note());
19780×
    }
19790×
    Ok(())
19800×
}
1981
19820×
pub fn checkpoint() -> Result<i32> {
19830×
    let repo = open()?;
19840×
    let sp = ui::spinner("Writing checkpoint…");
19850×
    let (r, changes, bytes) = repo.checkpoint()?;
19860×
    sp.done(&format!(
19870×
        "{} {} of {} ({} bytes) for {}",
19880×
        ui::done("Checkpoint"),
19890×
        ui::hash(format!("#{}", r.short(12))),
19900×
        plural(changes, "change"),
19910×
        bytes,
19920×
        ui::id(&repo.config.bookmark)
19930×
    ));
19940×
    Ok(0)
19950×
}
1996
1997
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
19980×
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
19990×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
20000×
        return Ok(1);
2001
    };
20020×
    let info = repo.quick_status()?;
20030×
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
20040×
        oxy_core::repo::GLYPH_PROMPT_FORMAT
2005
    } else {
20060×
        format
2007
    };
20080×
    let line = match color {
20090×
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
20100×
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
20110×
        Some(_) => info.format_colored(fmt, ("", "")),
20120×
        None => info.format(fmt),
2013
    };
20140×
    println!("{line}");
20150×
    Ok(0)
20160×
}
2017
20180×
pub fn sparse(paths: &[String]) -> Result<i32> {
20190×
    let mut repo = open()?;
20200×
    if paths.is_empty() {
20210×
        if repo.config.sparse_paths.is_empty() {
20220×
            println!("No sparse filter: the whole tree is materialized.");
20230×
        } else {
20240×
            println!("{}", ui::heading("Sparse filter"));
20250×
            for p in &repo.config.sparse_paths {
20260×
                println!("  {}", ui::path(p));
20270×
            }
2028
        }
20290×
        return Ok(0);
20300×
    }
20310×
    let snap = repo.snapshot("oxy sparse")?;
20320×
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
20330×
        anyhow::bail!(
2034
            "the working copy has changes; commit them before changing the sparse filter"
2035
        );
20360×
    }
20370×
    repo.config.set("filter.paths", &paths.join(","))?;
20380×
    repo.save_config()?;
20390×
    let heads = repo.bookmark_heads()?;
20400×
    let sp = ui::spinner("Re-checking out with the new filter…");
20410×
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
20420×
    sp.done(&format!(
20430×
        "{} {}: {} written, {} removed",
20440×
        ui::done("Sparse filter set to"),
20450×
        ui::path(paths.join(",")),
20460×
        plural(r.written, "file"),
20470×
        r.removed
20480×
    ));
20490×
    Ok(0)
20500×
}
2051
20522×
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
20532×
    let repo = open()?;
20542×
    repo.snapshot_status("oxy tag")?;
20552×
    let heads = if changes.is_empty() {
20562×
        repo.bookmark_heads()?
2057
    } else {
20580×
        let mut heads = Vec::new();
20590×
        for c in changes {
20600×
            heads.extend(repo.resolve_heads(c)?);
2061
        }
20620×
        heads
2063
    };
20642×
    let t = repo.tag_create(name, &heads, message)?;
20652×
    println!(
2066
        "{} {} {} {} ({}){}",
20672×
        ui::done("Tagged"),
20682×
        ui::bookmark(&t.name),
20692×
        ui::dim(ui::glyph("→", "->")),
20702×
        ui::hash(format!("#{}", t.state.short(12))),
20712×
        plural(t.heads.len(), "head"),
20722×
        t.signer
20732×
            .map(|s| format!(", signed by {s}"))
20742×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2075
    );
20762×
    Ok(0)
20772×
}
2078
20791×
pub fn tag_list(as_json: bool) -> Result<i32> {
20801×
    let repo = open()?;
20811×
    let tags = repo.tags()?;
20821×
    if as_json {
20831×
        println!(
2084
            "{}",
20851×
            json::arr(tags.iter().map(|t| {
20861×
                json::obj([
20871×
                    ("name", json::s(&t.name)),
20881×
                    ("state", json::s(&t.state.to_hex())),
20891×
                    ("heads", json::hashes(&t.heads)),
20901×
                    ("message", json::s(&t.message)),
2091
                    (
20921×
                        "signer",
20931×
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2094
                    ),
2095
                ])
20961×
            }))
2097
        );
20981×
        return Ok(0);
20990×
    }
21000×
    if tags.is_empty() {
21010×
        println!("{}", ui::dim("No tags."));
21020×
    }
21030×
    for t in tags {
21040×
        println!(
2105
            "{} {} {}{}{}{}",
21060×
            ui::ok(ui::glyph("⚑", "#")),
21070×
            ui::bookmark(&t.name),
2108
            // The heads, as `oxy log` shows changes, not the state hash.
21090×
            ui::hash(
21100×
                t.heads
21110×
                    .iter()
21120×
                    .map(|h| format!("#{}", h.short(12)))
21130×
                    .collect::<Vec<_>>()
21140×
                    .join(" ")
2115
            ),
21160×
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
21170×
            if t.message.is_empty() {
21180×
                String::new()
2119
            } else {
21200×
                format!("  {}", ui::subject(subject_of(&t.message)))
2121
            },
21220×
            t.signer
21230×
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
21240×
                .unwrap_or_default()
2125
        );
2126
    }
21270×
    Ok(0)
21281×
}
2129
2130
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2131
/// and workspace add take as "be on this bookmark" (oxygen#60).
21320×
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
21330×
    Ok(repo.view()?.bookmarks.contains_key(name)
21340×
        || repo
21350×
            .remote_only_bookmarks()?
21360×
            .iter()
21370×
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
21380×
}
2139
21400×
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
21410×
    let repo = open()?;
2142
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2143
    // this workspace's bookmark with that one's files.
21440×
    if let [name] = changes {
21450×
        if names_bookmark(&repo, name)? {
21460×
            let (local, _) = repo.local_bookmark_for(name)?;
21470×
            let heads = repo.resolve_heads(&local)?;
21480×
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
21490×
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
21500×
            sp.done(&format!(
21510×
                "{} {} (workspace {}) on {}",
21520×
                ui::done("Workspace created at"),
21530×
                ui::path(ws.root().display()),
21540×
                ui::id(ws.workspace().short(8)),
21550×
                ui::bookmark(&local)
21560×
            ));
21570×
            return Ok(0);
21580×
        }
21590×
    }
21600×
    let heads = if changes.is_empty() {
21610×
        None
2162
    } else {
21630×
        let mut heads = Vec::new();
21640×
        for c in changes {
21650×
            heads.extend(repo.resolve_heads(c)?);
2166
        }
21670×
        Some(heads)
2168
    };
21690×
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
21700×
    let ws = repo.workspace_add(path, heads.as_deref())?;
21710×
    sp.done(&format!(
21720×
        "{} {} (workspace {})",
21730×
        ui::done("Workspace created at"),
21740×
        ui::path(ws.root().display()),
21750×
        ui::id(ws.workspace().short(8))
21760×
    ));
21770×
    Ok(0)
21780×
}
2179
21801×
pub fn workspace_list(as_json: bool) -> Result<i32> {
21811×
    let repo = open()?;
21821×
    if as_json {
21831×
        println!(
2184
            "{}",
21851×
            json::arr(repo.workspaces()?.iter().map(|w| {
21861×
                json::obj([
21871×
                    ("id", json::s(&w.id.to_hex())),
21881×
                    ("path", json::s(&w.path.to_string_lossy())),
21891×
                    ("current", json::b(w.current)),
2190
                    (
21911×
                        "working_copy",
21921×
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2193
                    ),
2194
                ])
21951×
            }))
2196
        );
21971×
        return Ok(0);
21980×
    }
21990×
    for w in repo.workspaces()? {
22000×
        println!(
2201
            "{} {} {}{}",
22020×
            if w.current {
22030×
                ui::ok(ui::glyph("●", "*"))
2204
            } else {
22050×
                ui::dim(ui::glyph("○", "o"))
2206
            },
22070×
            ui::id(w.id.short(8)),
22080×
            ui::path(w.path.display()),
22090×
            w.working_copy
22100×
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
22110×
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2212
        );
2213
    }
22140×
    Ok(0)
22151×
}
2216
22170×
pub fn workspace_forget(spec: &str) -> Result<i32> {
22180×
    let repo = open()?;
22190×
    let all = repo.workspaces()?;
22200×
    let target = std::fs::canonicalize(spec).ok();
22210×
    let matches: Vec<_> = all
22220×
        .iter()
22230×
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
22240×
        .collect();
22250×
    let w = match matches.as_slice() {
22260×
        [w] => *w,
22270×
        [] => anyhow::bail!("no workspace matches {spec:?}"),
22280×
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2229
    };
22300×
    repo.workspace_forget(&w.id)?;
22310×
    println!(
2232
        "{} workspace {} at {}; its files were left in place.",
22330×
        ui::done("Forgot"),
22340×
        ui::id(w.id.short(8)),
22350×
        ui::path(w.path.display())
2236
    );
22370×
    Ok(0)
22380×
}
2239
22400×
pub fn lock(path: &str) -> Result<i32> {
22410×
    let repo = open()?;
22420×
    repo.lock_path(path)?;
22430×
    println!(
2244
        "{} {} {}",
22450×
        ui::done("Locked"),
22460×
        ui::path(path),
22470×
        ui::dim("(advisory, local)")
2248
    );
22490×
    Ok(0)
22500×
}
2251
22520×
pub fn unlock(path: &str) -> Result<i32> {
22530×
    let repo = open()?;
22540×
    repo.unlock_path(path)?;
22550×
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
22560×
    Ok(0)
22570×
}
2258
22590×
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
22600×
    let repo = open()?;
22610×
    let h = repo.resolve_change(change)?;
22620×
    let (h1, h2) = repo.split(&h, paths)?;
22630×
    let c1 = repo.store().get_change_meta(&h1)?;
22640×
    let c2 = repo.store().get_change_meta(&h2)?;
22650×
    println!(
2266
        "{} into {} {} and {} {}",
22670×
        ui::done("Split"),
22680×
        ui::id(c1.change_id.short(8)),
22690×
        ui::hash(format!("#{}", h1.short(12))),
22700×
        ui::id(c2.change_id.short(8)),
22710×
        ui::hash(format!("#{}", h2.short(12)))
2272
    );
22730×
    Ok(0)
22740×
}
2275
22766×
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
22776×
    let mut heads = Vec::new();
22786×
    for c in changes {
22796×
        heads.extend(repo.resolve_heads(c)?);
2280
    }
22816×
    Ok(heads)
22826×
}
2283
22846×
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
22856×
    let repo = open()?;
22866×
    repo.snapshot_status("oxy bookmark create")?;
22876×
    let heads = if changes.is_empty() {
22883×
        None
2289
    } else {
22903×
        let named = heads_from(&repo, changes)?;
22913×
        let (_, wc) = repo.working_copy()?;
22923×
        let gap = repo.state_gap(&wc.deps, &named)?;
22933×
        if upto {
22941×
            Some(gap.upto)
22952×
        } else if only || gap.earlier.is_empty() {
22961×
            Some(named)
2297
        } else {
22981×
            anyhow::bail!(
2299
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2300
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2301
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2302
                 or --only for just {0} and what it depends on.",
23031×
                changes.join(" "),
23041×
                plural(gap.earlier.len(), "change"),
23051×
                listed_changes(&repo, &gap.earlier)
2306
            );
2307
        }
2308
    };
23095×
    let heads = repo.bookmark_create(name, heads.as_deref())?;
23105×
    println!(
2311
        "{} bookmark {} {} {}",
23125×
        ui::done("Created"),
23135×
        ui::bookmark(name),
23145×
        ui::dim(ui::glyph("→", "->")),
23155×
        ui::dim(plural(heads.len(), "head"))
2316
    );
23175×
    println!(
2318
        "  {} {}",
23195×
        ui::note(),
23205×
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2321
    );
23225×
    Ok(0)
23236×
}
2324
2325
/// Up to five changes, newest last, as `  #hash subject` lines.
23262×
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
23272×
    let shown = changes.len().min(5);
23282×
    let mut lines: Vec<String> = changes[changes.len() - shown..]
23292×
        .iter()
23302×
        .map(|h| {
23312×
            let subject = repo
23322×
                .store()
23332×
                .get_change(h)
23342×
                .map(|c| subject_of(&c.message).to_string())
23352×
                .unwrap_or_default();
23362×
            format!("  #{} {subject}", h.short(12))
23372×
        })
23382×
        .collect();
23392×
    if changes.len() > shown {
23400×
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
23412×
    }
23422×
    lines.join("\n")
23432×
}
2344
23453×
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
23463×
    let repo = open()?;
23473×
    repo.snapshot_status("oxy bookmark set")?;
23483×
    let named = heads_from(&repo, changes)?;
2349
    // What the bookmark holds now and the new heads would leave out.
23503×
    let current = repo
23513×
        .bookmarks()?
23523×
        .into_iter()
23536×
        .find(|b| b.name == name)
23543×
        .map(|b| b.heads)
23553×
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
23563×
    let gap = repo.state_gap(&current, &named)?;
2357
    // A fast-forward: the new heads hold the bookmark's newest head, so
2358
    // what they leave out is older work nothing since has built on, such
2359
    // as an early change no later one depends on (oxygen#78). Keep it, as
2360
    // --upto does, and say so.
23613×
    let newest = current
23623×
        .iter()
23638×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m.hlc, *h)))
23643×
        .max()
23653×
        .map(|(_, h)| h);
2366
    // Ahead, too: a head the bookmark holds already (it would only drop
2367
    // the others) is not a move forward.
23683×
    let ahead = repo
23693×
        .load_state_history(&current)
23703×
        .is_ok_and(|st| named.iter().any(|h| !st.contains(h)));
23713×
    let forward = !only
23723×
        && ahead
23731×
        && !gap.earlier.is_empty()
23741×
        && newest.is_some_and(|n| {
23751×
            repo.load_state_history(&named)
23761×
                .is_ok_and(|st| st.contains(&n))
23771×
        });
23783×
    let heads = if upto {
23791×
        gap.upto
23802×
    } else if forward {
23811×
        println!(
2382
            "  {} {}",
23831×
            ui::note(),
23841×
            ui::dim(format!(
2385
                "{} builds on {name}'s newest head; keeping {} it holds that {0} does not depend on",
23861×
                changes.join(" "),
23871×
                plural(gap.earlier.len(), "change")
2388
            ))
2389
        );
23901×
        gap.upto
23911×
    } else if only || gap.earlier.is_empty() {
23920×
        named
2393
    } else {
23941×
        anyhow::bail!(
2395
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2396
             A state is its heads and what they depend on, not everything recorded before them.\n\
2397
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2398
             or --only for just {0} and what it depends on.",
23991×
            changes.join(" "),
24001×
            plural(gap.earlier.len(), "change"),
24011×
            listed_changes(&repo, &gap.earlier)
2402
        );
2403
    };
24042×
    let heads = repo.bookmark_set(name, &heads)?;
24052×
    println!(
2406
        "{} bookmark {} {} {}",
24072×
        ui::done("Moved"),
24082×
        ui::bookmark(name),
24092×
        ui::dim(ui::glyph("→", "->")),
24102×
        ui::dim(plural(heads.len(), "head"))
2411
    );
24122×
    Ok(0)
24133×
}
2414
24150×
pub fn bookmark_delete(name: &str) -> Result<i32> {
24160×
    let repo = open()?;
24170×
    repo.bookmark_delete(name)?;
24180×
    println!(
2419
        "{} bookmark {} {}",
24200×
        ui::done("Deleted"),
24210×
        ui::bookmark(name),
24220×
        ui::dim("(its changes stay until unreachable)")
2423
    );
24240×
    Ok(0)
24250×
}
2426
2427
/// Heads with their metadata, newest first.
24280×
fn heads_newest_first(
24290×
    repo: &Repo,
24300×
    heads: &[oxy_core::hash::ChangeHash],
24310×
) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> {
24320×
    let mut out: Vec<_> = heads
24330×
        .iter()
24340×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m)))
24350×
        .collect();
24360×
    out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc));
24370×
    out
24380×
}
2439
2440
/// One head as a line: id, hash, author, when, subject.
24410×
fn print_head(
24420×
    repo: &Repo,
24430×
    indent: &str,
24440×
    h: &oxy_core::hash::ChangeHash,
24450×
    m: &oxy_core::state::ChangeMeta,
24460×
) {
24470×
    println!(
2448
        "{indent}{} {} {}{}{}{}{}",
24490×
        ui::id(m.change_id.short(8)),
24500×
        ui::dim(format!("#{}", &h.to_hex()[..8])),
24510×
        author_name(repo, m),
24520×
        ui::sep(),
24530×
        ui::dim(ui::ago(m.hlc.wall_ms)),
24540×
        ui::sep(),
24550×
        ui::subject(subject_of(&m.message))
2456
    );
24570×
}
2458
24590×
pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result<i32> {
24600×
    let repo = open()?;
24610×
    let name = name.unwrap_or(&repo.config.bookmark).to_string();
24620×
    let view = repo.view()?;
24630×
    let st = match view.bookmarks.get(&name) {
24640×
        Some(st) => *st,
24650×
        None => match oxy_core::repo::remote_bookmark(&view, &name) {
24660×
            Some((_, _, st)) => st,
24670×
            None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"),
2468
        },
2469
    };
24700×
    let heads = repo.store().get_state(&st)?.heads;
24710×
    let shown = heads_newest_first(&repo, &heads);
24720×
    if as_json {
24730×
        println!(
2474
            "{}",
24750×
            json::obj([
24760×
                ("name", json::s(&name)),
24770×
                ("current", json::b(name == repo.config.bookmark)),
2478
                (
24790×
                    "heads",
24800×
                    json::arr(shown.iter().map(|(h, m)| {
24810×
                        json::obj([
24820×
                            ("hash", json::s(&h.to_hex())),
24830×
                            ("id", json::s(&m.change_id.to_string())),
24840×
                            ("author", json::s(&author_name(&repo, m))),
24850×
                            ("time_ms", json::n(m.hlc.wall_ms)),
24860×
                            ("subject", json::s(subject_of(&m.message))),
24870×
                        ])
24880×
                    }))
2489
                ),
2490
            ])
2491
        );
24920×
        return Ok(0);
24930×
    }
24940×
    println!(
2495
        "{} {}{}{}",
24960×
        ui::ok(ui::glyph("●", "*")),
24970×
        ui::bookmark(&name),
24980×
        ui::sep(),
24990×
        ui::dim(plural(heads.len(), "head"))
2500
    );
25010×
    for (h, m) in &shown {
25020×
        print_head(&repo, "  ", h, m);
25030×
    }
25040×
    if heads.len() > 1 {
25050×
        println!(
25060×
            "  {}",
25070×
            ui::dim("None depends on another: the bookmark is all of them and their dependencies.")
25080×
        );
25090×
    }
25100×
    Ok(0)
25110×
}
2512
25135×
pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result<i32> {
25145×
    let repo = open()?;
25155×
    let remote_only = repo.remote_only_bookmarks()?;
25165×
    if as_json {
25175×
        let mut items: Vec<String> = repo
25185×
            .bookmarks()?
25195×
            .into_iter()
252013×
            .map(|b| {
252113×
                json::obj([
252213×
                    ("name", json::s(&b.name)),
252313×
                    ("heads", json::hashes(&b.heads)),
252413×
                    ("current", json::b(b.current)),
252513×
                    ("ahead", json::opt(b.ahead, json::n)),
252613×
                    ("behind", json::opt(b.behind, json::n)),
252713×
                    ("remote", json::opt(b.remote.as_deref(), json::s)),
252813×
                ])
252913×
            })
25305×
            .collect();
25315×
        if all {
25320×
            items.extend(remote_only.iter().map(|b| {
25330×
                json::obj([
25340×
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
25350×
                    ("heads", json::hashes(&b.heads)),
25360×
                    ("current", json::b(false)),
25370×
                    ("ahead", "null".into()),
25380×
                    ("behind", "null".into()),
25390×
                    ("remote", json::s(&b.remote)),
25400×
                ])
25410×
            }));
25425×
        }
25435×
        println!("{}", json::arr(items));
25445×
        return Ok(0);
25450×
    }
25460×
    for b in repo.bookmarks()? {
25470×
        let mark = if b.current {
25480×
            ui::ok(ui::glyph("●", "*"))
2549
        } else {
25500×
            ui::dim(ui::glyph("○", "o"))
2551
        };
25520×
        let mut tail = String::new();
25530×
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
25540×
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
25550×
        }
25560×
        if let Some(n) = b.behind.filter(|n| *n > 0) {
25570×
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
25580×
        }
2559
        // Which remote, when there is a choice (oxygen#83).
25600×
        if !tail.is_empty() && repo.config.remotes.len() > 1 {
25610×
            if let Some(r) = &b.remote {
25620×
                tail += &ui::dim(format!(" {r}"));
25630×
            }
25640×
        }
25650×
        let shown = heads_newest_first(&repo, &b.heads);
2566
        // The newest head's subject, so a busy bookmark shows its latest work.
25670×
        let head = match shown.first() {
25680×
            Some(_) if verbose => String::new(),
25690×
            Some((_, m)) if b.heads.len() > 1 => format!(
2570
                "{} {}",
25710×
                ui::dim("newest"),
25720×
                ui::subject(subject_of(&m.message))
2573
            ),
25740×
            Some((_, m)) => ui::subject(subject_of(&m.message)),
25750×
            None => ui::dim("(empty)"),
2576
        };
25770×
        let head = if head.is_empty() {
25780×
            head
2579
        } else {
25800×
            format!("  {head}")
2581
        };
25820×
        println!(
2583
            "{mark} {}{}{}{tail}{head}",
25840×
            ui::bookmark(&b.name),
25850×
            ui::sep(),
25860×
            ui::dim(plural(b.heads.len(), "head"))
2587
        );
25880×
        if verbose {
25890×
            for (h, m) in &shown {
25900×
                print_head(&repo, "    ", h, m);
25910×
            }
25920×
        }
2593
    }
25940×
    if remote_only.is_empty() {
25950×
        return Ok(0);
25960×
    }
25970×
    if !all {
25980×
        println!(
2599
            "{}",
26000×
            ui::dim(format!(
2601
                "  and {} only on a remote: oxy bookmark list --all",
26020×
                plural(remote_only.len(), "bookmark")
2603
            ))
2604
        );
26050×
        return Ok(0);
26060×
    }
26070×
    for b in &remote_only {
26080×
        println!(
26090×
            "{} {}{}{}",
26100×
            ui::dim(ui::glyph("◌", ".")),
26110×
            ui::dim(format!("{}/{}", b.remote, b.name)),
26120×
            ui::sep(),
26130×
            ui::dim(plural(b.heads.len(), "head"))
26140×
        );
26150×
    }
26160×
    println!(
2617
        "  {} {}",
26180×
        ui::note(),
26190×
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2620
    );
26210×
    Ok(0)
26225×
}
2623
26243×
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
26253×
    let mut repo = open()?;
26263×
    let from = repo.config.bookmark.clone();
26273×
    let (local, created_from) = repo.local_bookmark_for(name)?;
26283×
    if let Some(remote) = created_from {
26290×
        println!(
26300×
            "{} {} from {}",
26310×
            ui::done("Created"),
26320×
            ui::bookmark(&local),
26330×
            ui::dim(format!("{remote}/{local}"))
26340×
        );
26353×
    }
26363×
    let name = local.as_str();
2637
    // Only behind its remote: take the remote's state, so the switch does
2638
    // not check out a stale one (oxygen#74).
26393×
    if let Some(n) = repo.catch_up_bookmark(name)? {
26400×
        println!(
26410×
            "{} {} with {}: {} it lacked",
26420×
            ui::done("Caught up"),
26430×
            ui::bookmark(name),
26440×
            ui::dim(format!("{}/{name}", repo.default_remote())),
26450×
            plural(n, "change")
26460×
        );
26473×
    }
26483×
    let sp = ui::spinner(&format!("Switching to {name}…"));
26493×
    let (r, carried) = if carry {
26500×
        repo.bookmark_switch_carry(name)?
2651
    } else {
26523×
        (repo.bookmark_switch(name, discard)?, vec![])
2653
    };
26543×
    sp.done(&format!(
2655
        "{} to {}: {} written, {} removed{}",
26563×
        ui::done("Switched"),
26573×
        ui::bookmark(name),
26583×
        plural(r.written, "file"),
2659
        r.removed,
26603×
        if carried.is_empty() {
26613×
            String::new()
2662
        } else {
26630×
            format!("; carried {}", plural(carried.len(), "changed path"))
2664
        }
2665
    ));
26663×
    if r.conflicted {
26670×
        println!(
26680×
            "  {} {}",
26690×
            ui::caution(),
26700×
            ui::warn("this state has conflicts; see oxy status")
26710×
        );
26723×
    }
2673
    // Say when the new state leaves out work the old one had: a state is
2674
    // its heads and what they depend on, which can be far less than a Git
2675
    // user expects.
26763×
    if r.lacks > 0 {
26771×
        println!(
26781×
            "  {} {}",
26791×
            ui::note(),
26801×
            ui::dim(format!(
26811×
                "{name} lacks {} that {from} has",
26821×
                plural(r.lacks, "change")
26831×
            ))
26841×
        );
26852×
    }
26863×
    super::sync::subrepos_behind(&repo);
26873×
    where_now(&repo);
26883×
    Ok(0)
26893×
}
2690
26910×
pub fn merge(bookmark: &str) -> Result<i32> {
26920×
    let repo = open()?;
26930×
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
26940×
    let r = repo.merge(bookmark)?;
26950×
    if !r.changed {
26960×
        sp.done(&format!(
26970×
            "{} {}",
26980×
            ui::ok(ui::glyph("✔", "*")),
26990×
            ui::dim(format!(
27000×
                "{} already contains {bookmark}",
27010×
                repo.config.bookmark
27020×
            ))
27030×
        ));
27040×
        return Ok(0);
27050×
    }
27060×
    sp.done(&format!(
2707
        "{} {} into {}: now {}{}",
27080×
        ui::done("Merged"),
27090×
        ui::bookmark(bookmark),
27100×
        ui::bookmark(&repo.config.bookmark),
27110×
        plural(r.heads.len(), "head"),
27120×
        ui::dim(if r.checked_out {
27130×
            "; working copy updated"
2714
        } else {
27150×
            "; run oxy checkout to update the working copy"
2716
        })
2717
    ));
27180×
    let snap = repo.snapshot("oxy merge")?;
27190×
    if snap.base_snapshot.is_conflicted() {
27200×
        println!(
27210×
            "  {} {}",
27220×
            ui::caution(),
27230×
            ui::warn("the result has conflicts; see oxy status")
27240×
        );
27250×
    }
27260×
    where_now(&repo);
27270×
    Ok(0)
27280×
}
2729
27300×
pub fn squash(change: &str, into: &str) -> Result<i32> {
27310×
    let repo = open()?;
27320×
    let c = repo.resolve_change(change)?;
27330×
    let d = repo.resolve_change(into)?;
27340×
    let sp = ui::spinner("Squashing…");
27350×
    let h = repo.squash(&c, &d)?;
27360×
    let new = repo.store().get_change_meta(&h)?;
27370×
    sp.done(&format!(
27380×
        "{} into {} {}  {}",
27390×
        ui::done("Squashed"),
27400×
        ui::id(new.change_id.short(8)),
27410×
        ui::hash(format!("#{}", h.short(12))),
27420×
        ui::subject(subject_of(&new.message))
27430×
    ));
27440×
    Ok(0)
27450×
}
2746
27470×
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
27480×
    let repo = open()?;
27490×
    let c = repo.resolve_change(change)?;
27500×
    let mut heads = Vec::new();
27510×
    for o in onto {
27520×
        heads.extend(repo.resolve_heads(o)?);
2753
    }
27540×
    let sp = ui::spinner("Rebasing…");
27550×
    let h = match repo.rebase(&c, &heads) {
27560×
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
27570×
            let r = repo.rebase_into_working_copy(&c, &heads)?;
27580×
            sp.done(&format!(
27590×
                "{} {} into {}: now {}",
27600×
                ui::done("Merged"),
27610×
                onto.join(" "),
27620×
                ui::bookmark(&repo.config.bookmark),
27630×
                plural(r.heads.len(), "head"),
27640×
            ));
27650×
            if r.checked_out {
27660×
                println!(
27670×
                    "  {} {}",
27680×
                    ui::caution(),
27690×
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
27700×
                );
27710×
            } else {
27720×
                println!(
27730×
                    "  {} {}",
27740×
                    ui::caution(),
27750×
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
27760×
                );
27770×
            }
27780×
            where_now(&repo);
27790×
            return Ok(0);
2780
        }
27810×
        other => other?,
2782
    };
27830×
    let new = repo.store().get_change_meta(&h)?;
27840×
    sp.done(&format!(
27850×
        "{} {} {}  {}",
27860×
        ui::done("Rebased"),
27870×
        ui::id(new.change_id.short(8)),
27880×
        ui::hash(format!("#{}", h.short(12))),
27890×
        ui::dim(format!(
27900×
            "now depends on {}",
27910×
            plural(new.deps.len(), "change")
27920×
        ))
27930×
    ));
27940×
    where_now(&repo);
27950×
    Ok(0)
27960×
}