OXYGENHUB

Coverage / src/cli/workspace.rs 37.9%

848 of 2237 lines run, 76 of 315 functions · run #256 on main · run missed

1
//! Commands that act on the local repository and working copy.
2
3
use super::format::{
4
    author_name, deps_line, deps_of, plural, short_id, signature_line, signature_mark_of,
5
    subject_of, via, when,
6
};
7
use super::json;
8
use super::open;
9
use super::ui;
10
use anyhow::Result;
11
use oxy_core::objects::ChangeKind;
12
use oxy_core::repo::SignatureStatus;
13
use oxy_core::repo::{render_change, ChangeStatus, Repo};
14
use std::io::Write;
15
use std::path::PathBuf;
16
1711×
pub fn init(path: Option<PathBuf>, bare: bool, store: Option<&str>) -> Result<i32> {
1811×
    let path = path.unwrap_or(std::env::current_dir()?);
1911×
    let repo = Repo::init_new(&path, bare, store)?;
2011×
    println!(
21
        "{} {}oxy repository in {}",
2211×
        ui::done("Initialized"),
2311×
        if bare { "bare " } else { "" },
2411×
        ui::path(repo.root().display())
25
    );
2611×
    println!(
27
        "{}",
2811×
        ui::kv("bookmark", ui::bookmark(&repo.config.bookmark))
29
    );
3011×
    if let Some(url) = &repo.config.storage_url {
310×
        println!(
320×
            "{}",
330×
            ui::kv(
340×
                "store",
350×
                format!(
360×
                    "{url} (cache in {}, up to {} MiB)",
370×
                    ui::path(repo.root().join(".oxy/cache").display()),
380×
                    repo.config.storage_cache >> 20
390×
                )
400×
            )
410×
        );
4211×
    }
4311×
    println!(
44
        "{}",
4511×
        ui::kv(
4611×
            "author",
4711×
            format!(
48
                "{} <{}>",
4911×
                ui::author(&repo.config.author_name),
50
                repo.config.author_email
51
            )
52
        )
53
    );
5411×
    Ok(0)
5511×
}
56
572×
fn status_tag(s: ChangeStatus) -> &'static str {
582×
    match s {
591×
        ChangeStatus::Added => "A",
600×
        ChangeStatus::Modified => "M",
610×
        ChangeStatus::Removed => "D",
620×
        ChangeStatus::Renamed => "R",
631×
        ChangeStatus::ModeChanged => "X",
640×
        ChangeStatus::ConflictEdited => "C!",
650×
        ChangeStatus::Resolved => "V",
66
    }
672×
}
68
69
/// Folders holding a repository of their own, which oxy leaves out (oxygen#43):
70
/// named, with how to track them.
7127×
fn print_untracked_nested(repo: &Repo, nested: &[String]) {
7227×
    if nested.is_empty() {
7325×
        return;
742×
    }
752×
    println!();
762×
    println!(
77
        "{} {}",
782×
        ui::section(ui::warn("Not tracked")),
792×
        ui::dim("folders holding a repository of their own")
80
    );
812×
    for p in nested {
822×
        let kind = if repo.root().join(p).join(".git").exists() {
832×
            "Git"
84
        } else {
850×
            "Oxygen"
86
        };
872×
        println!(
88
            "  {} {}  {}",
892×
            ui::caution(),
902×
            ui::path(format!("{p}/")),
912×
            ui::dim(format!("a nested {kind} repository"))
92
        );
93
    }
942×
    println!(
95
        "  {} {}",
962×
        ui::note(),
972×
        ui::dim(
98
            "to track one's files, remove its .git (or .oxy); to keep it a repository of its own, \
99
             oxy submodule add URL PATH; to leave it out quietly, list it in .oxyignore"
100
        )
101
    );
10227×
}
103
104
/// The working copy's changed paths, or that it is clean.
1054×
fn print_statuses(statuses: &[oxy_core::repo::PathStatus]) {
1064×
    if statuses.is_empty() {
1072×
        println!(
108
            "  {} {}",
1092×
            ui::ok(ui::glyph("✔", "*")),
1102×
            ui::dim("nothing to commit, working copy clean")
111
        );
1122×
        return;
1132×
    }
1142×
    println!();
1152×
    for s in statuses {
1162×
        println!(
1172×
            "  {} {}",
1182×
            ui::status_mark(status_tag(s.status)),
1192×
            ui::path(&s.path)
1202×
        );
1212×
    }
1224×
}
123
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).
1264×
fn print_behind(repo: &Repo) {
1274×
    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×
        );
1374×
    }
1384×
}
139
1407×
pub fn status(json: bool) -> Result<i32> {
1417×
    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.
1447×
    let known = if json {
1453×
        None
146
    } else {
1474×
        repo.status_by_manifest()?
148
    };
1497×
    if let Some(statuses) = known {
1502×
        let (_, wc) = repo.working_copy()?;
1512×
        let heads = repo.bookmark_heads()?;
1522×
        println!(
153
            "{} {}{}working copy {}{}{}",
1542×
            ui::dim("On"),
1552×
            ui::bookmark(&repo.config.bookmark),
1562×
            ui::sep(),
1572×
            ui::id(wc.change_id.short(8)),
1582×
            ui::sep(),
1592×
            ui::dim(plural(heads.len(), "head"))
160
        );
1612×
        print_behind(&repo);
1622×
        print_statuses(&statuses);
1632×
        print_untracked_nested(&repo, &repo.untracked_nested());
1642×
        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)
2267×
}
227
22823×
pub fn commit(
22923×
    message: &str,
23023×
    depends_on: &[String],
23123×
    paths: &[String],
23223×
    interactive: bool,
23323×
    hunks: &[usize],
23423×
) -> Result<i32> {
23523×
    let repo = open()?;
23623×
    let mut deps = Vec::new();
23723×
    for d in depends_on {
2380×
        deps.push(repo.resolve_change(d)?);
239
    }
24023×
    let selection = if !hunks.is_empty() {
2411×
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
24222×
    } 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)
31122×
    } else if paths.is_empty() {
31222×
        oxy_core::repo::Selection::All
313
    } else {
3140×
        oxy_core::repo::Selection::Paths(paths.to_vec())
315
    };
31623×
    let sp = ui::spinner("Committing…");
31723×
    let h = repo.commit_selection(message, &deps, &selection)?;
318
    // The metadata only: a first commit's change holds the whole tree.
31923×
    let meta = repo.store().get_change_meta(&h)?;
32023×
    sp.done(&format!(
32123×
        "{} {} {}  {}",
32223×
        ui::done("Committed"),
32323×
        ui::id(meta.change_id.short(8)),
32423×
        ui::hash(format!("#{}", h.short(12))),
32523×
        ui::subject(subject_of(message))
32623×
    ));
32723×
    print_untracked_nested(&repo, &repo.untracked_nested());
32823×
    if !matches!(selection, oxy_core::repo::Selection::All) {
3291×
        let rest = repo.snapshot_status("oxy commit")?;
3301×
        if !rest.statuses.is_empty() {
3311×
            println!(
3321×
                "  {} {}",
3331×
                ui::note(),
3341×
                ui::dim(format!(
3351×
                    "{} left uncommitted",
3361×
                    plural(rest.statuses.len(), "path")
3371×
                ))
3381×
            );
3391×
        }
34022×
    }
34123×
    where_now(&repo);
34223×
    Ok(0)
34323×
}
344
3450×
pub fn blame(path: &str, json: bool) -> Result<i32> {
3460×
    let repo = open()?;
3470×
    let lines = repo.blame(path)?;
3480×
    if json {
3490×
        let items = lines.iter().map(|l| {
3500×
            format!(
351
                "{{\"line\":{},\"change_id\":{},\"hash\":{},\"index\":{},\"author\":{},\"when_ms\":{}}}",
352
                l.line,
3530×
                oxy_core::repo::json_str(&l.change_id.to_hex()),
3540×
                oxy_core::repo::json_str(&l.hash.to_hex()),
355
                l.index,
3560×
                oxy_core::repo::json_str(&l.author),
357
                l.when_ms
358
            )
3590×
        });
3600×
        println!("{}", oxy_core::repo::json_array(items));
3610×
        return Ok(0);
3620×
    }
3630×
    let width = lines
3640×
        .iter()
3650×
        .map(|l| l.author.chars().count())
3660×
        .max()
3670×
        .unwrap_or(0)
3680×
        .min(20);
3690×
    let digits = lines.len().to_string().len();
3700×
    let _t = oxy_core::timing::phase("blame: print");
371
    // Most lines share their change with many others: each change's id,
372
    // author and age are formatted once, and the lines go out through one
373
    // buffered lock on stdout.
3740×
    let mut prefix: std::collections::HashMap<oxy_core::hash::ChangeHash, String> =
3750×
        std::collections::HashMap::new();
3760×
    let bar = ui::dim(ui::glyph("│", "|"));
3770×
    let mut out = std::io::BufWriter::with_capacity(1 << 16, std::io::stdout().lock());
3780×
    for l in &lines {
3790×
        let p = prefix.entry(l.hash).or_insert_with(|| {
3800×
            let author: String = l.author.chars().take(20).collect();
3810×
            format!(
382
                "{} {} {}",
3830×
                ui::id(l.change_id.short(8)),
3840×
                ui::author(format!("{author:<width$}")),
3850×
                ui::dim(ui::ago(l.when_ms))
386
            )
3870×
        });
3880×
        let text = String::from_utf8_lossy(&l.text);
3890×
        if writeln!(
3900×
            out,
391
            "{p} {:>digits$}{bar} {}",
392
            l.line,
3930×
            text.trim_end_matches('\n')
394
        )
3950×
        .is_err()
396
        {
397
            // A closed pipe (blame | head): stop quietly.
3980×
            return Ok(0);
3990×
        }
400
    }
4010×
    let _ = out.flush();
4020×
    Ok(0)
4030×
}
404
4050×
fn bisect_report(repo: &Repo, step: &oxy_core::repo::BisectStep) -> Result<i32> {
406
    use oxy_core::repo::BisectStep::*;
4070×
    match step {
4080×
        NeedMarks { good, bad } => {
4090×
            println!(
410
                "{} {} {}",
4110×
                ui::note(),
4120×
                ui::dim(format!("{good} good, {bad} bad;")),
4130×
                ui::dim(if *good == 0 {
4140×
                    "mark a known-good change or bookmark: oxy bisect good CHANGE"
415
                } else {
4160×
                    "mark a known-bad change or bookmark: oxy bisect bad CHANGE"
417
                })
418
            );
4190×
            Ok(0)
420
        }
421
        Testing {
4220×
            heads,
4230×
            remaining,
4240×
            steps_left,
425
        } => {
4260×
            println!(
427
                "{} {} {}",
4280×
                ui::done("Testing"),
4290×
                ui::dim(format!(
430
                    "{} in the state under test;",
4310×
                    plural(heads.len(), "head")
432
                )),
4330×
                ui::dim(format!(
434
                    "{remaining} candidates left, about {steps_left} more steps"
435
                ))
436
            );
4370×
            println!(
438
                "  {} {}",
4390×
                ui::note(),
4400×
                ui::dim("run your test, then oxy bisect good | bad | skip")
441
            );
4420×
            Ok(0)
443
        }
4440×
        Found { culprit } => {
4450×
            let c = repo.store().get_change(culprit)?;
4460×
            println!(
447
                "{} {} {}  {}",
4480×
                ui::done("Found"),
4490×
                ui::id(short_id(&c)),
4500×
                ui::hash(format!("#{}", culprit.short(12))),
4510×
                ui::subject(subject_of(&c.message))
452
            );
4530×
            println!("  {} {}", ui::note(), ui::dim("the first change whose inclusion makes the state bad; oxy bisect reset to return"));
4540×
            Ok(0)
455
        }
4560×
        Inconclusive { candidates } => {
4570×
            println!(
458
                "{} {}",
4590×
                ui::caution(),
4600×
                ui::warn(format!(
461
                    "every remaining candidate was skipped ({}); oxy bisect reset to return",
4620×
                    plural(candidates.len(), "change")
463
                ))
464
            );
4650×
            Ok(1)
466
        }
467
    }
4680×
}
469
4700×
pub fn bisect_start() -> Result<i32> {
4710×
    let repo = open()?;
4720×
    repo.bisect_start()?;
4730×
    println!(
474
        "{} bisect; {}",
4750×
        ui::done("Started"),
4760×
        ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE")
477
    );
4780×
    Ok(0)
4790×
}
480
4810×
pub fn bisect_mark(good: Option<bool>, changes: &[String]) -> Result<i32> {
4820×
    let repo = open()?;
4830×
    let mut heads = Vec::new();
4840×
    for c in changes {
4850×
        heads.extend(repo.resolve_heads(c)?);
486
    }
4870×
    let step = repo.bisect_mark(good, &heads)?;
4880×
    bisect_report(&repo, &step)
4890×
}
490
4910×
pub fn bisect_run(command: &[String]) -> Result<i32> {
4920×
    let repo = open()?;
4930×
    let step = repo.bisect_run(command)?;
4940×
    bisect_report(&repo, &step)
4950×
}
496
4971×
pub fn bisect_status(as_json: bool) -> Result<i32> {
4981×
    let repo = open()?;
4991×
    if as_json {
500
        use oxy_core::repo::BisectStep::*;
5011×
        let v = match repo.bisect_status()? {
5021×
            None => "null".to_string(),
5030×
            Some(NeedMarks { good, bad }) => json::obj([
5040×
                ("state", json::s("need-marks")),
5050×
                ("good", json::n(good)),
5060×
                ("bad", json::n(bad)),
5070×
            ]),
508
            Some(Testing {
5090×
                heads,
5100×
                remaining,
5110×
                steps_left,
5120×
            }) => json::obj([
5130×
                ("state", json::s("testing")),
5140×
                ("heads", json::hashes(&heads)),
5150×
                ("remaining", json::n(remaining)),
5160×
                ("steps_left", json::n(steps_left)),
5170×
            ]),
5180×
            Some(Found { culprit }) => json::obj([
5190×
                ("state", json::s("found")),
5200×
                ("culprit", json::s(&culprit.to_hex())),
5210×
            ]),
5220×
            Some(Inconclusive { candidates }) => json::obj([
5230×
                ("state", json::s("inconclusive")),
5240×
                ("candidates", json::hashes(&candidates)),
5250×
            ]),
526
        };
5271×
        println!("{v}");
5281×
        return Ok(0);
5290×
    }
5300×
    match repo.bisect_status()? {
531
        None => {
5320×
            println!("{}", ui::dim("No bisect in progress."));
5330×
            Ok(0)
534
        }
5350×
        Some(step) => bisect_report(&repo, &step),
536
    }
5371×
}
538
5390×
pub fn bisect_reset() -> Result<i32> {
5400×
    let repo = open()?;
5410×
    repo.bisect_reset()?;
5420×
    println!("{} bisect; working copy restored", ui::done("Reset"));
5430×
    Ok(0)
5440×
}
545
546
/// The log: one entry per change, newest first, joined by a rail. The
547
/// default view is the subject and a metadata line; `verbose` adds the full
548
/// message, dependencies, and the authenticating key.
54914×
fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
55014×
    Ok(match repo.authenticate_change(h)? {
5519×
        SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]),
552
        SignatureStatus::Valid {
5535×
            key,
5545×
            name,
5555×
            email,
5565×
            sealed,
5575×
            revoked,
5585×
        } => json::obj([
5595×
            ("status", json::s(if sealed { "sealed" } else { "signed" })),
5605×
            ("key", json::s(&key.to_hex())),
5615×
            ("name", json::s(&name)),
5625×
            ("email", json::s(&email)),
5635×
            ("revoked", json::b(revoked)),
564
        ]),
5650×
        SignatureStatus::Invalid(why) => {
5660×
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
567
        }
568
    })
56914×
}
570
57118×
fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result<String> {
57218×
    let c = &e.change;
57318×
    Ok(json::obj([
57418×
        ("hash", json::s(&e.hash.to_hex())),
57518×
        ("change_id", json::s(&c.change_id.to_hex())),
57618×
        ("author", json::s(&author_name(repo, c))),
57718×
        ("author_key", json::s(&c.author.to_hex())),
578
        (
57918×
            "via",
58018×
            match via(
58118×
                repo,
58218×
                &repo.authenticate_change_known(&e.hash, Some(c))?,
58318×
                &c.author,
584
            ) {
5850×
                Some(v) => json::obj([
5860×
                    ("name", json::s(&v.name)),
5870×
                    ("email", json::s(&v.email)),
5880×
                    ("key", json::s(&v.key.to_hex())),
5890×
                    ("scope", json::opt(v.scope.as_deref(), json::s)),
5900×
                    ("expires_ms", json::opt(v.expires, json::n)),
5910×
                    ("revoked", json::b(v.revoked)),
5920×
                ]),
59318×
                None => "null".to_string(),
594
            },
595
        ),
59618×
        ("when_ms", json::n(c.hlc.wall_ms)),
59718×
        ("message", json::s(&c.message)),
59818×
        ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())),
59918×
        ("deps", json::hashes(&c.deps)),
60018×
        ("head", json::b(e.is_head)),
60118×
        ("working_copy", json::b(e.is_working_copy)),
602
        (
60318×
            "signature",
60418×
            if e.is_working_copy {
6054×
                "null".into()
606
            } else {
60714×
                signature_json(repo, &e.hash)?
608
            },
609
        ),
610
    ]))
61118×
}
612
613
/// `START,END:PATH` for `oxy log -L`.
6142×
fn parse_line_range(spec: &str) -> Result<(usize, usize, &str)> {
6152×
    let bad = || anyhow::anyhow!("-L {spec}: expected START,END:PATH, as 10,24:src/lib.rs");
6162×
    let (range, path) = spec.split_once(':').ok_or_else(bad)?;
6172×
    let (a, b) = range.split_once(',').ok_or_else(bad)?;
618
    Ok((
6191×
        a.trim().parse().map_err(|_| bad())?,
6201×
        b.trim().parse().map_err(|_| bad())?,
6211×
        path,
622
    ))
6232×
}
624
6258×
pub fn log(
6268×
    revset: Option<&str>,
6278×
    limit: Option<usize>,
6288×
    verbose: bool,
6298×
    path: Option<&str>,
6308×
    lines: Option<&str>,
6318×
    as_json: bool,
6328×
) -> Result<i32> {
6338×
    let repo = open()?;
634
    // Whether the working copy is clean and conflicted: from the manifest
635
    // when it proves the working copy clean, else from a snapshot.
636
    // The working copy as last recorded, without looking at the files (as
637
    // Git's log does not): whether its change holds edits, and whether its
638
    // base was conflicted. `oxy status` is what checks the disk.
6398×
    let conflicted = !repo.is_at_op() && repo.recorded_conflicted()?;
6408×
    let listing = oxy_core::timing::phase("log: entries");
6418×
    let entries = match (path, lines) {
6428×
        _ if revset.is_some() => repo.log_revset(revset.unwrap_or_default())?,
6432×
        (_, Some(spec)) => {
6442×
            let (first, last, p) = parse_line_range(spec)?;
6451×
            let (_, wc) = repo.working_copy()?;
6461×
            let base = repo.load_state_history(&wc.deps)?.maximal(&wc.deps);
6471×
            repo.line_history(&base, p, first, last)?
648
        }
6491×
        (Some(p), None) => repo.log_for_path(p)?,
6505×
        (None, None) => repo.log()?,
651
    };
6527×
    drop(listing);
6537×
    let _print = oxy_core::timing::phase("log: print");
6547×
    if as_json {
6556×
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
6566×
        let mut items = Vec::new();
65717×
        for e in entries.iter().take(shown) {
65817×
            items.push(log_entry_json(&repo, e)?);
659
        }
6606×
        println!(
661
            "{}",
6626×
            json::obj([
6636×
                ("bookmark", json::s(&repo.config.bookmark)),
6646×
                ("total", json::n(entries.len())),
6656×
                ("changes", json::arr(items))
6666×
            ])
667
        );
6686×
        return Ok(0);
6691×
    }
6701×
    let total = entries.len();
6711×
    let shown = limit.unwrap_or(total).min(total);
672
    // Lay out a little past what is shown, so edges into the cut are drawn.
6731×
    let window: Vec<(ChangeHash, Vec<ChangeHash>)> = entries
6741×
        .iter()
6751×
        .take((shown + MAX_EDGE).min(total))
6764×
        .map(|e| (e.hash, e.change.deps.clone()))
6771×
        .collect();
6781×
    let rows = oxy_core::lanes::graph(&window, MAX_EDGE);
679
    // Highlight the shortest prefix that names each change: against the
680
    // whole log, which is what `resolve_change` searches.
681
    let everything;
6821×
    let all = if path.is_some() || lines.is_some() || revset.is_some() {
6830×
        everything = repo.log()?;
6840×
        &everything
685
    } else {
6861×
        &entries
687
    };
6884×
    let id_prefix = unique_prefixes(all.iter().map(|e| e.change.change_id.to_hex()));
6891×
    let labels = reference_labels(&repo)?;
6904×
    for (e, row) in entries.iter().take(shown).zip(&rows) {
6914×
        let c = &e.change;
6924×
        let bullet = ui::log_bullet(
6934×
            e.is_working_copy,
6944×
            e.is_head,
6954×
            e.is_working_copy && conflicted,
696
        );
6974×
        let id = c.change_id.to_hex();
6984×
        let n = id_prefix.get(&id).copied().unwrap_or(8).min(8);
6994×
        let mut head = vec![format!("{}{}", ui::id(&id[..n]), ui::dim(&id[n..8]))];
7004×
        head.push(ui::author(author_name(&repo, c)));
7014×
        head.push(ui::dim(ui::ago(c.hlc.wall_ms)));
7024×
        if let Some(names) = labels.get(&e.hash) {
7032×
            head.push(names.join(" "));
7042×
        }
7054×
        if c.kind == ChangeKind::Resolution {
7060×
            head.push(ui::warn("resolution"));
7074×
        }
7084×
        if !e.is_working_copy {
7093×
            head.push(ui::hash(format!("#{}", e.hash.short(8))));
7103×
            let status = repo.authenticate_change_known(&e.hash, Some(c))?;
7113×
            if let Some(agent) = via(&repo, &status, &c.author) {
7120×
                head.push(ui::dim(format!("via {}", agent.name)));
7133×
            }
7143×
            head.push(signature_mark_of(&status));
7151×
        }
7164×
        println!("{}{}", node_line(row, &bullet), head.join(" "));
7174×
        let subject = if e.is_working_copy && c.message.is_empty() {
7181×
            let edited = repo
7191×
                .store()
7201×
                .get_change(&e.hash)
7211×
                .is_ok_and(|w| !w.tree_ops.is_empty() || !w.edits.is_empty());
7221×
            ui::dim(if edited {
7230×
                "(working copy, uncommitted changes)"
724
            } else {
7251×
                "(working copy)"
726
            })
7273×
        } else if c.message.trim().is_empty() {
7280×
            ui::dim("(no description)")
729
        } else {
7303×
            subject_of(&c.message).to_string()
731
        };
7324×
        println!("{}{subject}", below_line(row));
7334×
        if verbose {
7340×
            let rail = continuation(row);
7350×
            if !e.is_working_copy {
7360×
                println!(
737
                    "{rail}{}",
7380×
                    ui::dim(format!(
739
                        "{} {}",
7400×
                        when(c.hlc.wall_ms),
7410×
                        signature_line(&repo, &e.hash)?
742
                    ))
743
                );
7440×
            }
7450×
            if !c.deps.is_empty() {
7460×
                println!(
7470×
                    "{rail}{} {}",
7480×
                    ui::dim(ui::glyph("↳", "->")),
7490×
                    ui::dim(deps_of(&c.deps))
7500×
                );
7510×
            }
7520×
            let body: Vec<&str> = c
7530×
                .message
7540×
                .lines()
7550×
                .skip(1)
7560×
                .skip_while(|l| l.trim().is_empty())
7570×
                .collect();
7580×
            for line in body {
7590×
                println!("{rail}  {line}");
7600×
            }
7614×
        }
762
    }
7631×
    if shown < total {
7640×
        if let Some(last) = rows.get(shown.saturating_sub(1)) {
7650×
            let cut: String = last
7660×
                .below
7670×
                .iter()
7680×
                .map(|c| match c {
7690×
                    Cell::Blank | Cell::Elided | Cell::JoinRight => "  ",
7700×
                    _ => "~ ",
7710×
                })
7720×
                .collect();
7730×
            if cut.trim().is_empty() {
7740×
                println!("{}", ui::dim("~"));
7750×
            } else {
7760×
                println!("{}", ui::dim(cut.trim_end()));
7770×
            }
7780×
        }
7790×
        println!(
780
            "{}",
7810×
            ui::dim(format!(
782
                "{} {} more; pass -n to see them",
7830×
                ui::glyph("…", "..."),
7840×
                total - shown
785
            ))
786
        );
7871×
    }
7881×
    Ok(0)
7898×
}
790
791
/// Rows a drawn edge may span in `oxy log`; a longer one is elided (`~`).
792
const MAX_EDGE: usize = 12;
793
794
use oxy_core::hash::ChangeHash;
795
use oxy_core::lanes::{Cell, GraphRow};
796
797
/// A graph cell, two columns wide.
7986×
fn cell(c: Cell) -> &'static str {
7996×
    match c {
8001×
        Cell::Blank => "  ",
8013×
        Cell::Line => ui::glyph("│ ", "| "),
8020×
        Cell::Elided => "~ ",
8031×
        Cell::JoinLeft => ui::glyph("├─", "|-"),
8040×
        Cell::JoinPass => ui::glyph("──", "--"),
8050×
        Cell::JoinCross => ui::glyph("┼─", "+-"),
8061×
        Cell::JoinRight => ui::glyph("╯ ", "' "),
807
    }
8086×
}
809
810
/// The graph part of a change's own line, its bullet in its column.
8114×
fn node_line(row: &GraphRow, bullet: &str) -> String {
8124×
    let width = row
8134×
        .passing
8144×
        .iter()
8154×
        .copied()
8164×
        .max()
8174×
        .unwrap_or(0)
8184×
        .max(row.column)
8194×
        + 1;
8204×
    let mut out = String::new();
8215×
    for c in 0..width {
8225×
        if c == row.column {
8234×
            out.push_str(bullet);
8244×
            out.push(' ');
8254×
        } else if row.passing.contains(&c) {
8261×
            out.push_str(&ui::dim(cell(Cell::Line)));
8271×
        } else {
8280×
            out.push_str("  ");
8290×
        }
830
    }
8314×
    out.push(' ');
8324×
    out
8334×
}
834
835
/// The graph part of the line under a change: lanes carrying on, a join,
836
/// or `~` for an elided edge.
8374×
fn below_line(row: &GraphRow) -> String {
8385×
    let g: String = row.below.iter().map(|c| cell(*c)).collect();
8394×
    format!("{} ", ui::dim(g))
8404×
}
841
842
/// The graph part of any further line of a change (`-v`).
8430×
fn continuation(row: &GraphRow) -> String {
8440×
    let g: String = row
8450×
        .below
8460×
        .iter()
8470×
        .map(|c| match c {
8480×
            Cell::Line | Cell::JoinLeft | Cell::JoinCross => cell(Cell::Line),
8490×
            _ => "  ",
8500×
        })
8510×
        .collect();
8520×
    format!("{} ", ui::dim(g))
8530×
}
854
855
/// For each hex ID, the length of its shortest prefix no other ID shares.
8561×
fn unique_prefixes(ids: impl Iterator<Item = String>) -> std::collections::HashMap<String, usize> {
8571×
    let mut v: Vec<String> = ids.collect();
8581×
    v.sort();
8591×
    v.dedup();
8606×
    let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
8611×
    let mut out = std::collections::HashMap::with_capacity(v.len());
8624×
    for i in 0..v.len() {
8634×
        let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 };
8644×
        let after = if i + 1 < v.len() {
8653×
            common(&v[i], &v[i + 1])
866
        } else {
8671×
            0
868
        };
8694×
        out.insert(v[i].clone(), before.max(after) + 1);
870
    }
8711×
    out
8721×
}
873
874
/// Bookmark, remote bookmark and tag names to show beside the changes they
875
/// point at. A name is shown on each head of its state; one with more than
876
/// three heads names too much of the log to help, so it is left out (oxy
877
/// bookmark list shows it). A remote bookmark at the same state as the
878
/// local one of that name is not repeated.
8791×
fn reference_labels(repo: &Repo) -> Result<std::collections::HashMap<ChangeHash, Vec<String>>> {
880
    const MAX_HEADS: usize = 3;
8811×
    let view = repo.view()?;
8821×
    let mut out: std::collections::HashMap<ChangeHash, Vec<String>> = Default::default();
8831×
    let mut add = |heads: Vec<ChangeHash>, label: String| {
8841×
        if heads.len() <= MAX_HEADS {
8852×
            for h in heads {
8862×
                out.entry(h).or_default().push(label.clone());
8872×
            }
8880×
        }
8891×
    };
8901×
    for (name, st) in &view.bookmarks {
8911×
        add(repo.store().get_state(st)?.heads, ui::bookmark(name));
892
    }
8931×
    for (remote, bookmarks) in &view.remotes {
8940×
        for (name, st) in bookmarks {
8950×
            if view.bookmarks.get(name) == Some(st) {
8960×
                continue;
8970×
            }
8980×
            add(
8990×
                repo.store().get_state(st)?.heads,
9000×
                ui::dim(format!("{remote}/{name}")),
901
            );
902
        }
903
    }
9041×
    for t in repo.tags()? {
9050×
        add(t.heads.clone(), ui::warn(&t.name));
9060×
    }
9071×
    Ok(out)
9081×
}
909
9101×
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
9111×
    let repo = open()?;
9121×
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
9131×
    if as_json {
9141×
        let files = repo.diff_files(hash.as_ref())?;
9153×
        let items = files.iter().map(|f| {
9163×
            json::obj([
9173×
                ("path", json::s(&f.path)),
9183×
                ("kind", json::s(&f.kind)),
9193×
                ("from", json::opt(f.from.as_deref(), json::s)),
920
                (
9213×
                    "hunks",
9223×
                    json::arr(f.hunks.iter().map(|h| {
9233×
                        json::obj([
9243×
                            ("base_line", json::n(h.base_line)),
925
                            (
9263×
                                "added",
9273×
                                json::arr(
9283×
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
929
                                ),
930
                            ),
931
                            (
9323×
                                "removed",
9333×
                                json::arr(h.removed.iter().map(|(n, l)| {
9340×
                                    json::obj([
9350×
                                        ("line", json::n(*n)),
9360×
                                        ("text", json::s(&String::from_utf8_lossy(l))),
9370×
                                    ])
9380×
                                })),
939
                            ),
940
                        ])
9413×
                    })),
942
                ),
943
            ])
9443×
        });
9451×
        println!(
946
            "{}",
9471×
            json::obj([
9481×
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
9491×
                ("files", json::arr(items))
950
            ])
951
        );
9521×
        return Ok(0);
9530×
    }
9540×
    match hash {
9550×
        Some(h) => {
9560×
            let c = repo.store().get_change(&h)?;
9570×
            let (base, snapshot) = repo.change_base(&c)?;
9580×
            print!("{}", render_change(&c, &base, &snapshot));
959
        }
960
        None => {
9610×
            let (wc, base, snapshot) = repo.working_copy_with_base()?;
9620×
            let text = {
9630×
                let _t = oxy_core::timing::phase("diff: render the change");
9640×
                render_change(&wc, &base, &snapshot)
965
            };
9660×
            print!("{text}");
967
            // The process ends here: freeing the base's tree and graphs
968
            // one by one would only cost time (about 27 ms on Linux).
9690×
            std::mem::forget((wc, base, snapshot));
970
        }
971
    }
9720×
    Ok(0)
9731×
}
974
9752×
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
9762×
    let repo = open()?;
9772×
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
9782×
    let bytes = match repo.file_at(path, heads.as_deref()) {
9792×
        Ok(b) => b,
980
        // -r CHANGE reads that change's dependency closure, not the
981
        // bookmark it is on: say so when the bookmark has the file
982
        // (oxygen#76).
9830×
        Err(e) => match change {
9840×
            Some(c)
9850×
                if !repo.view()?.bookmarks.contains_key(c)
9860×
                    && repo.tag_heads(c)?.is_none()
9870×
                    && repo.file_at(path, None).is_ok() =>
988
            {
9890×
                anyhow::bail!(
990
                    "{path} is not in {c}'s dependency closure (the change and what it \
991
                     depends on); it is on the bookmark: try -r {}, or --at-op OP for the \
992
                     state at an operation",
993
                    repo.config.bookmark
994
                )
995
            }
9960×
            _ => return Err(e.into()),
997
        },
998
    };
999
    use std::io::Write as _;
10002×
    std::io::stdout().write_all(&bytes)?;
10012×
    Ok(0)
10022×
}
1003
10041×
pub fn root(as_json: bool) -> Result<i32> {
10051×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
10060×
        if as_json {
10070×
            println!("null");
10080×
        }
10090×
        return Ok(1);
1010
    };
10111×
    if as_json {
10121×
        println!(
10131×
            "{}",
10141×
            json::obj([
10151×
                ("root", json::s(&repo.root().to_string_lossy())),
10161×
                ("workspace", json::s(&repo.workspace().to_hex())),
10171×
                ("bookmark", json::s(&repo.config.bookmark))
10181×
            ])
10191×
        );
10201×
    } else {
10210×
        println!("{}", repo.root().display());
10220×
    }
10231×
    Ok(0)
10241×
}
1025
10261×
pub fn version(as_json: bool) -> Result<i32> {
10271×
    if as_json {
10281×
        println!(
10291×
            "{}",
10301×
            json::obj([
10311×
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
10321×
                // What was built: a release's or install's `oxy describe`,
10331×
                // a Flow build's heads, or "local build".
10341×
                ("build", json::s(env!("OXY_BUILD_ID"))),
10351×
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
10361×
                ("format", json::n(2))
10371×
            ])
10381×
        );
10391×
    } else {
10400×
        println!(
10410×
            "oxy {} (repository format 2, protocol {})",
10420×
            env!("OXY_VERSION_LONG"),
10430×
            oxy_core::protocol::PROTOCOL_VERSION
10440×
        );
10450×
    }
10461×
    Ok(0)
10471×
}
1048
10492×
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
10502×
    let repo = open()?;
10512×
    if paths.is_empty() && hunks.is_empty() {
10520×
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
10532×
    }
10542×
    let mut n = 0;
10552×
    if !hunks.is_empty() {
10561×
        n += repo.discard_hunks(hunks)?;
10571×
    }
10582×
    if !paths.is_empty() {
10591×
        n += repo.discard(paths)?;
10601×
    }
10612×
    println!(
1062
        "{} {} restored to the working copy's base",
10632×
        ui::done("Discarded"),
10642×
        plural(n, "path")
1065
    );
10662×
    Ok(0)
10672×
}
1068
10692×
pub fn hunks(as_json: bool) -> Result<i32> {
10702×
    let repo = open()?;
10712×
    let (_, hunks) = repo.hunks()?;
10722×
    if as_json {
10732×
        println!(
1074
            "{}",
10755×
            json::arr(hunks.iter().map(|h| json::obj([
10765×
                ("index", json::n(h.index)),
10775×
                ("path", json::s(&h.path)),
10785×
                ("text", json::s(&h.text))
10795×
            ])))
1080
        );
10812×
        return Ok(0);
10820×
    }
10830×
    if hunks.is_empty() {
10840×
        println!(
10850×
            "{}",
10860×
            ui::dim("No hunks: the working copy matches its base.")
10870×
        );
10880×
    }
10890×
    for h in &hunks {
10900×
        println!(
1091
            "{} {}",
10920×
            ui::section(format!("hunk {}", h.index)),
10930×
            ui::path(&h.path)
1094
        );
10950×
        for line in h.text.lines() {
10960×
            let styled = if line.starts_with('+') {
10970×
                ui::ok(line)
10980×
            } else if line.starts_with('-') {
10990×
                ui::err(line)
1100
            } else {
11010×
                ui::dim(line)
1102
            };
11030×
            println!("  {styled}");
1104
        }
1105
    }
11060×
    Ok(0)
11072×
}
1108
11092×
pub fn show(change: Option<&str>, revset: Option<&str>, as_json: bool) -> Result<i32> {
11102×
    let repo = open()?;
11112×
    repo.snapshot_status("oxy show")?;
11122×
    let Some(r) = revset else {
11132×
        let h = repo.resolve_change(change.unwrap_or("@"))?;
11142×
        return show_one(&repo, h, as_json, false);
1115
    };
1116
    // Several changes: a JSON array, or the changes one after another.
11170×
    let hashes = repo.revset(r)?.hashes;
11180×
    if as_json {
11190×
        print!("[");
11200×
        for (i, h) in hashes.iter().enumerate() {
11210×
            if i > 0 {
11220×
                print!(",");
11230×
            }
11240×
            show_one(&repo, *h, true, true)?;
1125
        }
11260×
        println!("]");
11270×
        return Ok(0);
11280×
    }
11290×
    if hashes.is_empty() {
11300×
        println!("{}", ui::dim(format!("No change matches {r:?}.")));
11310×
        return Ok(0);
11320×
    }
11330×
    for (i, h) in hashes.iter().enumerate() {
11340×
        if i > 0 {
11350×
            println!();
11360×
        }
11370×
        show_one(&repo, *h, false, false)?;
1138
    }
11390×
    Ok(0)
11402×
}
1141
1142
/// One change, as `oxy show` prints it; `inline` JSON goes without its
1143
/// newline, for an array.
11442×
fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool) -> Result<i32> {
11452×
    let c = repo.store().get_change(&h)?;
11462×
    if as_json {
11471×
        let files = repo.diff_files(Some(&h))?;
11481×
        let heads = repo.bookmark_heads()?;
11491×
        let entry = oxy_core::repo::LogEntry {
11501×
            hash: h,
11511×
            change: oxy_core::state::ChangeMeta::of(&c),
11521×
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
11531×
            is_head: heads.contains(&h),
11541×
        };
11551×
        let mut body = log_entry_json(repo, &entry)?;
11561×
        body.pop();
11571×
        body.push_str(&format!(
1158
            ",{}:{}}}",
11591×
            json::s("files"),
11601×
            json::arr(files.iter().map(|f| json::obj([
11611×
                ("path", json::s(&f.path)),
11621×
                ("kind", json::s(&f.kind)),
11631×
                ("from", json::opt(f.from.as_deref(), json::s))
11641×
            ])))
1165
        ));
11661×
        if inline {
11670×
            print!("{body}");
11681×
        } else {
11691×
            println!("{body}");
11701×
        }
11711×
        return Ok(0);
11721×
    }
11731×
    println!(
1174
        "{} {} {}",
11751×
        ui::section("change"),
11761×
        ui::id(short_id(&c)),
11771×
        ui::hash(format!("#{h}"))
1178
    );
11791×
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1180
    // Fetched but not pulled (oxygen#56): say where it is.
11811×
    if let Some(at) = repo.remote_only_location(&h)? {
11820×
        println!(
11830×
            "{}",
11840×
            ui::kv(
11850×
                "only in",
11860×
                ui::warn(format!(
11870×
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
11880×
                ))
11890×
            )
11900×
        );
11911×
    }
11921×
    let meta = oxy_core::state::ChangeMeta::of(&c);
11931×
    let status = repo.authenticate_change_known(&h, Some(&meta))?;
11941×
    println!("{}", ui::kv("author", ui::author(author_name(repo, &meta))));
11951×
    if let Some(agent) = via(repo, &status, &meta.author) {
11960×
        println!("{}", ui::kv("via", agent.line()));
11971×
    }
11981×
    println!(
1199
        "{}",
12001×
        ui::kv(
12011×
            "date",
12021×
            format!(
1203
                "{} {}",
12041×
                when(c.hlc.wall_ms),
12051×
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1206
            )
1207
        )
1208
    );
12091×
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
12101×
    println!("{}", ui::kv("sig", signature_line(repo, &h)?));
12111×
    println!();
12124×
    for line in (if c.message.is_empty() {
12130×
        "(no description)"
1214
    } else {
12151×
        &c.message
1216
    })
12171×
    .lines()
12184×
    {
12194×
        println!("    {line}");
12204×
    }
12211×
    println!();
12221×
    print!("{}", repo.describe_change(&h)?);
12231×
    Ok(0)
12242×
}
1225
12260×
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
12270×
    let repo = open()?;
1228
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1229
    // BRANCH` is: checking its files out under another bookmark's name
1230
    // made the next commit move the wrong bookmark (oxygen#60).
12310×
    if let [name] = changes {
12320×
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
12330×
            drop(repo);
12340×
            return bookmark_switch(name, discard, carry);
12350×
        }
12360×
    }
12370×
    let heads = if changes.is_empty() {
12380×
        repo.bookmark_heads()?
1239
    } else {
12400×
        let mut heads = Vec::new();
12410×
        for c in changes {
12420×
            heads.extend(repo.resolve_heads(c)?);
1243
        }
12440×
        heads
1245
    };
12460×
    let spec = if changes.is_empty() {
12470×
        repo.config.bookmark.clone()
1248
    } else {
12490×
        changes.join(" ")
1250
    };
12510×
    let sp = ui::spinner(&format!("Checking out {spec}…"));
12520×
    let command = format!("oxy checkout {spec}");
12530×
    let (r, carried) = if carry {
12540×
        repo.checkout_carry(&heads, &spec, &command)?
1255
    } else {
12560×
        (repo.checkout(&heads, discard, &command)?, vec![])
1257
    };
12580×
    sp.done(&format!(
1259
        "{} on {}: {} written, {} removed{}",
12600×
        ui::done("Working copy"),
12610×
        ui::bookmark(&spec),
12620×
        plural(r.written, "file"),
1263
        r.removed,
12640×
        if carried.is_empty() {
12650×
            String::new()
1266
        } else {
12670×
            format!("; carried {}", plural(carried.len(), "changed path"))
1268
        }
1269
    ));
12700×
    for n in &r.notes {
12710×
        println!("  {} {n}", ui::note());
12720×
    }
12730×
    if r.conflicted {
12740×
        println!(
12750×
            "  {} {}",
12760×
            ui::caution(),
12770×
            ui::warn("this state has conflicts; see oxy status")
12780×
        );
12790×
    }
12800×
    where_now(&repo);
12810×
    Ok(0)
12820×
}
1283
12841×
pub fn resolve(as_json: bool) -> Result<i32> {
12851×
    let repo = open()?;
12861×
    let snap = repo.snapshot("oxy resolve")?;
12871×
    if as_json {
12881×
        println!("{}", repo.status_json(&snap)?);
12891×
        return Ok(if snap.base_snapshot.is_conflicted() {
12900×
            2
1291
        } else {
12921×
            0
1293
        });
12940×
    }
12950×
    if !snap.base_snapshot.is_conflicted() {
12960×
        println!("The working copy's base has no conflicts.");
12970×
        return Ok(0);
12980×
    }
12990×
    let mut remaining = 0;
13000×
    for (p, f) in &snap.base_snapshot.files {
13010×
        if !f.is_conflicted() {
13020×
            continue;
13030×
        }
13040×
        match snap
13050×
            .statuses
13060×
            .iter()
13070×
            .find(|s| s.path == *p)
13080×
            .map(|s| s.status)
1309
        {
13100×
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
13110×
            Some(ChangeStatus::ConflictEdited) => {
13120×
                remaining += 1;
13130×
                println!("markers    {p}");
13140×
            }
13150×
            _ => {
13160×
                remaining += 1;
13170×
                println!("unresolved {p}");
13180×
            }
1319
        }
1320
    }
13210×
    for c in &snap.base_snapshot.tree.conflicts {
13220×
        remaining += 1;
13230×
        println!("tree       {c:?}");
13240×
    }
13250×
    if remaining == 0 {
13260×
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
13270×
        Ok(0)
1328
    } else {
13290×
        Ok(2)
1330
    }
13311×
}
1332
13330×
pub fn undo() -> Result<i32> {
13340×
    let repo = open()?;
13350×
    let op = repo.undo()?;
13360×
    println!("{} now at: {}", ui::done("Undone;"), ui::dim(&op.command));
13370×
    where_now(&repo);
13380×
    Ok(0)
13390×
}
1340
13411×
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
13421×
    let repo = open()?;
13431×
    let ops = repo.op_log()?;
1344
    // What each operation changed, against the one before it.
134511×
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
134611×
        match ops.get(i + 1) {
134710×
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
13481×
            None => Ok(vec![]),
1349
        }
135011×
    };
13511×
    if as_json {
13521×
        let mut items = Vec::new();
135311×
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
135411×
            let summary: Vec<String> = changes_of(i)?
135511×
                .iter()
135611×
                .map(|c| change_words(&repo, c))
135711×
                .collect();
135811×
            items.push(json::obj([
135911×
                ("id", json::s(&r.to_hex())),
136011×
                ("when_ms", json::n(op.hlc.wall_ms)),
136111×
                ("command", json::s(&op.command)),
136211×
                ("snapshot", json::b(op.is_snapshot())),
136311×
                ("current", json::b(i == 0)),
136411×
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1365
            ]));
1366
        }
13671×
        println!("{}", json::arr(items));
13681×
        return Ok(0);
13690×
    }
13700×
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
13710×
    let id = |r: &oxy_core::hash::ObjectRef| {
13720×
        let hex = r.to_hex();
13730×
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
13740×
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
13750×
    };
13760×
    let rail = ui::dim(ui::glyph("│", "|"));
13770×
    let (mut i, mut shown) = (0, 0);
13780×
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
13790×
        let (r, op) = &ops[i];
13800×
        let bullet = if i == 0 {
13810×
            ui::ok(ui::glyph("@", "@"))
1382
        } else {
13830×
            ui::dim(ui::glyph("○", "o"))
1384
        };
1385
        // A run of snapshots folds into one entry.
13860×
        let mut run = 1;
13870×
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
13880×
            run += 1;
13890×
        }
13900×
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
13910×
        if op.is_snapshot() {
13920×
            let span = if run > 1 {
13930×
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1394
            } else {
13950×
                String::new()
1396
            };
13970×
            println!(
1398
                "{bullet}  {}{} {when}",
13990×
                id(r),
14000×
                if span.is_empty() {
14010×
                    String::new()
1402
                } else {
14030×
                    format!(" {span}")
1404
                }
1405
            );
14060×
            println!(
1407
                "{rail}  {}",
14080×
                ui::dim(if run == 1 {
14090×
                    "working-copy snapshot".to_string()
1410
                } else {
14110×
                    format!("{run} working-copy snapshots")
1412
                })
1413
            );
1414
        } else {
14150×
            println!("{bullet}  {} {when}", id(r));
14160×
            let words: Vec<String> = changes_of(i)?
14170×
                .iter()
14180×
                .map(|c| change_words(&repo, c))
14190×
                .collect();
14200×
            let summary = if words.is_empty() {
14210×
                if i + 1 == ops.len() {
14220×
                    "created the repository".to_string()
1423
                } else {
14240×
                    "no bookmark or working-copy change".to_string()
1425
                }
1426
            } else {
14270×
                words.join("; ")
1428
            };
14290×
            println!(
1430
                "{rail}  {}",
14310×
                if i == 0 {
14320×
                    ui::subject(&summary)
1433
                } else {
14340×
                    summary
1435
                }
1436
            );
14370×
            let cmd = op.command.lines().next().unwrap_or("");
14380×
            let cmd: String = cmd.chars().take(100).collect();
14390×
            println!("{rail}  {}", ui::dim(cmd));
1440
        }
14410×
        i += run;
14420×
        shown += 1;
1443
    }
14440×
    if i < ops.len() {
14450×
        println!(
14460×
            "{}",
14470×
            ui::dim(format!(
14480×
                "{} {} older; pass -n to see more",
14490×
                ui::glyph("…", "..."),
14500×
                plural(ops.len() - i, "operation")
14510×
            ))
14520×
        );
14530×
    }
14540×
    Ok(0)
14551×
}
1456
1457
/// One change an operation made, in words.
145811×
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1459
    use oxy_core::repo::ViewChange::*;
14602×
    match c {
14610×
        BookmarkCreated { name, heads } => {
14620×
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1463
        }
14640×
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
14652×
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
14661×
        BookmarkMoved { name, from, to } => format!(
1467
            "{name}: {from} {} {}",
14681×
            ui::glyph("→", "->"),
14691×
            plural(*to, "head")
1470
        ),
14711×
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
14720×
        TagCreated { name } => format!("tagged {name}"),
14730×
        TagDeleted { name } => format!("removed tag {name}"),
14740×
        Policy => "trust policy changed".to_string(),
14758×
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
14768×
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
14770×
            Err(_) => "working copy moved".to_string(),
1478
        },
1479
    }
148011×
}
1481
14820×
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
14830×
    let repo = open()?;
14840×
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
14850×
    let r = repo.op_restore(op, discard)?;
14860×
    sp.done(&format!(
14870×
        "{} to operation {} {}",
14880×
        ui::done("Restored"),
14890×
        ui::hash(r.op.short(12)),
14900×
        ui::dim(r.command.lines().next().unwrap_or(""))
14910×
    ));
14920×
    println!(
1493
        "  {} {}",
14940×
        ui::note(),
14950×
        ui::dim(format!(
1496
            "{} written, {} removed; oxy undo goes back again",
14970×
            plural(r.checkout.written, "file"),
1498
            r.checkout.removed
1499
        ))
1500
    );
15010×
    where_now(&repo);
15020×
    Ok(0)
15030×
}
1504
15050×
pub fn op_revert(op: &str) -> Result<i32> {
15060×
    let repo = open()?;
15070×
    let r = repo.op_revert(op)?;
15080×
    let view = repo.view()?;
15090×
    let names: Vec<String> = r
15100×
        .reverted
15110×
        .iter()
15120×
        .map(|n| {
15130×
            if view.bookmarks.contains_key(n) {
15140×
                ui::bookmark(n)
1515
            } else {
15160×
                format!("{} (removed)", ui::bookmark(n))
1517
            }
15180×
        })
15190×
        .collect();
15200×
    println!(
1521
        "{} operation {} {}",
15220×
        ui::done("Reverted"),
15230×
        ui::hash(r.op.short(12)),
15240×
        ui::dim(r.command.lines().next().unwrap_or(""))
1525
    );
15260×
    println!(
1527
        "  {} {}",
15280×
        ui::note(),
15290×
        ui::dim(format!("as before it: {}", names.join(", ")))
1530
    );
15310×
    if !r.kept.is_empty() {
15320×
        println!(
15330×
            "  {} {}",
15340×
            ui::caution(),
15350×
            ui::warn(format!(
15360×
                "left as they are, having moved again since: {}",
15370×
                r.kept.join(", ")
15380×
            ))
15390×
        );
15400×
    }
15410×
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
15420×
        println!(
15430×
            "  {} {}",
15440×
            ui::note(),
15450×
            ui::dim("the working copy has work of its own: oxy checkout to move it")
15460×
        );
15470×
    }
15480×
    where_now(&repo);
15490×
    Ok(0)
15500×
}
1551
1552
/// Where the working copy and bookmark are now, after a command moved
1553
/// them (as jj says "Working copy now at").
155428×
pub fn where_now(repo: &Repo) {
155528×
    let Ok((_, wc)) = repo.working_copy() else {
15560×
        return;
1557
    };
155828×
    let heads = repo.bookmark_heads().unwrap_or_default();
155928×
    let newest = heads
156028×
        .iter()
156139×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
156228×
        .max_by_key(|(m, _)| m.hlc);
156328×
    println!(
1564
        "  {} {}",
156528×
        ui::dim(format!("{:<13}", "Working copy")),
156628×
        ui::id(wc.change_id.short(8))
1567
    );
156828×
    let tail = match newest {
156928×
        Some((m, _)) => format!(
1570
            ", newest {} {}",
157128×
            ui::id(m.change_id.short(8)),
157228×
            subject_of(&m.message)
1573
        ),
15740×
        None => String::new(),
1575
    };
157628×
    println!(
1577
        "  {} {}: {}{tail}",
157828×
        ui::dim(format!("{:<13}", "Bookmark")),
157928×
        ui::bookmark(&repo.config.bookmark),
158028×
        plural(heads.len(), "head")
1581
    );
158228×
}
1583
15840×
pub fn gc(now: bool) -> Result<i32> {
15850×
    let repo = open()?;
15860×
    let sp = ui::spinner("Packing and pruning…");
15870×
    let r = repo.gc_with(now, &mut |phase| sp.set(&format!("{phase}…")))?;
15880×
    sp.clear();
15890×
    if r.packed.objects > 0 {
15900×
        println!(
15910×
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
15920×
            plural(r.packed.objects, "object"),
15930×
            r.packed.raw_bytes,
15940×
            r.packed.packed_bytes,
15950×
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
15960×
        );
15970×
    }
15980×
    println!(
1599
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
16000×
        plural(r.reachable, "object"),
16010×
        plural(r.pruned.objects, "unreachable object"),
1602
        r.pruned.bytes,
16030×
        if r.pruned.deferred > 0 {
16040×
            format!(
1605
                "; {} deferred by the grace period (use --now)",
16060×
                plural(r.pruned.deferred, "object")
1607
            )
1608
        } else {
16090×
            String::new()
1610
        },
16110×
        if r.merged_packs > 0 {
16120×
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1613
        } else {
16140×
            String::new()
1615
        },
16160×
        plural(repo.store().pack_count(), "pack")
1617
    );
16180×
    Ok(0)
16190×
}
1620
1621
/// `oxy gc --remote NAME`: fold a store remote's bundles into one.
16222×
pub fn gc_remote(name: &str, now: bool) -> Result<i32> {
16232×
    let repo = open()?;
16242×
    let sp = ui::spinner(&format!("Folding {name}'s bundles…"));
16252×
    let r = repo.gc_remote(name, now)?;
16261×
    sp.clear();
16271×
    if r.merged > 0 {
16281×
        println!(
16291×
            "{} {} into one of {} bytes ({})",
16301×
            ui::done("Folded"),
16311×
            plural(r.merged, "bundle"),
16321×
            r.bundle_bytes,
16331×
            plural(r.changes, "change")
16341×
        );
16351×
    } else {
16360×
        println!(
16370×
            "{} {}",
16380×
            ui::note(),
16390×
            ui::dim("nothing to fold: one bundle holds everything")
16400×
        );
16410×
    }
16421×
    println!(
1643
        "  {} {}",
16441×
        ui::note(),
16451×
        ui::dim(format!(
1646
            "removed {}{}",
16471×
            plural(r.deleted, "superseded bundle"),
16481×
            if r.deferred > 0 {
16490×
                format!(
1650
                    "; {} kept for readers that may still fetch them (use --now)",
16510×
                    plural(r.deferred, "bundle")
1652
                )
1653
            } else {
16541×
                String::new()
1655
            }
1656
        ))
1657
    );
16581×
    Ok(0)
16592×
}
1660
1661
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
16620×
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1663
    use oxy_core::repo::Health;
16640×
    let repo = open()?;
16650×
    let sp = ui::spinner(if offline {
16660×
        "Checking…"
1667
    } else {
16680×
        "Checking, and contacting remotes…"
1669
    });
16700×
    let r = repo.doctor(!offline);
16710×
    sp.clear();
16720×
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
16730×
    let word = |h: Health| match h {
16740×
        Health::Ok => "ok",
16750×
        Health::Warn => "warning",
16760×
        Health::Fail => "fail",
16770×
    };
16780×
    if as_json {
16790×
        let checks: Vec<String> = r
16800×
            .checks
16810×
            .iter()
16820×
            .map(|c| {
16830×
                json::obj([
16840×
                    ("area", json::s(&c.area)),
16850×
                    ("health", json::s(word(c.health))),
16860×
                    ("message", json::s(&c.message)),
16870×
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
16880×
                ])
16890×
            })
16900×
            .collect();
16910×
        println!(
1692
            "{}",
16930×
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1694
        );
16950×
        return Ok(code);
16960×
    }
16970×
    let mut last = "";
16980×
    for c in &r.checks {
16990×
        if c.area != last {
17000×
            println!("{}", ui::section(&c.area));
17010×
            last = &c.area;
17020×
        }
17030×
        let mark = match c.health {
17040×
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
17050×
            Health::Warn => ui::caution(),
17060×
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1707
        };
17080×
        println!("  {mark} {}", c.message);
17090×
        if let Some(h) = &c.hint {
17100×
            println!("    {} {}", ui::dim("→"), ui::dim(h));
17110×
        }
1712
    }
17130×
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
17140×
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
17150×
    if fails + warns == 0 {
17160×
        println!("{}", ui::done("Everything looks right."));
17170×
    } else {
17180×
        println!(
1719
            "{} {}, {}.",
17200×
            if fails > 0 {
17210×
                ui::err(ui::glyph("✖", "x"))
1722
            } else {
17230×
                ui::caution()
1724
            },
17250×
            plural(fails, "problem"),
17260×
            plural(warns, "warning")
1727
        );
1728
    }
17290×
    Ok(code)
17300×
}
1731
1732
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
17330×
pub fn fsck(as_json: bool) -> Result<i32> {
1734
    use oxy_core::repo::Severity;
17350×
    let repo = open()?;
17360×
    let sp = ui::spinner("Checking every object…");
17370×
    let r = repo.fsck()?;
17380×
    sp.clear();
17390×
    let code = if r.errors() > 0 { 1 } else { 0 };
17400×
    if as_json {
17410×
        let problems: Vec<String> = r
17420×
            .problems
17430×
            .iter()
17440×
            .map(|p| {
17450×
                json::obj([
1746
                    (
1747
                        "severity",
17480×
                        json::s(match p.severity {
17490×
                            Severity::Error => "error",
17500×
                            Severity::Warning => "warning",
1751
                        }),
1752
                    ),
1753
                    (
17540×
                        "object",
17550×
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1756
                    ),
17570×
                    ("what", json::s(&p.what)),
1758
                ])
17590×
            })
17600×
            .collect();
17610×
        println!(
1762
            "{}",
17630×
            json::obj([
17640×
                ("ok", json::b(code == 0)),
17650×
                ("objects", json::n(r.objects)),
17660×
                ("ops", json::n(r.ops)),
17670×
                ("changes", json::n(r.changes)),
17680×
                ("signed", json::n(r.signed)),
17690×
                ("unsigned", json::n(r.unsigned)),
17700×
                ("checkpoints", json::n(r.checkpoints)),
17710×
                ("attestations", json::n(r.attestations)),
17720×
                ("errors", json::n(r.errors())),
17730×
                ("warnings", json::n(r.warnings())),
17740×
                ("problems", json::arr(problems)),
17750×
            ])
1776
        );
17770×
        return Ok(code);
17780×
    }
17790×
    println!(
1780
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
17810×
        plural(r.objects, "object"),
17820×
        plural(r.ops, "operation"),
17830×
        plural(r.changes, "change"),
1784
        r.signed,
1785
        r.unsigned,
17860×
        plural(r.checkpoints, "checkpoint"),
17870×
        plural(r.attestations, "attestation"),
1788
    );
17890×
    for p in &r.problems {
17900×
        let obj = p
17910×
            .object
17920×
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
17930×
            .unwrap_or_default();
17940×
        match p.severity {
17950×
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
17960×
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1797
        }
1798
    }
17990×
    if r.problems.is_empty() {
18000×
        println!("{}", ui::done("No problems found."));
18010×
    } else if code == 0 {
18020×
        println!(
18030×
            "{}",
18040×
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
18050×
        );
18060×
    } else {
18070×
        println!(
18080×
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
18090×
            ui::err(ui::glyph("✖", "x")),
18100×
            plural(r.errors(), "error"),
18110×
            plural(r.warnings(), "warning")
18120×
        );
18130×
    }
18140×
    Ok(code)
18150×
}
1816
1817
/// The head the working copy sits on, for commands that default to it. With
1818
/// several heads beneath the working copy, the most recently made one is
1819
/// chosen and announced.
18200×
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
18210×
    let snap = repo.snapshot_status("oxy")?;
18220×
    let base = snap.base.maximal(&snap.wc.deps);
18230×
    match base.as_slice() {
18240×
        [] => anyhow::bail!("the working copy sits on no change yet"),
18250×
        [h] => Ok(*h),
18260×
        many => {
18270×
            let latest = many
18280×
                .iter()
18290×
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
18300×
                .copied()
18310×
                .unwrap();
18320×
            let c = repo.store().get_change(&latest)?;
18330×
            println!(
1834
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
18350×
                short_id(&c),
18360×
                latest.short(12),
18370×
                many.len()
1838
            );
18390×
            Ok(latest)
1840
        }
1841
    }
18420×
}
1843
1844
/// `oxy describe` without -m: the working copy's name for a build.
18454×
pub fn describe_name(as_json: bool) -> Result<i32> {
18464×
    let repo = open()?;
18474×
    let d = repo.describe_working_copy()?;
18484×
    if as_json {
18493×
        println!(
1850
            "{}",
18513×
            json::obj([
18523×
                ("describe", json::s(&d.line())),
18533×
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
18543×
                ("distance", json::n(d.distance)),
18553×
                ("bookmark", json::s(&d.bookmark)),
18563×
                ("change", json::s(&d.change.to_hex())),
18573×
                ("hash", json::s(&d.hash.to_hex())),
18583×
                ("dirty", json::b(d.dirty)),
1859
            ])
1860
        );
18611×
    } else {
18621×
        println!("{}", d.line());
18631×
    }
18644×
    Ok(0)
18654×
}
1866
18670×
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
18680×
    let repo = open()?;
18690×
    let h = match change {
18700×
        Some(c) => repo.resolve_change(c)?,
18710×
        None => current_head(&repo)?,
1872
    };
18730×
    let new = repo.describe(&h, message)?;
18740×
    let c = repo.store().get_change_meta(&new)?;
18750×
    println!(
1876
        "{} {} {}  {}",
18770×
        ui::done("Described"),
18780×
        ui::id(c.change_id.short(8)),
18790×
        ui::hash(format!("#{}", new.short(12))),
18800×
        ui::subject(subject_of(message))
1881
    );
18820×
    Ok(0)
18830×
}
1884
18850×
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
18860×
    let repo = open()?;
18870×
    let new = match into {
18880×
        Some(spec) => {
18890×
            let target = repo.resolve_change(spec)?;
18900×
            repo.amend_into(&target, message)?
1891
        }
18920×
        None => repo.amend(message)?,
1893
    };
18940×
    let c = repo.store().get_change_meta(&new)?;
18950×
    println!(
1896
        "{} {} {}  {}",
18970×
        ui::done("Amended"),
18980×
        ui::id(c.change_id.short(8)),
18990×
        ui::hash(format!("#{}", new.short(12))),
19000×
        ui::subject(subject_of(&c.message))
1901
    );
19020×
    where_now(&repo);
19030×
    Ok(0)
19040×
}
1905
19060×
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
19070×
    let repo = open()?;
19080×
    let Some(r) = revset else {
19090×
        let h = repo.resolve_change(change.unwrap_or_default())?;
19100×
        abandon_one(&repo, h)?;
19110×
        where_now(&repo);
19120×
        return Ok(0);
1913
    };
1914
    // A revset: say what it selects, refuse an empty set, ask above a few.
19150×
    let selected = repo.revset(r)?;
19160×
    let wc = repo.working_copy().ok().map(|(h, _)| h);
19170×
    let hashes: Vec<ChangeHash> = selected
19180×
        .hashes
19190×
        .iter()
19200×
        .copied()
19210×
        .filter(|h| Some(*h) != wc)
19220×
        .collect();
19230×
    if hashes.is_empty() {
19240×
        anyhow::bail!("{r:?} selects no change to abandon");
19250×
    }
19260×
    println!(
1927
        "{} {} selects {}:",
19280×
        ui::section("abandon"),
19290×
        ui::id(r),
19300×
        plural(hashes.len(), "change")
1931
    );
19320×
    for h in &hashes {
19330×
        if let Some(m) = selected.metas.get(h) {
19340×
            println!(
19350×
                "  {} {}  {}",
19360×
                ui::id(m.change_id.short(8)),
19370×
                ui::hash(format!("#{}", h.short(12))),
19380×
                subject_of(&m.message)
19390×
            );
19400×
        }
1941
    }
1942
    const ASK_ABOVE: usize = 5;
19430×
    if hashes.len() > ASK_ABOVE && !yes {
19440×
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
19450×
    }
1946
    // Newest first: abandoning a change rewrites what depends on it, so a
1947
    // later member is found again by its ChangeId.
19480×
    let mut done = 0;
19490×
    for h in &hashes {
19500×
        let Some(m) = selected.metas.get(h) else {
19510×
            continue;
1952
        };
19530×
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
19540×
            Ok(h) => h,
19550×
            Err(_) => continue,
1956
        };
19570×
        abandon_one(&repo, now)?;
19580×
        done += 1;
1959
    }
19600×
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
19610×
    where_now(&repo);
19620×
    Ok(0)
19630×
}
1964
19650×
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
19660×
    let c = repo.store().get_change_meta(&h)?;
19670×
    let notes = repo.abandon(&h)?;
19680×
    println!(
1969
        "{} {} {}  {}",
19700×
        ui::done("Abandoned"),
19710×
        ui::id(c.change_id.short(8)),
19720×
        ui::hash(format!("#{}", h.short(12))),
19730×
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
1974
    );
19750×
    for n in notes {
19760×
        println!("  {} {n}", ui::note());
19770×
    }
19780×
    Ok(())
19790×
}
1980
19810×
pub fn checkpoint() -> Result<i32> {
19820×
    let repo = open()?;
19830×
    let sp = ui::spinner("Writing checkpoint…");
19840×
    let (r, changes, bytes) = repo.checkpoint()?;
19850×
    sp.done(&format!(
19860×
        "{} {} of {} ({} bytes) for {}",
19870×
        ui::done("Checkpoint"),
19880×
        ui::hash(format!("#{}", r.short(12))),
19890×
        plural(changes, "change"),
19900×
        bytes,
19910×
        ui::id(&repo.config.bookmark)
19920×
    ));
19930×
    Ok(0)
19940×
}
1995
1996
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
19970×
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
19980×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
19990×
        return Ok(1);
2000
    };
20010×
    let info = repo.quick_status()?;
20020×
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
20030×
        oxy_core::repo::GLYPH_PROMPT_FORMAT
2004
    } else {
20050×
        format
2006
    };
20070×
    let line = match color {
20080×
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
20090×
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
20100×
        Some(_) => info.format_colored(fmt, ("", "")),
20110×
        None => info.format(fmt),
2012
    };
20130×
    println!("{line}");
20140×
    Ok(0)
20150×
}
2016
20170×
pub fn sparse(paths: &[String]) -> Result<i32> {
20180×
    let mut repo = open()?;
20190×
    if paths.is_empty() {
20200×
        if repo.config.sparse_paths.is_empty() {
20210×
            println!("No sparse filter: the whole tree is materialized.");
20220×
        } else {
20230×
            println!("{}", ui::heading("Sparse filter"));
20240×
            for p in &repo.config.sparse_paths {
20250×
                println!("  {}", ui::path(p));
20260×
            }
2027
        }
20280×
        return Ok(0);
20290×
    }
20300×
    let snap = repo.snapshot("oxy sparse")?;
20310×
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
20320×
        anyhow::bail!(
2033
            "the working copy has changes; commit them before changing the sparse filter"
2034
        );
20350×
    }
20360×
    repo.config.set("filter.paths", &paths.join(","))?;
20370×
    repo.save_config()?;
20380×
    let heads = repo.bookmark_heads()?;
20390×
    let sp = ui::spinner("Re-checking out with the new filter…");
20400×
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
20410×
    sp.done(&format!(
20420×
        "{} {}: {} written, {} removed",
20430×
        ui::done("Sparse filter set to"),
20440×
        ui::path(paths.join(",")),
20450×
        plural(r.written, "file"),
20460×
        r.removed
20470×
    ));
20480×
    Ok(0)
20490×
}
2050
20512×
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
20522×
    let repo = open()?;
20532×
    repo.snapshot_status("oxy tag")?;
20542×
    let heads = if changes.is_empty() {
20552×
        repo.bookmark_heads()?
2056
    } else {
20570×
        let mut heads = Vec::new();
20580×
        for c in changes {
20590×
            heads.extend(repo.resolve_heads(c)?);
2060
        }
20610×
        heads
2062
    };
20632×
    let t = repo.tag_create(name, &heads, message)?;
20642×
    println!(
2065
        "{} {} {} {} ({}){}",
20662×
        ui::done("Tagged"),
20672×
        ui::bookmark(&t.name),
20682×
        ui::dim(ui::glyph("→", "->")),
20692×
        ui::hash(format!("#{}", t.state.short(12))),
20702×
        plural(t.heads.len(), "head"),
20712×
        t.signer
20722×
            .map(|s| format!(", signed by {s}"))
20732×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2074
    );
20752×
    Ok(0)
20762×
}
2077
20781×
pub fn tag_list(as_json: bool) -> Result<i32> {
20791×
    let repo = open()?;
20801×
    let tags = repo.tags()?;
20811×
    if as_json {
20821×
        println!(
2083
            "{}",
20841×
            json::arr(tags.iter().map(|t| {
20851×
                json::obj([
20861×
                    ("name", json::s(&t.name)),
20871×
                    ("state", json::s(&t.state.to_hex())),
20881×
                    ("heads", json::hashes(&t.heads)),
20891×
                    ("message", json::s(&t.message)),
2090
                    (
20911×
                        "signer",
20921×
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2093
                    ),
2094
                ])
20951×
            }))
2096
        );
20971×
        return Ok(0);
20980×
    }
20990×
    if tags.is_empty() {
21000×
        println!("{}", ui::dim("No tags."));
21010×
    }
21020×
    for t in tags {
21030×
        println!(
2104
            "{} {} {}{}{}{}",
21050×
            ui::ok(ui::glyph("⚑", "#")),
21060×
            ui::bookmark(&t.name),
2107
            // The heads, as `oxy log` shows changes, not the state hash.
21080×
            ui::hash(
21090×
                t.heads
21100×
                    .iter()
21110×
                    .map(|h| format!("#{}", h.short(12)))
21120×
                    .collect::<Vec<_>>()
21130×
                    .join(" ")
2114
            ),
21150×
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
21160×
            if t.message.is_empty() {
21170×
                String::new()
2118
            } else {
21190×
                format!("  {}", ui::subject(subject_of(&t.message)))
2120
            },
21210×
            t.signer
21220×
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
21230×
                .unwrap_or_default()
2124
        );
2125
    }
21260×
    Ok(0)
21271×
}
2128
2129
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2130
/// and workspace add take as "be on this bookmark" (oxygen#60).
21310×
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
21320×
    Ok(repo.view()?.bookmarks.contains_key(name)
21330×
        || repo
21340×
            .remote_only_bookmarks()?
21350×
            .iter()
21360×
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
21370×
}
2138
21390×
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
21400×
    let repo = open()?;
2141
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2142
    // this workspace's bookmark with that one's files.
21430×
    if let [name] = changes {
21440×
        if names_bookmark(&repo, name)? {
21450×
            let (local, _) = repo.local_bookmark_for(name)?;
21460×
            let heads = repo.resolve_heads(&local)?;
21470×
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
21480×
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
21490×
            sp.done(&format!(
21500×
                "{} {} (workspace {}) on {}",
21510×
                ui::done("Workspace created at"),
21520×
                ui::path(ws.root().display()),
21530×
                ui::id(ws.workspace().short(8)),
21540×
                ui::bookmark(&local)
21550×
            ));
21560×
            return Ok(0);
21570×
        }
21580×
    }
21590×
    let heads = if changes.is_empty() {
21600×
        None
2161
    } else {
21620×
        let mut heads = Vec::new();
21630×
        for c in changes {
21640×
            heads.extend(repo.resolve_heads(c)?);
2165
        }
21660×
        Some(heads)
2167
    };
21680×
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
21690×
    let ws = repo.workspace_add(path, heads.as_deref())?;
21700×
    sp.done(&format!(
21710×
        "{} {} (workspace {})",
21720×
        ui::done("Workspace created at"),
21730×
        ui::path(ws.root().display()),
21740×
        ui::id(ws.workspace().short(8))
21750×
    ));
21760×
    Ok(0)
21770×
}
2178
21791×
pub fn workspace_list(as_json: bool) -> Result<i32> {
21801×
    let repo = open()?;
21811×
    if as_json {
21821×
        println!(
2183
            "{}",
21841×
            json::arr(repo.workspaces()?.iter().map(|w| {
21851×
                json::obj([
21861×
                    ("id", json::s(&w.id.to_hex())),
21871×
                    ("path", json::s(&w.path.to_string_lossy())),
21881×
                    ("current", json::b(w.current)),
2189
                    (
21901×
                        "working_copy",
21911×
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2192
                    ),
2193
                ])
21941×
            }))
2195
        );
21961×
        return Ok(0);
21970×
    }
21980×
    for w in repo.workspaces()? {
21990×
        println!(
2200
            "{} {} {}{}",
22010×
            if w.current {
22020×
                ui::ok(ui::glyph("●", "*"))
2203
            } else {
22040×
                ui::dim(ui::glyph("○", "o"))
2205
            },
22060×
            ui::id(w.id.short(8)),
22070×
            ui::path(w.path.display()),
22080×
            w.working_copy
22090×
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
22100×
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2211
        );
2212
    }
22130×
    Ok(0)
22141×
}
2215
22160×
pub fn workspace_forget(spec: &str) -> Result<i32> {
22170×
    let repo = open()?;
22180×
    let all = repo.workspaces()?;
22190×
    let target = std::fs::canonicalize(spec).ok();
22200×
    let matches: Vec<_> = all
22210×
        .iter()
22220×
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
22230×
        .collect();
22240×
    let w = match matches.as_slice() {
22250×
        [w] => *w,
22260×
        [] => anyhow::bail!("no workspace matches {spec:?}"),
22270×
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2228
    };
22290×
    repo.workspace_forget(&w.id)?;
22300×
    println!(
2231
        "{} workspace {} at {}; its files were left in place.",
22320×
        ui::done("Forgot"),
22330×
        ui::id(w.id.short(8)),
22340×
        ui::path(w.path.display())
2235
    );
22360×
    Ok(0)
22370×
}
2238
22390×
pub fn lock(path: &str) -> Result<i32> {
22400×
    let repo = open()?;
22410×
    repo.lock_path(path)?;
22420×
    println!(
2243
        "{} {} {}",
22440×
        ui::done("Locked"),
22450×
        ui::path(path),
22460×
        ui::dim("(advisory, local)")
2247
    );
22480×
    Ok(0)
22490×
}
2250
22510×
pub fn unlock(path: &str) -> Result<i32> {
22520×
    let repo = open()?;
22530×
    repo.unlock_path(path)?;
22540×
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
22550×
    Ok(0)
22560×
}
2257
22580×
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
22590×
    let repo = open()?;
22600×
    let h = repo.resolve_change(change)?;
22610×
    let (h1, h2) = repo.split(&h, paths)?;
22620×
    let c1 = repo.store().get_change_meta(&h1)?;
22630×
    let c2 = repo.store().get_change_meta(&h2)?;
22640×
    println!(
2265
        "{} into {} {} and {} {}",
22660×
        ui::done("Split"),
22670×
        ui::id(c1.change_id.short(8)),
22680×
        ui::hash(format!("#{}", h1.short(12))),
22690×
        ui::id(c2.change_id.short(8)),
22700×
        ui::hash(format!("#{}", h2.short(12)))
2271
    );
22720×
    Ok(0)
22730×
}
2274
22756×
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
22766×
    let mut heads = Vec::new();
22776×
    for c in changes {
22786×
        heads.extend(repo.resolve_heads(c)?);
2279
    }
22806×
    Ok(heads)
22816×
}
2282
22836×
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
22846×
    let repo = open()?;
22856×
    repo.snapshot_status("oxy bookmark create")?;
22866×
    let heads = if changes.is_empty() {
22873×
        None
2288
    } else {
22893×
        let named = heads_from(&repo, changes)?;
22903×
        let (_, wc) = repo.working_copy()?;
22913×
        let gap = repo.state_gap(&wc.deps, &named)?;
22923×
        if upto {
22931×
            Some(gap.upto)
22942×
        } else if only || gap.earlier.is_empty() {
22951×
            Some(named)
2296
        } else {
22971×
            anyhow::bail!(
2298
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2299
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2300
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2301
                 or --only for just {0} and what it depends on.",
23021×
                changes.join(" "),
23031×
                plural(gap.earlier.len(), "change"),
23041×
                listed_changes(&repo, &gap.earlier)
2305
            );
2306
        }
2307
    };
23085×
    let heads = repo.bookmark_create(name, heads.as_deref())?;
23095×
    println!(
2310
        "{} bookmark {} {} {}",
23115×
        ui::done("Created"),
23125×
        ui::bookmark(name),
23135×
        ui::dim(ui::glyph("→", "->")),
23145×
        ui::dim(plural(heads.len(), "head"))
2315
    );
23165×
    println!(
2317
        "  {} {}",
23185×
        ui::note(),
23195×
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2320
    );
23215×
    Ok(0)
23226×
}
2323
2324
/// Up to five changes, newest last, as `  #hash subject` lines.
23252×
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
23262×
    let shown = changes.len().min(5);
23272×
    let mut lines: Vec<String> = changes[changes.len() - shown..]
23282×
        .iter()
23292×
        .map(|h| {
23302×
            let subject = repo
23312×
                .store()
23322×
                .get_change(h)
23332×
                .map(|c| subject_of(&c.message).to_string())
23342×
                .unwrap_or_default();
23352×
            format!("  #{} {subject}", h.short(12))
23362×
        })
23372×
        .collect();
23382×
    if changes.len() > shown {
23390×
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
23402×
    }
23412×
    lines.join("\n")
23422×
}
2343
23443×
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
23453×
    let repo = open()?;
23463×
    repo.snapshot_status("oxy bookmark set")?;
23473×
    let named = heads_from(&repo, changes)?;
2348
    // What the bookmark holds now and the new heads would leave out.
23493×
    let current = repo
23503×
        .bookmarks()?
23513×
        .into_iter()
23526×
        .find(|b| b.name == name)
23533×
        .map(|b| b.heads)
23543×
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
23553×
    let gap = repo.state_gap(&current, &named)?;
2356
    // A fast-forward: the new heads hold the bookmark's newest head, so
2357
    // what they leave out is older work nothing since has built on, such
2358
    // as an early change no later one depends on (oxygen#78). Keep it, as
2359
    // --upto does, and say so.
23603×
    let newest = current
23613×
        .iter()
23628×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m.hlc, *h)))
23633×
        .max()
23643×
        .map(|(_, h)| h);
2365
    // Ahead, too: a head the bookmark holds already (it would only drop
2366
    // the others) is not a move forward.
23673×
    let ahead = repo
23683×
        .load_state_history(&current)
23693×
        .is_ok_and(|st| named.iter().any(|h| !st.contains(h)));
23703×
    let forward = !only
23713×
        && ahead
23721×
        && !gap.earlier.is_empty()
23731×
        && newest.is_some_and(|n| {
23741×
            repo.load_state_history(&named)
23751×
                .is_ok_and(|st| st.contains(&n))
23761×
        });
23773×
    let heads = if upto {
23781×
        gap.upto
23792×
    } else if forward {
23801×
        println!(
2381
            "  {} {}",
23821×
            ui::note(),
23831×
            ui::dim(format!(
2384
                "{} builds on {name}'s newest head; keeping {} it holds that {0} does not depend on",
23851×
                changes.join(" "),
23861×
                plural(gap.earlier.len(), "change")
2387
            ))
2388
        );
23891×
        gap.upto
23901×
    } else if only || gap.earlier.is_empty() {
23910×
        named
2392
    } else {
23931×
        anyhow::bail!(
2394
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2395
             A state is its heads and what they depend on, not everything recorded before them.\n\
2396
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2397
             or --only for just {0} and what it depends on.",
23981×
            changes.join(" "),
23991×
            plural(gap.earlier.len(), "change"),
24001×
            listed_changes(&repo, &gap.earlier)
2401
        );
2402
    };
24032×
    let heads = repo.bookmark_set(name, &heads)?;
24042×
    println!(
2405
        "{} bookmark {} {} {}",
24062×
        ui::done("Moved"),
24072×
        ui::bookmark(name),
24082×
        ui::dim(ui::glyph("→", "->")),
24092×
        ui::dim(plural(heads.len(), "head"))
2410
    );
24112×
    Ok(0)
24123×
}
2413
24140×
pub fn bookmark_delete(name: &str) -> Result<i32> {
24150×
    let repo = open()?;
24160×
    repo.bookmark_delete(name)?;
24170×
    println!(
2418
        "{} bookmark {} {}",
24190×
        ui::done("Deleted"),
24200×
        ui::bookmark(name),
24210×
        ui::dim("(its changes stay until unreachable)")
2422
    );
24230×
    Ok(0)
24240×
}
2425
2426
/// Heads with their metadata, newest first.
24270×
fn heads_newest_first(
24280×
    repo: &Repo,
24290×
    heads: &[oxy_core::hash::ChangeHash],
24300×
) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> {
24310×
    let mut out: Vec<_> = heads
24320×
        .iter()
24330×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m)))
24340×
        .collect();
24350×
    out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc));
24360×
    out
24370×
}
2438
2439
/// One head as a line: id, hash, author, when, subject.
24400×
fn print_head(
24410×
    repo: &Repo,
24420×
    indent: &str,
24430×
    h: &oxy_core::hash::ChangeHash,
24440×
    m: &oxy_core::state::ChangeMeta,
24450×
) {
24460×
    println!(
2447
        "{indent}{} {} {}{}{}{}{}",
24480×
        ui::id(m.change_id.short(8)),
24490×
        ui::dim(format!("#{}", &h.to_hex()[..8])),
24500×
        author_name(repo, m),
24510×
        ui::sep(),
24520×
        ui::dim(ui::ago(m.hlc.wall_ms)),
24530×
        ui::sep(),
24540×
        ui::subject(subject_of(&m.message))
2455
    );
24560×
}
2457
24580×
pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result<i32> {
24590×
    let repo = open()?;
24600×
    let name = name.unwrap_or(&repo.config.bookmark).to_string();
24610×
    let view = repo.view()?;
24620×
    let st = match view.bookmarks.get(&name) {
24630×
        Some(st) => *st,
24640×
        None => match oxy_core::repo::remote_bookmark(&view, &name) {
24650×
            Some((_, _, st)) => st,
24660×
            None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"),
2467
        },
2468
    };
24690×
    let heads = repo.store().get_state(&st)?.heads;
24700×
    let shown = heads_newest_first(&repo, &heads);
24710×
    if as_json {
24720×
        println!(
2473
            "{}",
24740×
            json::obj([
24750×
                ("name", json::s(&name)),
24760×
                ("current", json::b(name == repo.config.bookmark)),
2477
                (
24780×
                    "heads",
24790×
                    json::arr(shown.iter().map(|(h, m)| {
24800×
                        json::obj([
24810×
                            ("hash", json::s(&h.to_hex())),
24820×
                            ("id", json::s(&m.change_id.to_string())),
24830×
                            ("author", json::s(&author_name(&repo, m))),
24840×
                            ("time_ms", json::n(m.hlc.wall_ms)),
24850×
                            ("subject", json::s(subject_of(&m.message))),
24860×
                        ])
24870×
                    }))
2488
                ),
2489
            ])
2490
        );
24910×
        return Ok(0);
24920×
    }
24930×
    println!(
2494
        "{} {}{}{}",
24950×
        ui::ok(ui::glyph("●", "*")),
24960×
        ui::bookmark(&name),
24970×
        ui::sep(),
24980×
        ui::dim(plural(heads.len(), "head"))
2499
    );
25000×
    for (h, m) in &shown {
25010×
        print_head(&repo, "  ", h, m);
25020×
    }
25030×
    if heads.len() > 1 {
25040×
        println!(
25050×
            "  {}",
25060×
            ui::dim("None depends on another: the bookmark is all of them and their dependencies.")
25070×
        );
25080×
    }
25090×
    Ok(0)
25100×
}
2511
25125×
pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result<i32> {
25135×
    let repo = open()?;
25145×
    let remote_only = repo.remote_only_bookmarks()?;
25155×
    if as_json {
25165×
        let mut items: Vec<String> = repo
25175×
            .bookmarks()?
25185×
            .into_iter()
251913×
            .map(|b| {
252013×
                json::obj([
252113×
                    ("name", json::s(&b.name)),
252213×
                    ("heads", json::hashes(&b.heads)),
252313×
                    ("current", json::b(b.current)),
252413×
                    ("ahead", json::opt(b.ahead, json::n)),
252513×
                    ("behind", json::opt(b.behind, json::n)),
252613×
                    ("remote", json::opt(b.remote.as_deref(), json::s)),
252713×
                ])
252813×
            })
25295×
            .collect();
25305×
        if all {
25310×
            items.extend(remote_only.iter().map(|b| {
25320×
                json::obj([
25330×
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
25340×
                    ("heads", json::hashes(&b.heads)),
25350×
                    ("current", json::b(false)),
25360×
                    ("ahead", "null".into()),
25370×
                    ("behind", "null".into()),
25380×
                    ("remote", json::s(&b.remote)),
25390×
                ])
25400×
            }));
25415×
        }
25425×
        println!("{}", json::arr(items));
25435×
        return Ok(0);
25440×
    }
25450×
    for b in repo.bookmarks()? {
25460×
        let mark = if b.current {
25470×
            ui::ok(ui::glyph("●", "*"))
2548
        } else {
25490×
            ui::dim(ui::glyph("○", "o"))
2550
        };
25510×
        let mut tail = String::new();
25520×
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
25530×
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
25540×
        }
25550×
        if let Some(n) = b.behind.filter(|n| *n > 0) {
25560×
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
25570×
        }
2558
        // Which remote, when there is a choice (oxygen#83).
25590×
        if !tail.is_empty() && repo.config.remotes.len() > 1 {
25600×
            if let Some(r) = &b.remote {
25610×
                tail += &ui::dim(format!(" {r}"));
25620×
            }
25630×
        }
25640×
        let shown = heads_newest_first(&repo, &b.heads);
2565
        // The newest head's subject, so a busy bookmark shows its latest work.
25660×
        let head = match shown.first() {
25670×
            Some(_) if verbose => String::new(),
25680×
            Some((_, m)) if b.heads.len() > 1 => format!(
2569
                "{} {}",
25700×
                ui::dim("newest"),
25710×
                ui::subject(subject_of(&m.message))
2572
            ),
25730×
            Some((_, m)) => ui::subject(subject_of(&m.message)),
25740×
            None => ui::dim("(empty)"),
2575
        };
25760×
        let head = if head.is_empty() {
25770×
            head
2578
        } else {
25790×
            format!("  {head}")
2580
        };
25810×
        println!(
2582
            "{mark} {}{}{}{tail}{head}",
25830×
            ui::bookmark(&b.name),
25840×
            ui::sep(),
25850×
            ui::dim(plural(b.heads.len(), "head"))
2586
        );
25870×
        if verbose {
25880×
            for (h, m) in &shown {
25890×
                print_head(&repo, "    ", h, m);
25900×
            }
25910×
        }
2592
    }
25930×
    if remote_only.is_empty() {
25940×
        return Ok(0);
25950×
    }
25960×
    if !all {
25970×
        println!(
2598
            "{}",
25990×
            ui::dim(format!(
2600
                "  and {} only on a remote: oxy bookmark list --all",
26010×
                plural(remote_only.len(), "bookmark")
2602
            ))
2603
        );
26040×
        return Ok(0);
26050×
    }
26060×
    for b in &remote_only {
26070×
        println!(
26080×
            "{} {}{}{}",
26090×
            ui::dim(ui::glyph("◌", ".")),
26100×
            ui::dim(format!("{}/{}", b.remote, b.name)),
26110×
            ui::sep(),
26120×
            ui::dim(plural(b.heads.len(), "head"))
26130×
        );
26140×
    }
26150×
    println!(
2616
        "  {} {}",
26170×
        ui::note(),
26180×
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2619
    );
26200×
    Ok(0)
26215×
}
2622
26233×
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
26243×
    let mut repo = open()?;
26253×
    let from = repo.config.bookmark.clone();
26263×
    let (local, created_from) = repo.local_bookmark_for(name)?;
26273×
    if let Some(remote) = created_from {
26280×
        println!(
26290×
            "{} {} from {}",
26300×
            ui::done("Created"),
26310×
            ui::bookmark(&local),
26320×
            ui::dim(format!("{remote}/{local}"))
26330×
        );
26343×
    }
26353×
    let name = local.as_str();
2636
    // Only behind its remote: take the remote's state, so the switch does
2637
    // not check out a stale one (oxygen#74).
26383×
    if let Some(n) = repo.catch_up_bookmark(name)? {
26390×
        println!(
26400×
            "{} {} with {}: {} it lacked",
26410×
            ui::done("Caught up"),
26420×
            ui::bookmark(name),
26430×
            ui::dim(format!("{}/{name}", repo.default_remote())),
26440×
            plural(n, "change")
26450×
        );
26463×
    }
26473×
    let sp = ui::spinner(&format!("Switching to {name}…"));
26483×
    let (r, carried) = if carry {
26490×
        repo.bookmark_switch_carry(name)?
2650
    } else {
26513×
        (repo.bookmark_switch(name, discard)?, vec![])
2652
    };
26533×
    sp.done(&format!(
2654
        "{} to {}: {} written, {} removed{}",
26553×
        ui::done("Switched"),
26563×
        ui::bookmark(name),
26573×
        plural(r.written, "file"),
2658
        r.removed,
26593×
        if carried.is_empty() {
26603×
            String::new()
2661
        } else {
26620×
            format!("; carried {}", plural(carried.len(), "changed path"))
2663
        }
2664
    ));
26653×
    if r.conflicted {
26660×
        println!(
26670×
            "  {} {}",
26680×
            ui::caution(),
26690×
            ui::warn("this state has conflicts; see oxy status")
26700×
        );
26713×
    }
2672
    // Say when the new state leaves out work the old one had: a state is
2673
    // its heads and what they depend on, which can be far less than a Git
2674
    // user expects.
26753×
    if r.lacks > 0 {
26761×
        println!(
26771×
            "  {} {}",
26781×
            ui::note(),
26791×
            ui::dim(format!(
26801×
                "{name} lacks {} that {from} has",
26811×
                plural(r.lacks, "change")
26821×
            ))
26831×
        );
26842×
    }
26853×
    super::sync::subrepos_behind(&repo);
26863×
    where_now(&repo);
26873×
    Ok(0)
26883×
}
2689
26900×
pub fn merge(bookmark: &str) -> Result<i32> {
26910×
    let repo = open()?;
26920×
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
26930×
    let r = repo.merge(bookmark)?;
26940×
    if !r.changed {
26950×
        sp.done(&format!(
26960×
            "{} {}",
26970×
            ui::ok(ui::glyph("✔", "*")),
26980×
            ui::dim(format!(
26990×
                "{} already contains {bookmark}",
27000×
                repo.config.bookmark
27010×
            ))
27020×
        ));
27030×
        return Ok(0);
27040×
    }
27050×
    sp.done(&format!(
2706
        "{} {} into {}: now {}{}",
27070×
        ui::done("Merged"),
27080×
        ui::bookmark(bookmark),
27090×
        ui::bookmark(&repo.config.bookmark),
27100×
        plural(r.heads.len(), "head"),
27110×
        ui::dim(if r.checked_out {
27120×
            "; working copy updated"
2713
        } else {
27140×
            "; run oxy checkout to update the working copy"
2715
        })
2716
    ));
27170×
    let snap = repo.snapshot("oxy merge")?;
27180×
    if snap.base_snapshot.is_conflicted() {
27190×
        println!(
27200×
            "  {} {}",
27210×
            ui::caution(),
27220×
            ui::warn("the result has conflicts; see oxy status")
27230×
        );
27240×
    }
27250×
    where_now(&repo);
27260×
    Ok(0)
27270×
}
2728
27290×
pub fn squash(change: &str, into: &str) -> Result<i32> {
27300×
    let repo = open()?;
27310×
    let c = repo.resolve_change(change)?;
27320×
    let d = repo.resolve_change(into)?;
27330×
    let sp = ui::spinner("Squashing…");
27340×
    let h = repo.squash(&c, &d)?;
27350×
    let new = repo.store().get_change_meta(&h)?;
27360×
    sp.done(&format!(
27370×
        "{} into {} {}  {}",
27380×
        ui::done("Squashed"),
27390×
        ui::id(new.change_id.short(8)),
27400×
        ui::hash(format!("#{}", h.short(12))),
27410×
        ui::subject(subject_of(&new.message))
27420×
    ));
27430×
    Ok(0)
27440×
}
2745
27460×
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
27470×
    let repo = open()?;
27480×
    let c = repo.resolve_change(change)?;
27490×
    let mut heads = Vec::new();
27500×
    for o in onto {
27510×
        heads.extend(repo.resolve_heads(o)?);
2752
    }
27530×
    let sp = ui::spinner("Rebasing…");
27540×
    let h = match repo.rebase(&c, &heads) {
27550×
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
27560×
            let r = repo.rebase_into_working_copy(&c, &heads)?;
27570×
            sp.done(&format!(
27580×
                "{} {} into {}: now {}",
27590×
                ui::done("Merged"),
27600×
                onto.join(" "),
27610×
                ui::bookmark(&repo.config.bookmark),
27620×
                plural(r.heads.len(), "head"),
27630×
            ));
27640×
            if r.checked_out {
27650×
                println!(
27660×
                    "  {} {}",
27670×
                    ui::caution(),
27680×
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
27690×
                );
27700×
            } else {
27710×
                println!(
27720×
                    "  {} {}",
27730×
                    ui::caution(),
27740×
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
27750×
                );
27760×
            }
27770×
            where_now(&repo);
27780×
            return Ok(0);
2779
        }
27800×
        other => other?,
2781
    };
27820×
    let new = repo.store().get_change_meta(&h)?;
27830×
    sp.done(&format!(
27840×
        "{} {} {}  {}",
27850×
        ui::done("Rebased"),
27860×
        ui::id(new.change_id.short(8)),
27870×
        ui::hash(format!("#{}", h.short(12))),
27880×
        ui::dim(format!(
27890×
            "now depends on {}",
27900×
            plural(new.deps.len(), "change")
27910×
        ))
27920×
    ));
27930×
    where_now(&repo);
27940×
    Ok(0)
27950×
}