OXYGENHUB

Coverage / src/cli/workspace.rs 39.3%

970 of 2471 lines run, 95 of 349 functions · run #383 on main · run missed

1
//! Commands that act on the local repository and working copy.
2
3
use super::format::{
4
    author_name, deps_line, deps_of, plural, short_id, signature_line, signature_mark_of,
5
    subject_of, via, when,
6
};
7
use super::json;
8
use super::open;
9
use super::ui;
10
use anyhow::Result;
11
use oxy_core::objects::ChangeKind;
12
use oxy_core::repo::SignatureStatus;
13
use oxy_core::repo::{render_change, ChangeStatus, Repo};
14
use std::io::Write;
15
use std::path::PathBuf;
16
1712×
pub fn init(path: Option<PathBuf>, bare: bool, store: Option<&str>) -> Result<i32> {
1812×
    let path = path.unwrap_or(std::env::current_dir()?);
1912×
    let repo = Repo::init_new(&path, bare, store)?;
2012×
    println!(
21
        "{} {}oxy repository in {}",
2212×
        ui::done("Initialized"),
2312×
        if bare { "bare " } else { "" },
2412×
        ui::path(repo.root().display())
25
    );
2612×
    println!(
27
        "{}",
2812×
        ui::kv("bookmark", ui::bookmark(&repo.config.bookmark))
29
    );
3012×
    if let Some(url) = &repo.config.storage_url {
310×
        println!(
320×
            "{}",
330×
            ui::kv(
340×
                "store",
350×
                format!(
360×
                    "{url} (cache in {}, up to {} MiB)",
370×
                    ui::path(repo.root().join(".oxy/cache").display()),
380×
                    repo.config.storage_cache >> 20
390×
                )
400×
            )
410×
        );
4212×
    }
4312×
    println!(
44
        "{}",
4512×
        ui::kv(
4612×
            "author",
4712×
            format!(
48
                "{} <{}>",
4912×
                ui::author(&repo.config.author_name),
50
                repo.config.author_email
51
            )
52
        )
53
    );
5412×
    Ok(0)
5512×
}
56
572×
fn status_tag(s: ChangeStatus) -> &'static str {
582×
    match s {
591×
        ChangeStatus::Added => "A",
600×
        ChangeStatus::Modified => "M",
610×
        ChangeStatus::Removed => "D",
620×
        ChangeStatus::Renamed => "R",
631×
        ChangeStatus::ModeChanged => "X",
640×
        ChangeStatus::ConflictEdited => "C!",
650×
        ChangeStatus::Resolved => "V",
66
    }
672×
}
68
69
/// New untracked files left out of the snapshot for their size (oxygen#98):
70
/// named, with how to keep them out quietly or take them in.
7131×
fn print_skipped_large(repo: &Repo) {
7231×
    let skipped = repo.skipped_large();
7331×
    if skipped.is_empty() {
7431×
        return;
750×
    }
760×
    let size = |n: u64| {
770×
        if n >= 1 << 30 {
780×
            format!("{:.1} GiB", n as f64 / (1u64 << 30) as f64)
79
        } else {
800×
            format!("{:.0} MiB", n as f64 / (1u64 << 20) as f64)
81
        }
820×
    };
830×
    println!();
840×
    println!(
85
        "{} {}",
860×
        ui::section(ui::warn("Not tracked")),
870×
        ui::dim(format!("new files over {}", size(repo.config.max_new_file)))
88
    );
890×
    for (p, n) in &skipped {
900×
        println!("  {} {}  {}", ui::caution(), ui::path(p), ui::dim(size(*n)));
910×
    }
920×
    println!(
93
        "  {} {}",
940×
        ui::note(),
950×
        ui::dim(
96
            "to leave them out quietly, list them in .oxyignore; to track one, \
97
             raise snapshot.max-new-file-size (oxy config snapshot.max-new-file-size 2G)"
98
        )
99
    );
10031×
}
101
102
/// Name what a checkout removed from the working copy (oxygen#102): a
103
/// switch to a bookmark lacking files takes them off disk, which an
104
/// editor open on the tree notices before a person reading a count does.
1053×
fn print_removed(r: &oxy_core::repo::CheckoutReport) {
1063×
    if r.removed == 0 {
1072×
        return;
1081×
    }
1091×
    let more = r.removed.saturating_sub(r.removed_paths.len());
1101×
    let names = r.removed_paths.join(", ");
1111×
    let tail = if more > 0 {
1120×
        format!(" and {more} more")
113
    } else {
1141×
        String::new()
115
    };
1161×
    let lead = if r.removed >= 20 {
1170×
        ui::caution()
118
    } else {
1191×
        ui::note()
120
    };
1211×
    println!(
122
        "  {} {}",
123
        lead,
1241×
        ui::dim(format!(
125
            "removed from disk (the bookmark does not have them): {names}{tail}"
126
        ))
127
    );
1283×
}
129
130
/// Name the work a switch carried (oxygen#120): it is still on disk, as it
131
/// was, on the new bookmark.
1323×
fn print_carried(paths: &[String]) {
1333×
    if paths.is_empty() {
1343×
        return;
1350×
    }
1360×
    let shown: Vec<&str> = paths.iter().take(10).map(String::as_str).collect();
1370×
    let more = paths.len().saturating_sub(shown.len());
1380×
    println!(
139
        "  {} {}",
1400×
        ui::note(),
1410×
        ui::dim(format!(
142
            "carried, as they were: {}{}",
1430×
            shown.join(", "),
1440×
            if more > 0 {
1450×
                format!(" and {more} more")
146
            } else {
1470×
                String::new()
148
            }
149
        ))
150
    );
1513×
}
152
153
/// Folders holding a repository of their own, which oxy leaves out (oxygen#43):
154
/// named, with how to track them.
15531×
fn print_untracked_nested(repo: &Repo, nested: &[String]) {
15631×
    if nested.is_empty() {
15729×
        return;
1582×
    }
1592×
    println!();
1602×
    println!(
161
        "{} {}",
1622×
        ui::section(ui::warn("Not tracked")),
1632×
        ui::dim("folders holding a repository of their own")
164
    );
1652×
    for p in nested {
1662×
        let kind = if repo.root().join(p).join(".git").exists() {
1672×
            "Git"
168
        } else {
1690×
            "Oxygen"
170
        };
1712×
        println!(
172
            "  {} {}  {}",
1732×
            ui::caution(),
1742×
            ui::path(format!("{p}/")),
1752×
            ui::dim(format!("a nested {kind} repository"))
176
        );
177
    }
1782×
    println!(
179
        "  {} {}",
1802×
        ui::note(),
1812×
        ui::dim(
182
            "to track one's files, remove its .git (or .oxy); to keep it a repository of its own, \
183
             oxy submodule add URL PATH; to leave it out quietly, list it in .oxyignore"
184
        )
185
    );
18631×
}
187
188
/// The working copy's changed paths, or that it is clean.
1895×
fn print_statuses(statuses: &[oxy_core::repo::PathStatus]) {
1905×
    if statuses.is_empty() {
1913×
        println!(
192
            "  {} {}",
1933×
            ui::ok(ui::glyph("✔", "*")),
1943×
            ui::dim("nothing to commit, working copy clean")
195
        );
1963×
        return;
1972×
    }
1982×
    println!();
1992×
    for s in statuses {
2002×
        println!(
2012×
            "  {} {}",
2022×
            ui::status_mark(status_tag(s.status)),
2032×
            ui::path(&s.path)
2042×
        );
2052×
    }
2065×
}
207
208
/// Say when the working copy has fallen behind its own bookmark: a
209
/// "clean" status there hid a pull that left it on old code (oxygen#89).
2105×
fn print_behind(repo: &Repo) {
2115×
    if let Ok(Some(n)) = repo.working_copy_behind() {
2120×
        println!(
2130×
            "  {} {}",
2140×
            ui::caution(),
2150×
            ui::warn(format!(
2160×
                "the working copy is behind {}: it lacks {} the bookmark has; oxy checkout brings it up",
2170×
                repo.config.bookmark,
2180×
                plural(n, "change")
2190×
            ))
2200×
        );
2215×
    }
2225×
}
223
2248×
pub fn status(json: bool) -> Result<i32> {
2258×
    let repo = open()?;
226
    // Answered by the manifest alone, with no history to load (oxygen#35,
227
    // #41): a clean working copy, or one as the last snapshot left it.
2288×
    let known = if json {
2293×
        None
230
    } else {
2315×
        repo.status_by_manifest()?
232
    };
2338×
    if let Some(statuses) = known {
2343×
        let (_, wc) = repo.working_copy()?;
2353×
        let heads = repo.bookmark_heads()?;
2363×
        println!(
237
            "{} {}{}working copy {}{}{}",
2383×
            ui::dim("On"),
2393×
            ui::bookmark(&repo.config.bookmark),
2403×
            ui::sep(),
2413×
            ui::id(wc.change_id.short(8)),
2423×
            ui::sep(),
2433×
            ui::dim(plural(heads.len(), "head"))
244
        );
2453×
        print_behind(&repo);
2463×
        print_statuses(&statuses);
2473×
        print_untracked_nested(&repo, &repo.untracked_nested());
2483×
        print_skipped_large(&repo);
2493×
        return Ok(0);
2505×
    }
2515×
    let sp = ui::spinner("Snapshotting the working copy…");
2525×
    let snap = repo.snapshot_status("oxy status")?;
2535×
    let heads = {
2545×
        let _t = oxy_core::timing::phase("status: heads");
2555×
        repo.bookmark_heads()?
256
    };
2575×
    let _drop = oxy_core::timing::phase("status: print and drop");
2585×
    sp.clear();
2595×
    if json {
2603×
        println!("{}", repo.status_json(&snap)?);
2613×
        return Ok(if snap.base_snapshot.is_conflicted() {
2620×
            2
263
        } else {
2643×
            0
265
        });
2662×
    }
2672×
    println!(
268
        "{} {}{}working copy {}{}{}",
2692×
        ui::dim("On"),
2702×
        ui::bookmark(&repo.config.bookmark),
2712×
        ui::sep(),
2722×
        ui::id(snap.wc.change_id.short(8)),
2732×
        ui::sep(),
2742×
        ui::dim(plural(heads.len(), "head"))
275
    );
2762×
    print_behind(&repo);
2772×
    print_statuses(&snap.statuses);
2782×
    print_untracked_nested(&repo, &snap.untracked_nested);
2792×
    print_skipped_large(&repo);
2802×
    if !snap.base_snapshot.is_conflicted() {
2812×
        return Ok(0);
2820×
    }
2830×
    println!();
2840×
    println!(
285
        "{} {}",
2860×
        ui::section(ui::err("Conflicts")),
2870×
        ui::dim("edit the marked files, or the .oxy-conflict-N candidates, then commit")
288
    );
2890×
    for c in &snap.base_snapshot.tree.conflicts {
2900×
        println!("  {} tree: {c:?}", ui::err(ui::glyph("✱", "!")));
2910×
    }
2920×
    for (p, f) in &snap.base_snapshot.files {
2930×
        if f.is_conflicted() {
2940×
            let state = match snap
2950×
                .statuses
2960×
                .iter()
2970×
                .find(|s| s.path == *p)
2980×
                .map(|s| s.status)
299
            {
300
                Some(ChangeStatus::Resolved) => {
3010×
                    ui::ok(format!("{} resolved in working copy", ui::glyph("✔", "*")))
302
                }
303
                Some(ChangeStatus::ConflictEdited) => {
3040×
                    ui::warn(format!("{} markers remain", ui::glyph("‼", "!")))
305
                }
3060×
                _ => ui::err(format!("{} unresolved", ui::glyph("✱", "!"))),
307
            };
3080×
            println!("  {}  {state}", ui::path(p));
3090×
        }
310
    }
3110×
    Ok(2)
3128×
}
313
31426×
pub fn commit(
31526×
    message: &str,
31626×
    depends_on: &[String],
31726×
    paths: &[String],
31826×
    interactive: bool,
31926×
    hunks: &[usize],
32026×
) -> Result<i32> {
32126×
    let repo = open()?;
32226×
    let mut deps = Vec::new();
32326×
    for d in depends_on {
3240×
        deps.push(repo.resolve_change(d)?);
325
    }
32626×
    let selection = if !hunks.is_empty() {
3271×
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
32825×
    } else if interactive {
3290×
        let (_, hunks) = repo.hunks()?;
3300×
        if hunks.is_empty() {
3310×
            anyhow::bail!("nothing to commit: the working copy matches its base");
3320×
        }
3330×
        let hunks: Vec<_> = hunks
3340×
            .into_iter()
3350×
            .filter(|h| {
3360×
                paths.is_empty()
3370×
                    || paths.iter().any(|p| {
3380×
                        h.path == *p || h.path.starts_with(&format!("{}/", p.trim_end_matches('/')))
3390×
                    })
3400×
            })
3410×
            .collect();
3420×
        let mut chosen = Vec::new();
3430×
        let stdin = std::io::stdin();
3440×
        let mut take_rest = false;
3450×
        for (n, h) in hunks.iter().enumerate() {
3460×
            if take_rest {
3470×
                chosen.push(h.index);
3480×
                continue;
3490×
            }
3500×
            println!(
351
                "{} {} {}",
3520×
                ui::section(format!("hunk {} of {}", n + 1, hunks.len())),
3530×
                ui::path(&h.path),
3540×
                ui::dim(format!("(#{})", h.index))
355
            );
3560×
            for line in h.text.lines() {
3570×
                let styled = if line.starts_with('+') {
3580×
                    ui::ok(line)
3590×
                } else if line.starts_with('-') {
3600×
                    ui::err(line)
361
                } else {
3620×
                    ui::dim(line)
363
                };
3640×
                println!("  {styled}");
365
            }
366
            loop {
3670×
                print!(
368
                    "{} ",
3690×
                    ui::warn("Commit this hunk? [y]es [n]o [a]ll remaining [q]uit:")
370
                );
371
                use std::io::Write as _;
3720×
                std::io::stdout().flush()?;
3730×
                let mut answer = String::new();
3740×
                if stdin.read_line(&mut answer)? == 0 {
3750×
                    anyhow::bail!("aborted");
3760×
                }
3770×
                match answer.trim() {
3780×
                    "y" | "Y" => {
3790×
                        chosen.push(h.index);
3800×
                        break;
381
                    }
3820×
                    "n" | "N" | "" => break,
3830×
                    "a" | "A" => {
3840×
                        chosen.push(h.index);
3850×
                        take_rest = true;
3860×
                        break;
387
                    }
3880×
                    "q" | "Q" => anyhow::bail!("aborted; nothing committed"),
3890×
                    _ => continue,
390
                }
391
            }
392
        }
3930×
        if chosen.is_empty() {
3940×
            anyhow::bail!("no hunks chosen; nothing committed");
3950×
        }
3960×
        oxy_core::repo::Selection::Hunks(chosen)
39725×
    } else if paths.is_empty() {
39823×
        oxy_core::repo::Selection::All
399
    } else {
4002×
        oxy_core::repo::Selection::Paths(paths.to_vec())
401
    };
40226×
    let sp = ui::spinner("Committing…");
40326×
    let (h, partial) = repo.commit_selection_partial(message, &deps, &selection)?;
404
    // The metadata only: a first commit's change holds the whole tree.
40526×
    let meta = repo.store().get_change_meta(&h)?;
40626×
    sp.done(&format!(
40726×
        "{} {} {}  {}",
40826×
        ui::done("Committed"),
40926×
        ui::id(meta.change_id.short(8)),
41026×
        ui::hash(format!("#{}", h.short(12))),
41126×
        ui::subject(subject_of(message))
41226×
    ));
41326×
    print_untracked_nested(&repo, &repo.untracked_nested());
41426×
    print_skipped_large(&repo);
415
    // Only a commit that took part of the working copy leaves anything.
41626×
    if partial {
4172×
        let rest = repo.snapshot_status("oxy commit")?;
4182×
        if !rest.statuses.is_empty() {
4192×
            println!(
4202×
                "  {} {}",
4212×
                ui::note(),
4222×
                ui::dim(format!(
4232×
                    "{} left uncommitted",
4242×
                    plural(rest.statuses.len(), "path")
4252×
                ))
4262×
            );
4272×
        }
42824×
    }
42926×
    where_now(&repo);
43026×
    Ok(0)
43126×
}
432
4330×
pub fn blame(path: &str, json: bool) -> Result<i32> {
4340×
    let repo = open()?;
4350×
    let lines = repo.blame(path)?;
4360×
    if json {
4370×
        let items = lines.iter().map(|l| {
4380×
            format!(
439
                "{{\"line\":{},\"change_id\":{},\"hash\":{},\"index\":{},\"author\":{},\"when_ms\":{}}}",
440
                l.line,
4410×
                oxy_core::repo::json_str(&l.change_id.to_hex()),
4420×
                oxy_core::repo::json_str(&l.hash.to_hex()),
443
                l.index,
4440×
                oxy_core::repo::json_str(&l.author),
445
                l.when_ms
446
            )
4470×
        });
4480×
        println!("{}", oxy_core::repo::json_array(items));
4490×
        return Ok(0);
4500×
    }
4510×
    let width = lines
4520×
        .iter()
4530×
        .map(|l| l.author.chars().count())
4540×
        .max()
4550×
        .unwrap_or(0)
4560×
        .min(20);
4570×
    let digits = lines.len().to_string().len();
4580×
    let _t = oxy_core::timing::phase("blame: print");
459
    // Most lines share their change with many others: each change's id,
460
    // author and age are formatted once, and the lines go out through one
461
    // buffered lock on stdout.
4620×
    let mut prefix: std::collections::HashMap<oxy_core::hash::ChangeHash, String> =
4630×
        std::collections::HashMap::new();
4640×
    let bar = ui::dim(ui::glyph("│", "|"));
4650×
    let mut out = std::io::BufWriter::with_capacity(1 << 16, std::io::stdout().lock());
4660×
    for l in &lines {
4670×
        let p = prefix.entry(l.hash).or_insert_with(|| {
4680×
            let author: String = l.author.chars().take(20).collect();
4690×
            format!(
470
                "{} {} {}",
4710×
                ui::id(l.change_id.short(8)),
4720×
                ui::author(format!("{author:<width$}")),
4730×
                ui::dim(ui::ago(l.when_ms))
474
            )
4750×
        });
4760×
        let text = String::from_utf8_lossy(&l.text);
4770×
        if writeln!(
4780×
            out,
479
            "{p} {:>digits$}{bar} {}",
480
            l.line,
4810×
            text.trim_end_matches('\n')
482
        )
4830×
        .is_err()
484
        {
485
            // A closed pipe (blame | head): stop quietly.
4860×
            return Ok(0);
4870×
        }
488
    }
4890×
    let _ = out.flush();
4900×
    Ok(0)
4910×
}
492
4930×
fn bisect_report(repo: &Repo, step: &oxy_core::repo::BisectStep) -> Result<i32> {
494
    use oxy_core::repo::BisectStep::*;
4950×
    match step {
4960×
        NeedMarks { good, bad } => {
4970×
            println!(
498
                "{} {} {}",
4990×
                ui::note(),
5000×
                ui::dim(format!("{good} good, {bad} bad;")),
5010×
                ui::dim(if *good == 0 {
5020×
                    "mark a known-good change or bookmark: oxy bisect good CHANGE"
503
                } else {
5040×
                    "mark a known-bad change or bookmark: oxy bisect bad CHANGE"
505
                })
506
            );
5070×
            Ok(0)
508
        }
509
        Testing {
5100×
            heads,
5110×
            remaining,
5120×
            steps_left,
513
        } => {
5140×
            println!(
515
                "{} {} {}",
5160×
                ui::done("Testing"),
5170×
                ui::dim(format!(
518
                    "{} in the state under test;",
5190×
                    plural(heads.len(), "head")
520
                )),
5210×
                ui::dim(format!(
522
                    "{remaining} candidates left, about {steps_left} more steps"
523
                ))
524
            );
5250×
            println!(
526
                "  {} {}",
5270×
                ui::note(),
5280×
                ui::dim("run your test, then oxy bisect good | bad | skip")
529
            );
5300×
            Ok(0)
531
        }
5320×
        Found { culprit } => {
5330×
            let c = repo.store().get_change(culprit)?;
5340×
            println!(
535
                "{} {} {}  {}",
5360×
                ui::done("Found"),
5370×
                ui::id(short_id(&c)),
5380×
                ui::hash(format!("#{}", culprit.short(12))),
5390×
                ui::subject(subject_of(&c.message))
540
            );
5410×
            println!("  {} {}", ui::note(), ui::dim("the first change whose inclusion makes the state bad; oxy bisect reset to return"));
5420×
            Ok(0)
543
        }
5440×
        Inconclusive { candidates } => {
5450×
            println!(
546
                "{} {}",
5470×
                ui::caution(),
5480×
                ui::warn(format!(
549
                    "every remaining candidate was skipped ({}); oxy bisect reset to return",
5500×
                    plural(candidates.len(), "change")
551
                ))
552
            );
5530×
            Ok(1)
554
        }
555
    }
5560×
}
557
5580×
pub fn bisect_start() -> Result<i32> {
5590×
    let repo = open()?;
5600×
    repo.bisect_start()?;
5610×
    println!(
562
        "{} bisect; {}",
5630×
        ui::done("Started"),
5640×
        ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE")
565
    );
5660×
    Ok(0)
5670×
}
568
5690×
pub fn bisect_mark(good: Option<bool>, changes: &[String]) -> Result<i32> {
5700×
    let repo = open()?;
5710×
    let mut heads = Vec::new();
5720×
    for c in changes {
5730×
        heads.extend(repo.resolve_heads(c)?);
574
    }
5750×
    let step = repo.bisect_mark(good, &heads)?;
5760×
    bisect_report(&repo, &step)
5770×
}
578
5790×
pub fn bisect_run(command: &[String]) -> Result<i32> {
5800×
    let repo = open()?;
5810×
    let step = repo.bisect_run(command)?;
5820×
    bisect_report(&repo, &step)
5830×
}
584
5851×
pub fn bisect_status(as_json: bool) -> Result<i32> {
5861×
    let repo = open()?;
5871×
    if as_json {
588
        use oxy_core::repo::BisectStep::*;
5891×
        let v = match repo.bisect_status()? {
5901×
            None => "null".to_string(),
5910×
            Some(NeedMarks { good, bad }) => json::obj([
5920×
                ("state", json::s("need-marks")),
5930×
                ("good", json::n(good)),
5940×
                ("bad", json::n(bad)),
5950×
            ]),
596
            Some(Testing {
5970×
                heads,
5980×
                remaining,
5990×
                steps_left,
6000×
            }) => json::obj([
6010×
                ("state", json::s("testing")),
6020×
                ("heads", json::hashes(&heads)),
6030×
                ("remaining", json::n(remaining)),
6040×
                ("steps_left", json::n(steps_left)),
6050×
            ]),
6060×
            Some(Found { culprit }) => json::obj([
6070×
                ("state", json::s("found")),
6080×
                ("culprit", json::s(&culprit.to_hex())),
6090×
            ]),
6100×
            Some(Inconclusive { candidates }) => json::obj([
6110×
                ("state", json::s("inconclusive")),
6120×
                ("candidates", json::hashes(&candidates)),
6130×
            ]),
614
        };
6151×
        println!("{v}");
6161×
        return Ok(0);
6170×
    }
6180×
    match repo.bisect_status()? {
619
        None => {
6200×
            println!("{}", ui::dim("No bisect in progress."));
6210×
            Ok(0)
622
        }
6230×
        Some(step) => bisect_report(&repo, &step),
624
    }
6251×
}
626
6270×
pub fn bisect_reset() -> Result<i32> {
6280×
    let repo = open()?;
6290×
    repo.bisect_reset()?;
6300×
    println!("{} bisect; working copy restored", ui::done("Reset"));
6310×
    Ok(0)
6320×
}
633
634
/// The log: one entry per change, newest first, joined by a rail. The
635
/// default view is the subject and a metadata line; `verbose` adds the full
636
/// message, dependencies, and the authenticating key.
63714×
fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
63814×
    Ok(match repo.authenticate_change(h)? {
6399×
        SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]),
640
        SignatureStatus::Valid {
6415×
            key,
6425×
            name,
6435×
            email,
6445×
            sealed,
6455×
            revoked,
6465×
        } => json::obj([
6475×
            ("status", json::s(if sealed { "sealed" } else { "signed" })),
6485×
            ("key", json::s(&key.to_hex())),
6495×
            ("name", json::s(&name)),
6505×
            ("email", json::s(&email)),
6515×
            ("revoked", json::b(revoked)),
652
        ]),
6530×
        SignatureStatus::Invalid(why) => {
6540×
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
655
        }
656
    })
65714×
}
658
65918×
fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result<String> {
66018×
    let c = &e.change;
66118×
    Ok(json::obj([
66218×
        ("hash", json::s(&e.hash.to_hex())),
66318×
        ("change_id", json::s(&c.change_id.to_hex())),
66418×
        ("author", json::s(&author_name(repo, c))),
66518×
        ("author_key", json::s(&c.author.to_hex())),
666
        (
66718×
            "via",
66818×
            match via(
66918×
                repo,
67018×
                &repo.authenticate_change_known(&e.hash, Some(c))?,
67118×
                &c.author,
672
            ) {
6730×
                Some(v) => json::obj([
6740×
                    ("name", json::s(&v.name)),
6750×
                    ("email", json::s(&v.email)),
6760×
                    ("key", json::s(&v.key.to_hex())),
6770×
                    ("scope", json::opt(v.scope.as_deref(), json::s)),
6780×
                    ("expires_ms", json::opt(v.expires, json::n)),
6790×
                    ("revoked", json::b(v.revoked)),
6800×
                ]),
68118×
                None => "null".to_string(),
682
            },
683
        ),
68418×
        ("when_ms", json::n(c.hlc.wall_ms)),
68518×
        ("message", json::s(&c.message)),
68618×
        ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())),
68718×
        ("deps", json::hashes(&c.deps)),
68818×
        ("head", json::b(e.is_head)),
68918×
        ("working_copy", json::b(e.is_working_copy)),
690
        (
69118×
            "signature",
69218×
            if e.is_working_copy {
6934×
                "null".into()
694
            } else {
69514×
                signature_json(repo, &e.hash)?
696
            },
697
        ),
698
    ]))
69918×
}
700
701
/// `START,END:PATH` for `oxy log -L`.
7022×
fn parse_line_range(spec: &str) -> Result<(usize, usize, &str)> {
7032×
    let bad = || anyhow::anyhow!("-L {spec}: expected START,END:PATH, as 10,24:src/lib.rs");
7042×
    let (range, path) = spec.split_once(':').ok_or_else(bad)?;
7052×
    let (a, b) = range.split_once(',').ok_or_else(bad)?;
706
    Ok((
7071×
        a.trim().parse().map_err(|_| bad())?,
7081×
        b.trim().parse().map_err(|_| bad())?,
7091×
        path,
710
    ))
7112×
}
712
7138×
pub fn log(
7148×
    revset: Option<&str>,
7158×
    limit: Option<usize>,
7168×
    verbose: bool,
7178×
    path: Option<&str>,
7188×
    lines: Option<&str>,
7198×
    as_json: bool,
7208×
) -> Result<i32> {
7218×
    let repo = open()?;
722
    // Whether the working copy is clean and conflicted: from the manifest
723
    // when it proves the working copy clean, else from a snapshot.
724
    // The working copy as last recorded, without looking at the files (as
725
    // Git's log does not): whether its change holds edits, and whether its
726
    // base was conflicted. `oxy status` is what checks the disk.
7278×
    let conflicted = !repo.is_at_op() && repo.recorded_conflicted()?;
7288×
    let listing = oxy_core::timing::phase("log: entries");
7298×
    let entries = match (path, lines) {
7308×
        _ if revset.is_some() => repo.log_revset(revset.unwrap_or_default())?,
7312×
        (_, Some(spec)) => {
7322×
            let (first, last, p) = parse_line_range(spec)?;
7331×
            let (_, wc) = repo.working_copy()?;
7341×
            let base = repo.load_state_history(&wc.deps)?.maximal(&wc.deps);
7351×
            repo.line_history(&base, p, first, last)?
736
        }
7371×
        (Some(p), None) => repo.log_for_path(p)?,
7385×
        (None, None) => repo.log()?,
739
    };
7407×
    drop(listing);
7417×
    let _print = oxy_core::timing::phase("log: print");
7427×
    if as_json {
7436×
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
7446×
        let mut items = Vec::new();
74517×
        for e in entries.iter().take(shown) {
74617×
            items.push(log_entry_json(&repo, e)?);
747
        }
7486×
        println!(
749
            "{}",
7506×
            json::obj([
7516×
                ("bookmark", json::s(&repo.config.bookmark)),
7526×
                ("total", json::n(entries.len())),
7536×
                ("changes", json::arr(items))
7546×
            ])
755
        );
7566×
        return Ok(0);
7571×
    }
7581×
    let total = entries.len();
7591×
    let shown = limit.unwrap_or(total).min(total);
760
    // Lay out a little past what is shown, so edges into the cut are drawn.
7611×
    let window: Vec<(ChangeHash, Vec<ChangeHash>)> = entries
7621×
        .iter()
7631×
        .take((shown + MAX_EDGE).min(total))
7644×
        .map(|e| (e.hash, e.change.deps.clone()))
7651×
        .collect();
7661×
    let rows = oxy_core::lanes::graph(&window, MAX_EDGE);
767
    // Highlight the shortest prefix that names each change: against the
768
    // whole log, which is what `resolve_change` searches.
769
    let everything;
7701×
    let all = if path.is_some() || lines.is_some() || revset.is_some() {
7710×
        everything = repo.log()?;
7720×
        &everything
773
    } else {
7741×
        &entries
775
    };
7761×
    let prefixes = oxy_core::timing::phase("log: id prefixes");
7771×
    let id_prefix = id_prefixes(
7781×
        all.iter().map(|e| e.change.change_id.0).collect(),
7791×
        entries.iter().take(shown).map(|e| e.change.change_id.0),
780
    );
7811×
    drop(prefixes);
7821×
    let labels = reference_labels(&repo)?;
7834×
    for (e, row) in entries.iter().take(shown).zip(&rows) {
7844×
        let c = &e.change;
7854×
        let bullet = ui::log_bullet(
7864×
            e.is_working_copy,
7874×
            e.is_head,
7884×
            e.is_working_copy && conflicted,
789
        );
7904×
        let id = c.change_id.to_hex();
7914×
        let n = id_prefix.get(&c.change_id.0).copied().unwrap_or(8).min(8);
7924×
        let mut head = vec![format!("{}{}", ui::id(&id[..n]), ui::dim(&id[n..8]))];
7934×
        head.push(ui::author(author_name(&repo, c)));
7944×
        head.push(ui::dim(ui::ago(c.hlc.wall_ms)));
7954×
        if let Some(names) = labels.get(&e.hash) {
7962×
            head.push(names.join(" "));
7972×
        }
7984×
        if c.kind == ChangeKind::Resolution {
7990×
            head.push(ui::warn("resolution"));
8004×
        }
8014×
        if !e.is_working_copy {
8023×
            head.push(ui::hash(format!("#{}", e.hash.short(8))));
8033×
            let status = repo.authenticate_change_known(&e.hash, Some(c))?;
8043×
            if let Some(agent) = via(&repo, &status, &c.author) {
8050×
                head.push(ui::dim(format!("via {}", agent.name)));
8063×
            }
8073×
            head.push(signature_mark_of(&status));
8081×
        }
8094×
        println!("{}{}", node_line(row, &bullet), head.join(" "));
8104×
        let subject = if e.is_working_copy && c.message.is_empty() {
8111×
            let edited = repo
8121×
                .store()
8131×
                .get_change(&e.hash)
8141×
                .is_ok_and(|w| !w.tree_ops.is_empty() || !w.edits.is_empty());
8151×
            ui::dim(if edited {
8160×
                "(working copy, uncommitted changes)"
817
            } else {
8181×
                "(working copy)"
819
            })
8203×
        } else if c.message.trim().is_empty() {
8210×
            ui::dim("(no description)")
822
        } else {
8233×
            subject_of(&c.message).to_string()
824
        };
8254×
        println!("{}{subject}", below_line(row));
8264×
        if verbose {
8270×
            let rail = continuation(row);
8280×
            if !e.is_working_copy {
8290×
                println!(
830
                    "{rail}{}",
8310×
                    ui::dim(format!(
832
                        "{} {}",
8330×
                        when(c.hlc.wall_ms),
8340×
                        signature_line(&repo, &e.hash)?
835
                    ))
836
                );
8370×
            }
8380×
            if !c.deps.is_empty() {
8390×
                println!(
8400×
                    "{rail}{} {}",
8410×
                    ui::dim(ui::glyph("↳", "->")),
8420×
                    ui::dim(deps_of(&c.deps))
8430×
                );
8440×
            }
8450×
            let body: Vec<&str> = c
8460×
                .message
8470×
                .lines()
8480×
                .skip(1)
8490×
                .skip_while(|l| l.trim().is_empty())
8500×
                .collect();
8510×
            for line in body {
8520×
                println!("{rail}  {line}");
8530×
            }
8544×
        }
855
    }
8561×
    if shown < total {
8570×
        if let Some(last) = rows.get(shown.saturating_sub(1)) {
8580×
            let cut: String = last
8590×
                .below
8600×
                .iter()
8610×
                .map(|c| match c {
8620×
                    Cell::Blank | Cell::Elided | Cell::JoinRight => "  ",
8630×
                    _ => "~ ",
8640×
                })
8650×
                .collect();
8660×
            if cut.trim().is_empty() {
8670×
                println!("{}", ui::dim("~"));
8680×
            } else {
8690×
                println!("{}", ui::dim(cut.trim_end()));
8700×
            }
8710×
        }
8720×
        println!(
873
            "{}",
8740×
            ui::dim(format!(
875
                "{} {} more; pass -n to see them",
8760×
                ui::glyph("…", "..."),
8770×
                total - shown
878
            ))
879
        );
8801×
    }
8811×
    Ok(0)
8828×
}
883
884
/// Rows a drawn edge may span in `oxy log`; a longer one is elided (`~`).
885
const MAX_EDGE: usize = 12;
886
887
use oxy_core::hash::ChangeHash;
888
use oxy_core::lanes::{Cell, GraphRow};
889
890
/// A graph cell, two columns wide.
8916×
fn cell(c: Cell) -> &'static str {
8926×
    match c {
8931×
        Cell::Blank => "  ",
8943×
        Cell::Line => ui::glyph("│ ", "| "),
8950×
        Cell::Elided => "~ ",
8961×
        Cell::JoinLeft => ui::glyph("├─", "|-"),
8970×
        Cell::JoinPass => ui::glyph("──", "--"),
8980×
        Cell::JoinCross => ui::glyph("┼─", "+-"),
8991×
        Cell::JoinRight => ui::glyph("╯ ", "' "),
900
    }
9016×
}
902
903
/// The graph part of a change's own line, its bullet in its column.
9044×
fn node_line(row: &GraphRow, bullet: &str) -> String {
9054×
    let width = row
9064×
        .passing
9074×
        .iter()
9084×
        .copied()
9094×
        .max()
9104×
        .unwrap_or(0)
9114×
        .max(row.column)
9124×
        + 1;
9134×
    let mut out = String::new();
9145×
    for c in 0..width {
9155×
        if c == row.column {
9164×
            out.push_str(bullet);
9174×
            out.push(' ');
9184×
        } else if row.passing.contains(&c) {
9191×
            out.push_str(&ui::dim(cell(Cell::Line)));
9201×
        } else {
9210×
            out.push_str("  ");
9220×
        }
923
    }
9244×
    out.push(' ');
9254×
    out
9264×
}
927
928
/// The graph part of the line under a change: lanes carrying on, a join,
929
/// or `~` for an elided edge.
9304×
fn below_line(row: &GraphRow) -> String {
9315×
    let g: String = row.below.iter().map(|c| cell(*c)).collect();
9324×
    format!("{} ", ui::dim(g))
9334×
}
934
935
/// The graph part of any further line of a change (`-v`).
9360×
fn continuation(row: &GraphRow) -> String {
9370×
    let g: String = row
9380×
        .below
9390×
        .iter()
9400×
        .map(|c| match c {
9410×
            Cell::Line | Cell::JoinLeft | Cell::JoinCross => cell(Cell::Line),
9420×
            _ => "  ",
9430×
        })
9440×
        .collect();
9450×
    format!("{} ", ui::dim(g))
9460×
}
947
948
/// For each hex ID, the length of its shortest prefix no other ID shares.
949
/// The shortest prefix, in hex digits, that names each of `wanted` among
950
/// `all`: worked out for the few shown rather than for the whole history.
9512×
fn id_prefixes(
9522×
    mut all: Vec<[u8; 16]>,
9532×
    wanted: impl Iterator<Item = [u8; 16]>,
9542×
) -> std::collections::HashMap<[u8; 16], usize> {
9552×
    all.sort_unstable();
9562×
    all.dedup();
957
    // Hex digits two ids share at the start.
9584004×
    let common = |a: &[u8; 16], b: &[u8; 16]| {
95910720×
        let bytes = a.iter().zip(b).take_while(|(x, y)| x == y).count();
9604004×
        match (a.get(bytes), b.get(bytes)) {
9614004×
            (Some(x), Some(y)) if x >> 4 == y >> 4 => 2 * bytes + 1,
9621856×
            _ => 2 * bytes,
963
        }
9644004×
    };
9652×
    let mut out = std::collections::HashMap::new();
9662004×
    for id in wanted {
9672004×
        let Ok(i) = all.binary_search(&id) else {
9680×
            continue;
969
        };
9702004×
        let before = i.checked_sub(1).map_or(0, |j| common(&all[j], &id));
9712004×
        let after = all.get(i + 1).map_or(0, |n| common(&id, n));
9722004×
        out.insert(id, before.max(after) + 1);
973
    }
9742×
    out
9752×
}
976
9771×
fn unique_prefixes(ids: impl Iterator<Item = String>) -> std::collections::HashMap<String, usize> {
9781×
    let mut v: Vec<String> = ids.collect();
9791×
    v.sort();
9801×
    v.dedup();
98119576×
    let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
9821×
    let mut out = std::collections::HashMap::with_capacity(v.len());
9832000×
    for i in 0..v.len() {
9842000×
        let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 };
9852000×
        let after = if i + 1 < v.len() {
9861999×
            common(&v[i], &v[i + 1])
987
        } else {
9881×
            0
989
        };
9902000×
        out.insert(v[i].clone(), before.max(after) + 1);
991
    }
9921×
    out
9931×
}
994
995
/// Bookmark, remote bookmark and tag names to show beside the changes they
996
/// point at. A name is shown on each head of its state; one with more than
997
/// three heads names too much of the log to help, so it is left out (oxy
998
/// bookmark list shows it). A remote bookmark at the same state as the
999
/// local one of that name is not repeated.
10001×
fn reference_labels(repo: &Repo) -> Result<std::collections::HashMap<ChangeHash, Vec<String>>> {
1001
    const MAX_HEADS: usize = 3;
10021×
    let view = repo.view()?;
10031×
    let mut out: std::collections::HashMap<ChangeHash, Vec<String>> = Default::default();
10041×
    let mut add = |heads: Vec<ChangeHash>, label: String| {
10051×
        if heads.len() <= MAX_HEADS {
10062×
            for h in heads {
10072×
                out.entry(h).or_default().push(label.clone());
10082×
            }
10090×
        }
10101×
    };
10111×
    for (name, st) in &view.bookmarks {
10121×
        add(repo.store().get_state(st)?.heads, ui::bookmark(name));
1013
    }
10141×
    for (remote, bookmarks) in &view.remotes {
10150×
        for (name, st) in bookmarks {
10160×
            if view.bookmarks.get(name) == Some(st) {
10170×
                continue;
10180×
            }
10190×
            add(
10200×
                repo.store().get_state(st)?.heads,
10210×
                ui::dim(format!("{remote}/{name}")),
1022
            );
1023
        }
1024
    }
10251×
    for t in repo.tags()? {
10260×
        add(t.heads.clone(), ui::warn(&t.name));
10270×
    }
10281×
    Ok(out)
10291×
}
1030
10311×
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
10321×
    let repo = open()?;
10331×
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
10341×
    if as_json {
10351×
        let files = repo.diff_files(hash.as_ref())?;
10363×
        let items = files.iter().map(|f| {
10373×
            json::obj([
10383×
                ("path", json::s(&f.path)),
10393×
                ("kind", json::s(&f.kind)),
10403×
                ("from", json::opt(f.from.as_deref(), json::s)),
1041
                (
10423×
                    "hunks",
10433×
                    json::arr(f.hunks.iter().map(|h| {
10443×
                        json::obj([
10453×
                            ("base_line", json::n(h.base_line)),
1046
                            (
10473×
                                "added",
10483×
                                json::arr(
10493×
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
1050
                                ),
1051
                            ),
1052
                            (
10533×
                                "removed",
10543×
                                json::arr(h.removed.iter().map(|(n, l)| {
10550×
                                    json::obj([
10560×
                                        ("line", json::n(*n)),
10570×
                                        ("text", json::s(&String::from_utf8_lossy(l))),
10580×
                                    ])
10590×
                                })),
1060
                            ),
1061
                        ])
10623×
                    })),
1063
                ),
1064
            ])
10653×
        });
10661×
        println!(
1067
            "{}",
10681×
            json::obj([
10691×
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
10701×
                ("files", json::arr(items))
1071
            ])
1072
        );
10731×
        return Ok(0);
10740×
    }
10750×
    match hash {
10760×
        Some(h) => {
10770×
            let c = repo.store().get_change(&h)?;
10780×
            let (base, snapshot) = repo.change_base(&c)?;
10790×
            print!("{}", render_change(&c, &base, &snapshot));
1080
        }
1081
        None => {
1082
            // Nothing changed: nothing to show, and no base to load.
10830×
            let Some((wc, base, snapshot)) = repo.working_copy_with_base_unless_unchanged()? else {
10840×
                return Ok(0);
1085
            };
10860×
            let text = {
10870×
                let _t = oxy_core::timing::phase("diff: render the change");
10880×
                render_change(&wc, &base, &snapshot)
1089
            };
10900×
            print!("{text}");
1091
            // The process ends here: freeing the base's tree and graphs
1092
            // one by one would only cost time (about 27 ms on Linux).
10930×
            std::mem::forget((wc, base, snapshot));
1094
        }
1095
    }
10960×
    Ok(0)
10971×
}
1098
10992×
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
11002×
    let repo = open()?;
11012×
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
11022×
    let bytes = match repo.file_at(path, heads.as_deref()) {
11032×
        Ok(b) => b,
1104
        // -r CHANGE reads that change's dependency closure, not the
1105
        // bookmark it is on: say so when the bookmark has the file
1106
        // (oxygen#76).
11070×
        Err(e) => match change {
11080×
            Some(c)
11090×
                if !repo.view()?.bookmarks.contains_key(c)
11100×
                    && repo.tag_heads(c)?.is_none()
11110×
                    && repo.file_at(path, None).is_ok() =>
1112
            {
11130×
                anyhow::bail!(
1114
                    "{path} is not in {c}'s dependency closure (the change and what it \
1115
                     depends on); it is on the bookmark: try -r {}, or --at-op OP for the \
1116
                     state at an operation",
1117
                    repo.config.bookmark
1118
                )
1119
            }
11200×
            _ => return Err(e.into()),
1121
        },
1122
    };
1123
    use std::io::Write as _;
11242×
    std::io::stdout().write_all(&bytes)?;
11252×
    Ok(0)
11262×
}
1127
11281×
pub fn root(as_json: bool) -> Result<i32> {
11291×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
11300×
        if as_json {
11310×
            println!("null");
11320×
        }
11330×
        return Ok(1);
1134
    };
11351×
    if as_json {
11361×
        println!(
11371×
            "{}",
11381×
            json::obj([
11391×
                ("root", json::s(&repo.root().to_string_lossy())),
11401×
                ("workspace", json::s(&repo.workspace().to_hex())),
11411×
                ("bookmark", json::s(&repo.config.bookmark))
11421×
            ])
11431×
        );
11441×
    } else {
11450×
        println!("{}", repo.root().display());
11460×
    }
11471×
    Ok(0)
11481×
}
1149
11501×
pub fn version(as_json: bool) -> Result<i32> {
11511×
    if as_json {
11521×
        println!(
11531×
            "{}",
11541×
            json::obj([
11551×
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
11561×
                // What was built: a release's or install's `oxy describe`,
11571×
                // a Flow build's heads, or "local build".
11581×
                ("build", json::s(env!("OXY_BUILD_ID"))),
11591×
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
11601×
                ("format", json::n(2))
11611×
            ])
11621×
        );
11631×
    } else {
11640×
        println!(
11650×
            "oxy {} (repository format 2, protocol {})",
11660×
            env!("OXY_VERSION_LONG"),
11670×
            oxy_core::protocol::PROTOCOL_VERSION
11680×
        );
11690×
    }
11701×
    Ok(0)
11711×
}
1172
11732×
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
11742×
    let repo = open()?;
11752×
    if paths.is_empty() && hunks.is_empty() {
11760×
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
11772×
    }
11782×
    let mut n = 0;
11792×
    if !hunks.is_empty() {
11801×
        n += repo.discard_hunks(hunks)?;
11811×
    }
11822×
    if !paths.is_empty() {
11831×
        n += repo.discard(paths)?;
11841×
    }
11852×
    println!(
1186
        "{} {} restored to the working copy's base",
11872×
        ui::done("Discarded"),
11882×
        plural(n, "path")
1189
    );
11902×
    Ok(0)
11912×
}
1192
11932×
pub fn hunks(as_json: bool) -> Result<i32> {
11942×
    let repo = open()?;
11952×
    let (_, hunks) = repo.hunks()?;
11962×
    if as_json {
11972×
        println!(
1198
            "{}",
11995×
            json::arr(hunks.iter().map(|h| json::obj([
12005×
                ("index", json::n(h.index)),
12015×
                ("path", json::s(&h.path)),
12025×
                ("text", json::s(&h.text))
12035×
            ])))
1204
        );
12052×
        return Ok(0);
12060×
    }
12070×
    if hunks.is_empty() {
12080×
        println!(
12090×
            "{}",
12100×
            ui::dim("No hunks: the working copy matches its base.")
12110×
        );
12120×
    }
12130×
    for h in &hunks {
12140×
        println!(
1215
            "{} {}",
12160×
            ui::section(format!("hunk {}", h.index)),
12170×
            ui::path(&h.path)
1218
        );
12190×
        for line in h.text.lines() {
12200×
            let styled = if line.starts_with('+') {
12210×
                ui::ok(line)
12220×
            } else if line.starts_with('-') {
12230×
                ui::err(line)
1224
            } else {
12250×
                ui::dim(line)
1226
            };
12270×
            println!("  {styled}");
1228
        }
1229
    }
12300×
    Ok(0)
12312×
}
1232
12333×
pub fn show(change: Option<&str>, revset: Option<&str>, stat: bool, as_json: bool) -> Result<i32> {
12343×
    let repo = open()?;
12353×
    repo.snapshot_status("oxy show")?;
12363×
    let Some(r) = revset else {
12373×
        let h = repo.resolve_change(change.unwrap_or("@"))?;
12383×
        return show_one(&repo, h, as_json, false, stat);
1239
    };
1240
    // Several changes: a JSON array, or the changes one after another.
12410×
    let hashes = repo.revset(r)?.hashes;
12420×
    if as_json {
12430×
        print!("[");
12440×
        for (i, h) in hashes.iter().enumerate() {
12450×
            if i > 0 {
12460×
                print!(",");
12470×
            }
12480×
            show_one(&repo, *h, true, true, stat)?;
1249
        }
12500×
        println!("]");
12510×
        return Ok(0);
12520×
    }
12530×
    if hashes.is_empty() {
12540×
        println!("{}", ui::dim(format!("No change matches {r:?}.")));
12550×
        return Ok(0);
12560×
    }
12570×
    for (i, h) in hashes.iter().enumerate() {
12580×
        if i > 0 {
12590×
            println!();
12600×
        }
12610×
        show_one(&repo, *h, false, false, stat)?;
1262
    }
12630×
    Ok(0)
12643×
}
1265
1266
/// Lines added and removed in one file's diff.
12672×
fn counts(f: &oxy_core::repo::FileDiff) -> (usize, usize) {
12682×
    f.hunks
12692×
        .iter()
12702×
        .fold((0, 0), |(a, r), h| (a + h.added.len(), r + h.removed.len()))
12712×
}
1272
1273
/// What `--stat` prints (oxygen#119): each file the change touched, its
1274
/// lines added and removed, then the total.
12751×
fn print_stat(files: &[oxy_core::repo::FileDiff]) {
12761×
    let width = files
12771×
        .iter()
12781×
        .map(|f| f.path.chars().count())
12791×
        .max()
12801×
        .unwrap_or(0)
12811×
        .min(60);
12821×
    let (mut added, mut removed) = (0, 0);
12831×
    for f in files {
12841×
        let (a, r) = counts(f);
12851×
        added += a;
12861×
        removed += r;
12871×
        let path = match &f.from {
12880×
            Some(from) => format!("{from} → {}", f.path),
12891×
            None => f.path.clone(),
1290
        };
12911×
        println!(
1292
            " {path:<width$}  {} {}  {}",
12931×
            ui::ok(format!("{:>6}", format!("+{a}"))),
12941×
            ui::err(format!("{:>6}", format!("-{r}"))),
12951×
            ui::dim(&f.kind)
1296
        );
1297
    }
12981×
    println!(
1299
        " {}",
13001×
        ui::dim(format!(
1301
            "{} changed, {added} added, {removed} removed",
13021×
            plural(files.len(), "file")
1303
        ))
1304
    );
13051×
}
1306
1307
/// One change, as `oxy show` prints it; `inline` JSON goes without its
1308
/// newline, for an array. `stat` lists the files instead of the diff.
13093×
fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool, stat: bool) -> Result<i32> {
13103×
    let c = repo.store().get_change(&h)?;
13113×
    if as_json {
13121×
        let files = repo.diff_files(Some(&h))?;
13131×
        let heads = repo.bookmark_heads()?;
13141×
        let entry = oxy_core::repo::LogEntry {
13151×
            hash: h,
13161×
            change: oxy_core::state::ChangeMeta::of(&c),
13171×
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
13181×
            is_head: heads.contains(&h),
13191×
        };
13201×
        let mut body = log_entry_json(repo, &entry)?;
13211×
        body.pop();
13221×
        body.push_str(&format!(
1323
            ",{}:{}}}",
13241×
            json::s("files"),
13251×
            json::arr(files.iter().map(|f| {
13261×
                let (a, r) = counts(f);
13271×
                json::obj([
13281×
                    ("path", json::s(&f.path)),
13291×
                    ("kind", json::s(&f.kind)),
13301×
                    ("from", json::opt(f.from.as_deref(), json::s)),
13311×
                    ("added", a.to_string()),
13321×
                    ("removed", r.to_string()),
13331×
                ])
13341×
            }))
1335
        ));
13361×
        if inline {
13370×
            print!("{body}");
13381×
        } else {
13391×
            println!("{body}");
13401×
        }
13411×
        return Ok(0);
13422×
    }
13432×
    println!(
1344
        "{} {} {}",
13452×
        ui::section("change"),
13462×
        ui::id(short_id(&c)),
13472×
        ui::hash(format!("#{h}"))
1348
    );
13492×
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1350
    // Fetched but not pulled (oxygen#56): say where it is.
13512×
    if let Some(at) = repo.remote_only_location(&h)? {
13520×
        println!(
13530×
            "{}",
13540×
            ui::kv(
13550×
                "only in",
13560×
                ui::warn(format!(
13570×
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
13580×
                ))
13590×
            )
13600×
        );
13612×
    }
13622×
    let meta = oxy_core::state::ChangeMeta::of(&c);
13632×
    let status = repo.authenticate_change_known(&h, Some(&meta))?;
13642×
    println!("{}", ui::kv("author", ui::author(author_name(repo, &meta))));
13652×
    if let Some(agent) = via(repo, &status, &meta.author) {
13660×
        println!("{}", ui::kv("via", agent.line()));
13672×
    }
13682×
    println!(
1369
        "{}",
13702×
        ui::kv(
13712×
            "date",
13722×
            format!(
1373
                "{} {}",
13742×
                when(c.hlc.wall_ms),
13752×
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1376
            )
1377
        )
1378
    );
13792×
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
13802×
    println!("{}", ui::kv("sig", signature_line(repo, &h)?));
13812×
    println!();
13825×
    for line in (if c.message.is_empty() {
13830×
        "(no description)"
1384
    } else {
13852×
        &c.message
1386
    })
13872×
    .lines()
13885×
    {
13895×
        println!("    {line}");
13905×
    }
13912×
    println!();
13922×
    if stat {
13931×
        print_stat(&repo.diff_files(Some(&h))?);
1394
    } else {
13951×
        print!("{}", repo.describe_change(&h)?);
1396
    }
13972×
    Ok(0)
13983×
}
1399
14000×
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
14010×
    let repo = open()?;
1402
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1403
    // BRANCH` is: checking its files out under another bookmark's name
1404
    // made the next commit move the wrong bookmark (oxygen#60).
14050×
    if let [name] = changes {
14060×
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
14070×
            drop(repo);
14080×
            return bookmark_switch(name, discard, carry);
14090×
        }
14100×
    }
14110×
    let heads = if changes.is_empty() {
14120×
        repo.bookmark_heads()?
1413
    } else {
14140×
        let mut heads = Vec::new();
14150×
        for c in changes {
14160×
            heads.extend(repo.resolve_heads(c)?);
1417
        }
14180×
        heads
1419
    };
14200×
    let spec = if changes.is_empty() {
14210×
        repo.config.bookmark.clone()
1422
    } else {
14230×
        changes.join(" ")
1424
    };
14250×
    let sp = ui::spinner(&format!("Checking out {spec}…"));
14260×
    let command = format!("oxy checkout {spec}");
14270×
    let (r, carried) = if carry {
14280×
        repo.checkout_carry(&heads, &spec, &command)?
1429
    } else {
14300×
        (repo.checkout(&heads, discard, &command)?, vec![])
1431
    };
14320×
    sp.done(&format!(
1433
        "{} on {}: {} written, {} removed{}",
14340×
        ui::done("Working copy"),
14350×
        ui::bookmark(&spec),
14360×
        plural(r.written, "file"),
1437
        r.removed,
14380×
        if carried.is_empty() {
14390×
            String::new()
1440
        } else {
14410×
            format!("; carried {}", plural(carried.len(), "changed path"))
1442
        }
1443
    ));
14440×
    print_removed(&r);
14450×
    for n in &r.notes {
14460×
        println!("  {} {n}", ui::note());
14470×
    }
14480×
    if r.conflicted {
14490×
        println!(
14500×
            "  {} {}",
14510×
            ui::caution(),
14520×
            ui::warn("this state has conflicts; see oxy status")
14530×
        );
14540×
    }
14550×
    where_now(&repo);
14560×
    Ok(0)
14570×
}
1458
14591×
pub fn resolve(paths: &[String], as_json: bool) -> Result<i32> {
14601×
    let repo = open()?;
14611×
    let mut snap = repo.snapshot("oxy resolve")?;
14621×
    if !paths.is_empty() {
1463
        // A replace conflict has no markers to edit out: the user says which
1464
        // content wins (oxygen#140, spec §9.3), and the snapshot builds it.
14650×
        let paths: Vec<String> = paths
14660×
            .iter()
14670×
            .map(|p| p.trim_start_matches("./").trim_end_matches('/').to_string())
14680×
            .collect();
14690×
        repo.choose_resolutions(&snap.base_snapshot, &paths)?;
14700×
        snap = repo.snapshot("oxy resolve")?;
14711×
    }
14721×
    if as_json {
14731×
        println!("{}", repo.status_json(&snap)?);
14741×
        return Ok(if snap.base_snapshot.is_conflicted() {
14750×
            2
1476
        } else {
14771×
            0
1478
        });
14790×
    }
14800×
    if !snap.base_snapshot.is_conflicted() {
14810×
        println!("The working copy's base has no conflicts.");
14820×
        return Ok(0);
14830×
    }
14840×
    let mut remaining = 0;
14850×
    for (p, f) in &snap.base_snapshot.files {
14860×
        if !f.is_conflicted() {
14870×
            continue;
14880×
        }
14890×
        match snap
14900×
            .statuses
14910×
            .iter()
14920×
            .find(|s| s.path == *p)
14930×
            .map(|s| s.status)
1494
        {
14950×
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
14960×
            Some(ChangeStatus::ConflictEdited) => {
14970×
                remaining += 1;
14980×
                println!("markers    {p}");
14990×
            }
15000×
            _ => {
15010×
                remaining += 1;
15020×
                println!("unresolved {p}");
15030×
            }
1504
        }
1505
    }
15060×
    for c in &snap.base_snapshot.tree.conflicts {
15070×
        remaining += 1;
15080×
        println!("tree       {c:?}");
15090×
    }
15100×
    if remaining == 0 {
15110×
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
15120×
        Ok(0)
1513
    } else {
15140×
        Ok(2)
1515
    }
15161×
}
1517
15180×
pub fn undo() -> Result<i32> {
15190×
    let repo = open()?;
15200×
    let u = repo.undo()?;
15210×
    println!("{} {}", ui::done("Undone:"), u.command);
15220×
    for c in &u.changes {
15230×
        println!("  {} {}", ui::note(), change_words(&repo, c));
15240×
    }
15250×
    if u.others_kept > 0 {
15260×
        let s = if u.others_kept == 1 { "" } else { "s" };
15270×
        println!(
1528
            "  {} {}",
15290×
            ui::note(),
15300×
            ui::dim(format!(
1531
                "{} newer operation{s} from other workspaces left as they are",
1532
                u.others_kept
1533
            ))
1534
        );
15350×
    }
15360×
    for (bookmark, remote) in &u.pushed {
15370×
        println!(
15380×
            "  {} {}",
15390×
            ui::caution(),
15400×
            ui::warn(format!(
15410×
                "{remote}/{bookmark} already has what this undid: undone here only; the next push of {bookmark} needs --force to take it back there"
15420×
            ))
15430×
        );
15440×
    }
15450×
    where_now(&repo);
15460×
    Ok(0)
15470×
}
1548
15491×
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
15501×
    let repo = open()?;
15511×
    let ops = repo.op_log()?;
1552
    // What each operation changed, against the one before it.
155311×
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
155411×
        match ops.get(i + 1) {
155510×
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
15561×
            None => Ok(vec![]),
1557
        }
155811×
    };
15591×
    if as_json {
15601×
        let mut items = Vec::new();
156111×
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
156211×
            let summary: Vec<String> = changes_of(i)?
156311×
                .iter()
156411×
                .map(|c| change_words(&repo, c))
156511×
                .collect();
156611×
            items.push(json::obj([
156711×
                ("id", json::s(&r.to_hex())),
156811×
                ("when_ms", json::n(op.hlc.wall_ms)),
156911×
                ("command", json::s(&op.command)),
157011×
                ("snapshot", json::b(op.is_snapshot())),
157111×
                ("current", json::b(i == 0)),
157211×
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1573
            ]));
1574
        }
15751×
        println!("{}", json::arr(items));
15761×
        return Ok(0);
15770×
    }
15780×
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
15790×
    let id = |r: &oxy_core::hash::ObjectRef| {
15800×
        let hex = r.to_hex();
15810×
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
15820×
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
15830×
    };
15840×
    let rail = ui::dim(ui::glyph("│", "|"));
15850×
    let (mut i, mut shown) = (0, 0);
15860×
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
15870×
        let (r, op) = &ops[i];
15880×
        let bullet = if i == 0 {
15890×
            ui::ok(ui::glyph("@", "@"))
1590
        } else {
15910×
            ui::dim(ui::glyph("○", "o"))
1592
        };
1593
        // A run of snapshots folds into one entry.
15940×
        let mut run = 1;
15950×
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
15960×
            run += 1;
15970×
        }
15980×
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
15990×
        if op.is_snapshot() {
16000×
            let span = if run > 1 {
16010×
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1602
            } else {
16030×
                String::new()
1604
            };
16050×
            println!(
1606
                "{bullet}  {}{} {when}",
16070×
                id(r),
16080×
                if span.is_empty() {
16090×
                    String::new()
1610
                } else {
16110×
                    format!(" {span}")
1612
                }
1613
            );
16140×
            println!(
1615
                "{rail}  {}",
16160×
                ui::dim(if run == 1 {
16170×
                    "working-copy snapshot".to_string()
1618
                } else {
16190×
                    format!("{run} working-copy snapshots")
1620
                })
1621
            );
1622
        } else {
16230×
            println!("{bullet}  {} {when}", id(r));
16240×
            let words: Vec<String> = changes_of(i)?
16250×
                .iter()
16260×
                .map(|c| change_words(&repo, c))
16270×
                .collect();
16280×
            let summary = if words.is_empty() {
16290×
                if i + 1 == ops.len() {
16300×
                    "created the repository".to_string()
1631
                } else {
16320×
                    "no bookmark or working-copy change".to_string()
1633
                }
1634
            } else {
16350×
                words.join("; ")
1636
            };
16370×
            println!(
1638
                "{rail}  {}",
16390×
                if i == 0 {
16400×
                    ui::subject(&summary)
1641
                } else {
16420×
                    summary
1643
                }
1644
            );
16450×
            let cmd = op.command.lines().next().unwrap_or("");
16460×
            let cmd: String = cmd.chars().take(100).collect();
16470×
            println!("{rail}  {}", ui::dim(cmd));
1648
        }
16490×
        i += run;
16500×
        shown += 1;
1651
    }
16520×
    if i < ops.len() {
16530×
        println!(
16540×
            "{}",
16550×
            ui::dim(format!(
16560×
                "{} {} older; pass -n to see more",
16570×
                ui::glyph("…", "..."),
16580×
                plural(ops.len() - i, "operation")
16590×
            ))
16600×
        );
16610×
    }
16620×
    Ok(0)
16631×
}
1664
1665
/// One change an operation made, in words.
166611×
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1667
    use oxy_core::repo::ViewChange::*;
16682×
    match c {
16690×
        BookmarkCreated { name, heads } => {
16700×
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1671
        }
16720×
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
16732×
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
16741×
        BookmarkMoved { name, from, to } => format!(
1675
            "{name}: {from} {} {}",
16761×
            ui::glyph("→", "->"),
16771×
            plural(*to, "head")
1678
        ),
16791×
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
16800×
        TagCreated { name } => format!("tagged {name}"),
16810×
        TagDeleted { name } => format!("removed tag {name}"),
16820×
        Policy => "trust policy changed".to_string(),
16838×
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
16848×
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
16850×
            Err(_) => "working copy moved".to_string(),
1686
        },
1687
    }
168811×
}
1689
16900×
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
16910×
    let repo = open()?;
16920×
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
16930×
    let r = repo.op_restore(op, discard)?;
16940×
    sp.done(&format!(
16950×
        "{} to operation {} {}",
16960×
        ui::done("Restored"),
16970×
        ui::hash(r.op.short(12)),
16980×
        ui::dim(r.command.lines().next().unwrap_or(""))
16990×
    ));
17000×
    println!(
1701
        "  {} {}",
17020×
        ui::note(),
17030×
        ui::dim(format!(
1704
            "{} written, {} removed; oxy undo goes back again",
17050×
            plural(r.checkout.written, "file"),
1706
            r.checkout.removed
1707
        ))
1708
    );
17090×
    where_now(&repo);
17100×
    Ok(0)
17110×
}
1712
17130×
pub fn op_revert(op: &str) -> Result<i32> {
17140×
    let repo = open()?;
17150×
    let r = repo.op_revert(op)?;
17160×
    let view = repo.view()?;
17170×
    let names: Vec<String> = r
17180×
        .reverted
17190×
        .iter()
17200×
        .map(|n| {
17210×
            if view.bookmarks.contains_key(n) {
17220×
                ui::bookmark(n)
1723
            } else {
17240×
                format!("{} (removed)", ui::bookmark(n))
1725
            }
17260×
        })
17270×
        .collect();
17280×
    println!(
1729
        "{} operation {} {}",
17300×
        ui::done("Reverted"),
17310×
        ui::hash(r.op.short(12)),
17320×
        ui::dim(r.command.lines().next().unwrap_or(""))
1733
    );
17340×
    println!(
1735
        "  {} {}",
17360×
        ui::note(),
17370×
        ui::dim(format!("as before it: {}", names.join(", ")))
1738
    );
17390×
    if !r.kept.is_empty() {
17400×
        println!(
17410×
            "  {} {}",
17420×
            ui::caution(),
17430×
            ui::warn(format!(
17440×
                "left as they are, having moved again since: {}",
17450×
                r.kept.join(", ")
17460×
            ))
17470×
        );
17480×
    }
17490×
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
17500×
        println!(
17510×
            "  {} {}",
17520×
            ui::note(),
17530×
            ui::dim("the working copy has work of its own: oxy checkout to move it")
17540×
        );
17550×
    }
17560×
    where_now(&repo);
17570×
    Ok(0)
17580×
}
1759
1760
/// Where the working copy and bookmark are now, after a command moved
1761
/// them (as jj says "Working copy now at").
176231×
pub fn where_now(repo: &Repo) {
176331×
    let Ok((_, wc)) = repo.working_copy() else {
17640×
        return;
1765
    };
176631×
    let heads = repo.bookmark_heads().unwrap_or_default();
176731×
    let newest = heads
176831×
        .iter()
176943×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
177031×
        .max_by_key(|(m, _)| m.hlc);
177131×
    println!(
1772
        "  {} {}",
177331×
        ui::dim(format!("{:<13}", "Working copy")),
177431×
        ui::id(wc.change_id.short(8))
1775
    );
177631×
    let tail = match newest {
177731×
        Some((m, _)) => format!(
1778
            ", newest {} {}",
177931×
            ui::id(m.change_id.short(8)),
178031×
            subject_of(&m.message)
1781
        ),
17820×
        None => String::new(),
1783
    };
178431×
    println!(
1785
        "  {} {}: {}{tail}",
178631×
        ui::dim(format!("{:<13}", "Bookmark")),
178731×
        ui::bookmark(&repo.config.bookmark),
178831×
        plural(heads.len(), "head")
1789
    );
179031×
}
1791
17920×
pub fn gc(now: bool, expire_snapshots: bool) -> Result<i32> {
17930×
    let mut repo = open()?;
17940×
    if expire_snapshots {
17950×
        repo.config.snapshot_retention_days = 0;
17960×
    }
17970×
    let sp = ui::spinner("Packing and pruning…");
17980×
    let r = repo.gc_with(now, &mut |phase| sp.set(&format!("{phase}…")))?;
17990×
    sp.clear();
18000×
    if r.packed.objects > 0 {
18010×
        println!(
18020×
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
18030×
            plural(r.packed.objects, "object"),
18040×
            r.packed.raw_bytes,
18050×
            r.packed.packed_bytes,
18060×
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
18070×
        );
18080×
    }
18090×
    println!(
1810
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
18110×
        plural(r.reachable, "object"),
18120×
        plural(r.pruned.objects, "unreachable object"),
1813
        r.pruned.bytes,
18140×
        if r.pruned.deferred > 0 {
18150×
            format!(
1816
                "; {} deferred by the grace period (use --now)",
18170×
                plural(r.pruned.deferred, "object")
1818
            )
1819
        } else {
18200×
            String::new()
1821
        },
18220×
        if r.merged_packs > 0 {
18230×
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1824
        } else {
18250×
            String::new()
1826
        },
18270×
        plural(repo.store().pack_count(), "pack")
1828
    );
1829
    // What earlier repacks replaced stays an hour for readers still using
1830
    // it (oxygenhub#249); a collection after that deletes it.
18310×
    let kept = if r.retired.kept > 0 {
18320×
        format!(
1833
            "{} retired less than an hour ago kept for readers",
18340×
            plural(r.retired.kept, "file")
1835
        )
1836
    } else {
18370×
        String::new()
1838
    };
18390×
    if r.retired.packs + r.retired.loose > 0 {
18400×
        println!(
1841
            "Deleted {} and {} retired by earlier repacks{}.",
18420×
            plural(r.retired.packs, "pack"),
18430×
            plural(r.retired.loose, "loose object"),
18440×
            if kept.is_empty() {
18450×
                String::new()
1846
            } else {
18470×
                format!("; {kept}")
1848
            }
1849
        );
18500×
    } else if !kept.is_empty() {
18510×
        println!("{kept}.");
18520×
    }
18530×
    Ok(0)
18540×
}
1855
1856
/// `oxy gc --remote NAME`: fold a store remote's bundles into one.
18572×
pub fn gc_remote(name: &str, now: bool) -> Result<i32> {
18582×
    let repo = open()?;
18592×
    let sp = ui::spinner(&format!("Folding {name}'s bundles…"));
18602×
    let r = repo.gc_remote(name, now)?;
18611×
    sp.clear();
18621×
    if r.merged > 0 {
18631×
        println!(
18641×
            "{} {} into one of {} bytes ({})",
18651×
            ui::done("Folded"),
18661×
            plural(r.merged, "bundle"),
18671×
            r.bundle_bytes,
18681×
            plural(r.changes, "change")
18691×
        );
18701×
    } else {
18710×
        println!(
18720×
            "{} {}",
18730×
            ui::note(),
18740×
            ui::dim("nothing to fold: one bundle holds everything")
18750×
        );
18760×
    }
18771×
    println!(
1878
        "  {} {}",
18791×
        ui::note(),
18801×
        ui::dim(format!(
1881
            "removed {}{}",
18821×
            plural(r.deleted, "superseded bundle"),
18831×
            if r.deferred > 0 {
18840×
                format!(
1885
                    "; {} kept for readers that may still fetch them (use --now)",
18860×
                    plural(r.deferred, "bundle")
1887
                )
1888
            } else {
18891×
                String::new()
1890
            }
1891
        ))
1892
    );
18931×
    Ok(0)
18942×
}
1895
1896
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
18970×
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1898
    use oxy_core::repo::Health;
18990×
    let repo = open()?;
19000×
    let sp = ui::spinner(if offline {
19010×
        "Checking…"
1902
    } else {
19030×
        "Checking, and contacting remotes…"
1904
    });
19050×
    let r = repo.doctor(!offline);
19060×
    sp.clear();
19070×
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
19080×
    let word = |h: Health| match h {
19090×
        Health::Ok => "ok",
19100×
        Health::Warn => "warning",
19110×
        Health::Fail => "fail",
19120×
    };
19130×
    if as_json {
19140×
        let checks: Vec<String> = r
19150×
            .checks
19160×
            .iter()
19170×
            .map(|c| {
19180×
                json::obj([
19190×
                    ("area", json::s(&c.area)),
19200×
                    ("health", json::s(word(c.health))),
19210×
                    ("message", json::s(&c.message)),
19220×
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
19230×
                ])
19240×
            })
19250×
            .collect();
19260×
        println!(
1927
            "{}",
19280×
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1929
        );
19300×
        return Ok(code);
19310×
    }
19320×
    let mut last = "";
19330×
    for c in &r.checks {
19340×
        if c.area != last {
19350×
            println!("{}", ui::section(&c.area));
19360×
            last = &c.area;
19370×
        }
19380×
        let mark = match c.health {
19390×
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
19400×
            Health::Warn => ui::caution(),
19410×
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1942
        };
19430×
        println!("  {mark} {}", c.message);
19440×
        if let Some(h) = &c.hint {
19450×
            println!("    {} {}", ui::dim("→"), ui::dim(h));
19460×
        }
1947
    }
19480×
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
19490×
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
19500×
    if fails + warns == 0 {
19510×
        println!("{}", ui::done("Everything looks right."));
19520×
    } else {
19530×
        println!(
1954
            "{} {}, {}.",
19550×
            if fails > 0 {
19560×
                ui::err(ui::glyph("✖", "x"))
1957
            } else {
19580×
                ui::caution()
1959
            },
19600×
            plural(fails, "problem"),
19610×
            plural(warns, "warning")
1962
        );
1963
    }
19640×
    Ok(code)
19650×
}
1966
1967
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
19680×
pub fn fsck(as_json: bool) -> Result<i32> {
1969
    use oxy_core::repo::Severity;
19700×
    let repo = open()?;
19710×
    let sp = ui::spinner("Checking every object…");
19720×
    let r = repo.fsck()?;
19730×
    sp.clear();
19740×
    let code = if r.errors() > 0 { 1 } else { 0 };
19750×
    if as_json {
19760×
        let problems: Vec<String> = r
19770×
            .problems
19780×
            .iter()
19790×
            .map(|p| {
19800×
                json::obj([
1981
                    (
1982
                        "severity",
19830×
                        json::s(match p.severity {
19840×
                            Severity::Error => "error",
19850×
                            Severity::Warning => "warning",
1986
                        }),
1987
                    ),
1988
                    (
19890×
                        "object",
19900×
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1991
                    ),
19920×
                    ("what", json::s(&p.what)),
1993
                ])
19940×
            })
19950×
            .collect();
19960×
        println!(
1997
            "{}",
19980×
            json::obj([
19990×
                ("ok", json::b(code == 0)),
20000×
                ("objects", json::n(r.objects)),
20010×
                ("ops", json::n(r.ops)),
20020×
                ("changes", json::n(r.changes)),
20030×
                ("signed", json::n(r.signed)),
20040×
                ("unsigned", json::n(r.unsigned)),
20050×
                ("checkpoints", json::n(r.checkpoints)),
20060×
                ("attestations", json::n(r.attestations)),
20070×
                ("errors", json::n(r.errors())),
20080×
                ("warnings", json::n(r.warnings())),
20090×
                ("problems", json::arr(problems)),
20100×
            ])
2011
        );
20120×
        return Ok(code);
20130×
    }
20140×
    println!(
2015
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
20160×
        plural(r.objects, "object"),
20170×
        plural(r.ops, "operation"),
20180×
        plural(r.changes, "change"),
2019
        r.signed,
2020
        r.unsigned,
20210×
        plural(r.checkpoints, "checkpoint"),
20220×
        plural(r.attestations, "attestation"),
2023
    );
20240×
    for p in &r.problems {
20250×
        let obj = p
20260×
            .object
20270×
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
20280×
            .unwrap_or_default();
20290×
        match p.severity {
20300×
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
20310×
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
2032
        }
2033
    }
20340×
    if r.problems.is_empty() {
20350×
        println!("{}", ui::done("No problems found."));
20360×
    } else if code == 0 {
20370×
        println!(
20380×
            "{}",
20390×
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
20400×
        );
20410×
    } else {
20420×
        println!(
20430×
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
20440×
            ui::err(ui::glyph("✖", "x")),
20450×
            plural(r.errors(), "error"),
20460×
            plural(r.warnings(), "warning")
20470×
        );
20480×
    }
20490×
    Ok(code)
20500×
}
2051
2052
/// The head the working copy sits on, for commands that default to it. With
2053
/// several heads beneath the working copy, the most recently made one is
2054
/// chosen and announced.
20550×
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
20560×
    let snap = repo.snapshot_status("oxy")?;
20570×
    let base = snap.base.maximal(&snap.wc.deps);
20580×
    match base.as_slice() {
20590×
        [] => anyhow::bail!("the working copy sits on no change yet"),
20600×
        [h] => Ok(*h),
20610×
        many => {
20620×
            let latest = many
20630×
                .iter()
20640×
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
20650×
                .copied()
20660×
                .unwrap();
20670×
            let c = repo.store().get_change(&latest)?;
20680×
            println!(
2069
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
20700×
                short_id(&c),
20710×
                latest.short(12),
20720×
                many.len()
2073
            );
20740×
            Ok(latest)
2075
        }
2076
    }
20770×
}
2078
2079
/// `oxy describe` without -m: the working copy's name for a build.
20804×
pub fn describe_name(as_json: bool) -> Result<i32> {
20814×
    let repo = open()?;
20824×
    let d = repo.describe_working_copy()?;
20834×
    if as_json {
20843×
        println!(
2085
            "{}",
20863×
            json::obj([
20873×
                ("describe", json::s(&d.line())),
20883×
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
20893×
                ("distance", json::n(d.distance)),
20903×
                ("bookmark", json::s(&d.bookmark)),
20913×
                ("change", json::s(&d.change.to_hex())),
20923×
                ("hash", json::s(&d.hash.to_hex())),
20933×
                ("dirty", json::b(d.dirty)),
2094
            ])
2095
        );
20961×
    } else {
20971×
        println!("{}", d.line());
20981×
    }
20994×
    Ok(0)
21004×
}
2101
21020×
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
21030×
    let repo = open()?;
21040×
    let h = match change {
21050×
        Some(c) => repo.resolve_change(c)?,
21060×
        None => current_head(&repo)?,
2107
    };
21080×
    let new = repo.describe(&h, message)?;
21090×
    let c = repo.store().get_change_meta(&new)?;
21100×
    println!(
2111
        "{} {} {}  {}",
21120×
        ui::done("Described"),
21130×
        ui::id(c.change_id.short(8)),
21140×
        ui::hash(format!("#{}", new.short(12))),
21150×
        ui::subject(subject_of(message))
2116
    );
21170×
    Ok(0)
21180×
}
2119
21200×
pub fn amend(message: Option<&str>, into: Option<&str>, paths: &[String]) -> Result<i32> {
21210×
    let repo = open()?;
21220×
    let before = repo.view()?;
21230×
    let new = match into {
21240×
        Some(spec) => {
21250×
            let target = repo.resolve_change(spec)?;
21260×
            repo.amend_into(&target, message)?
2127
        }
21280×
        None if !paths.is_empty() => repo.amend_paths(message, paths)?,
21290×
        None => repo.amend(message)?,
2130
    };
21310×
    let c = repo.store().get_change_meta(&new)?;
21320×
    println!(
2133
        "{} {} {}  {}",
21340×
        ui::done("Amended"),
21350×
        ui::id(c.change_id.short(8)),
21360×
        ui::hash(format!("#{}", new.short(12))),
21370×
        ui::subject(subject_of(&c.message))
2138
    );
2139
    // Rewriting what a remote already has means the next push replaces it
2140
    // there (oxygen#99): say so now, not when the push is refused.
21410×
    let bookmark = repo.config.bookmark.clone();
21420×
    let (had, has) = (
21430×
        repo.heads_of(&before, &bookmark)?,
21440×
        repo.heads_of(&repo.view()?, &bookmark)?,
2145
    );
21460×
    for (remote, bookmarks) in &before.remotes {
21470×
        let Some(st) = bookmarks.get(&bookmark) else {
21480×
            continue;
2149
        };
21500×
        let theirs = repo.store().get_state(st)?.heads;
21510×
        if theirs.iter().any(|h| had.contains(h) && !has.contains(h)) {
21520×
            println!(
21530×
                "  {} {}",
21540×
                ui::caution(),
21550×
                ui::warn(format!(
21560×
                    "{remote}/{bookmark} has the change as it was: the next push of {bookmark} needs --force to replace it"
21570×
                ))
21580×
            );
21590×
        }
2160
    }
21610×
    where_now(&repo);
21620×
    Ok(0)
21630×
}
2164
21650×
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
21660×
    let repo = open()?;
21670×
    let Some(r) = revset else {
21680×
        let h = repo.resolve_change(change.unwrap_or_default())?;
21690×
        abandon_one(&repo, h)?;
21700×
        where_now(&repo);
21710×
        return Ok(0);
2172
    };
2173
    // A revset: say what it selects, refuse an empty set, ask above a few.
21740×
    let selected = repo.revset(r)?;
21750×
    let wc = repo.working_copy().ok().map(|(h, _)| h);
21760×
    let hashes: Vec<ChangeHash> = selected
21770×
        .hashes
21780×
        .iter()
21790×
        .copied()
21800×
        .filter(|h| Some(*h) != wc)
21810×
        .collect();
21820×
    if hashes.is_empty() {
21830×
        anyhow::bail!("{r:?} selects no change to abandon");
21840×
    }
21850×
    println!(
2186
        "{} {} selects {}:",
21870×
        ui::section("abandon"),
21880×
        ui::id(r),
21890×
        plural(hashes.len(), "change")
2190
    );
21910×
    for h in &hashes {
21920×
        if let Some(m) = selected.metas.get(h) {
21930×
            println!(
21940×
                "  {} {}  {}",
21950×
                ui::id(m.change_id.short(8)),
21960×
                ui::hash(format!("#{}", h.short(12))),
21970×
                subject_of(&m.message)
21980×
            );
21990×
        }
2200
    }
2201
    const ASK_ABOVE: usize = 5;
22020×
    if hashes.len() > ASK_ABOVE && !yes {
22030×
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
22040×
    }
2205
    // Newest first: abandoning a change rewrites what depends on it, so a
2206
    // later member is found again by its ChangeId.
22070×
    let mut done = 0;
22080×
    for h in &hashes {
22090×
        let Some(m) = selected.metas.get(h) else {
22100×
            continue;
2211
        };
22120×
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
22130×
            Ok(h) => h,
22140×
            Err(_) => continue,
2215
        };
22160×
        abandon_one(&repo, now)?;
22170×
        done += 1;
2218
    }
22190×
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
22200×
    where_now(&repo);
22210×
    Ok(0)
22220×
}
2223
22240×
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
22250×
    let c = repo.store().get_change_meta(&h)?;
22260×
    let notes = repo.abandon(&h)?;
22270×
    println!(
2228
        "{} {} {}  {}",
22290×
        ui::done("Abandoned"),
22300×
        ui::id(c.change_id.short(8)),
22310×
        ui::hash(format!("#{}", h.short(12))),
22320×
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
2233
    );
22340×
    for n in notes {
22350×
        println!("  {} {n}", ui::note());
22360×
    }
22370×
    Ok(())
22380×
}
2239
22400×
pub fn checkpoint() -> Result<i32> {
22410×
    let repo = open()?;
22420×
    let sp = ui::spinner("Writing checkpoint…");
22430×
    let (r, changes, bytes) = repo.checkpoint()?;
22440×
    sp.done(&format!(
22450×
        "{} {} of {} ({} bytes) for {}",
22460×
        ui::done("Checkpoint"),
22470×
        ui::hash(format!("#{}", r.short(12))),
22480×
        plural(changes, "change"),
22490×
        bytes,
22500×
        ui::id(&repo.config.bookmark)
22510×
    ));
22520×
    Ok(0)
22530×
}
2254
2255
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
22560×
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
22570×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
22580×
        return Ok(1);
2259
    };
22600×
    let info = repo.quick_status()?;
22610×
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
22620×
        oxy_core::repo::GLYPH_PROMPT_FORMAT
2263
    } else {
22640×
        format
2265
    };
22660×
    let line = match color {
22670×
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
22680×
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
22690×
        Some(_) => info.format_colored(fmt, ("", "")),
22700×
        None => info.format(fmt),
2271
    };
22720×
    println!("{line}");
22730×
    Ok(0)
22740×
}
2275
22760×
pub fn sparse(paths: &[String]) -> Result<i32> {
22770×
    let mut repo = open()?;
22780×
    if paths.is_empty() {
22790×
        if repo.config.sparse_paths.is_empty() {
22800×
            println!("No sparse filter: the whole tree is materialized.");
22810×
        } else {
22820×
            println!("{}", ui::heading("Sparse filter"));
22830×
            for p in &repo.config.sparse_paths {
22840×
                println!("  {}", ui::path(p));
22850×
            }
2286
        }
22870×
        return Ok(0);
22880×
    }
22890×
    let snap = repo.snapshot("oxy sparse")?;
22900×
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
22910×
        anyhow::bail!(
2292
            "the working copy has changes; commit them before changing the sparse filter"
2293
        );
22940×
    }
22950×
    repo.config.set("filter.paths", &paths.join(","))?;
22960×
    repo.save_config()?;
22970×
    let heads = repo.bookmark_heads()?;
22980×
    let sp = ui::spinner("Re-checking out with the new filter…");
22990×
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
23000×
    sp.done(&format!(
23010×
        "{} {}: {} written, {} removed",
23020×
        ui::done("Sparse filter set to"),
23030×
        ui::path(paths.join(",")),
23040×
        plural(r.written, "file"),
23050×
        r.removed
23060×
    ));
23070×
    Ok(0)
23080×
}
2309
23102×
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
23112×
    let repo = open()?;
23122×
    repo.snapshot_status("oxy tag")?;
23132×
    let heads = if changes.is_empty() {
23142×
        repo.bookmark_heads()?
2315
    } else {
23160×
        let mut heads = Vec::new();
23170×
        for c in changes {
23180×
            heads.extend(repo.resolve_heads(c)?);
2319
        }
23200×
        heads
2321
    };
23222×
    let t = repo.tag_create(name, &heads, message)?;
23232×
    println!(
2324
        "{} {} {} {} ({}){}",
23252×
        ui::done("Tagged"),
23262×
        ui::bookmark(&t.name),
23272×
        ui::dim(ui::glyph("→", "->")),
23282×
        ui::hash(format!("#{}", t.state.short(12))),
23292×
        plural(t.heads.len(), "head"),
23302×
        t.signer
23312×
            .map(|s| format!(", signed by {s}"))
23322×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2333
    );
23342×
    Ok(0)
23352×
}
2336
23370×
pub fn tag_delete(name: &str, reason: &str) -> Result<i32> {
23380×
    let repo = open()?;
23390×
    let t = repo.tag_delete(name, reason)?;
23400×
    println!(
2341
        "{} {} {} {}{}",
23420×
        ui::done("Withdrew"),
23430×
        ui::bookmark(&t.name),
23440×
        ui::dim(ui::glyph("→", "->")),
23450×
        ui::hash(format!("#{}", t.state.short(12))),
23460×
        t.signer
23470×
            .map(|s| format!(", signed by {s}"))
23480×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2349
    );
23500×
    println!(
2351
        "  {} {}",
23520×
        ui::note(),
23530×
        ui::dim("`oxy push` sends the withdrawal to a remote that has the tag; the name is not used again")
2354
    );
23550×
    Ok(0)
23560×
}
2357
23581×
pub fn tag_list(as_json: bool) -> Result<i32> {
23591×
    let repo = open()?;
23601×
    let tags = repo.tags()?;
23611×
    if as_json {
23621×
        println!(
2363
            "{}",
23641×
            json::arr(tags.iter().map(|t| {
23651×
                json::obj([
23661×
                    ("name", json::s(&t.name)),
23671×
                    ("state", json::s(&t.state.to_hex())),
23681×
                    ("heads", json::hashes(&t.heads)),
23691×
                    ("message", json::s(&t.message)),
2370
                    (
23711×
                        "signer",
23721×
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2373
                    ),
2374
                ])
23751×
            }))
2376
        );
23771×
        return Ok(0);
23780×
    }
23790×
    if tags.is_empty() {
23800×
        println!("{}", ui::dim("No tags."));
23810×
    }
23820×
    for t in tags {
23830×
        println!(
2384
            "{} {} {}{}{}{}",
23850×
            ui::ok(ui::glyph("⚑", "#")),
23860×
            ui::bookmark(&t.name),
2387
            // The heads, as `oxy log` shows changes, not the state hash.
23880×
            ui::hash(
23890×
                t.heads
23900×
                    .iter()
23910×
                    .map(|h| format!("#{}", h.short(12)))
23920×
                    .collect::<Vec<_>>()
23930×
                    .join(" ")
2394
            ),
23950×
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
23960×
            if t.message.is_empty() {
23970×
                String::new()
2398
            } else {
23990×
                format!("  {}", ui::subject(subject_of(&t.message)))
2400
            },
24010×
            t.signer
24020×
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
24030×
                .unwrap_or_default()
2404
        );
2405
    }
24060×
    Ok(0)
24071×
}
2408
2409
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2410
/// and workspace add take as "be on this bookmark" (oxygen#60).
24110×
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
24120×
    Ok(repo.view()?.bookmarks.contains_key(name)
24130×
        || repo
24140×
            .remote_only_bookmarks()?
24150×
            .iter()
24160×
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
24170×
}
2418
24190×
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
24200×
    let repo = open()?;
2421
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2422
    // this workspace's bookmark with that one's files.
24230×
    if let [name] = changes {
24240×
        if names_bookmark(&repo, name)? {
24250×
            let (local, _) = repo.local_bookmark_for(name)?;
24260×
            let heads = repo.resolve_heads(&local)?;
24270×
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
24280×
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
24290×
            sp.done(&format!(
24300×
                "{} {} (workspace {}) on {}",
24310×
                ui::done("Workspace created at"),
24320×
                ui::path(ws.root().display()),
24330×
                ui::id(ws.workspace().short(8)),
24340×
                ui::bookmark(&local)
24350×
            ));
24360×
            return Ok(0);
24370×
        }
24380×
    }
24390×
    let heads = if changes.is_empty() {
24400×
        None
2441
    } else {
24420×
        let mut heads = Vec::new();
24430×
        for c in changes {
24440×
            heads.extend(repo.resolve_heads(c)?);
2445
        }
24460×
        Some(heads)
2447
    };
24480×
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
24490×
    let ws = repo.workspace_add(path, heads.as_deref())?;
24500×
    sp.done(&format!(
24510×
        "{} {} (workspace {})",
24520×
        ui::done("Workspace created at"),
24530×
        ui::path(ws.root().display()),
24540×
        ui::id(ws.workspace().short(8))
24550×
    ));
24560×
    Ok(0)
24570×
}
2458
24591×
pub fn workspace_list(as_json: bool) -> Result<i32> {
24601×
    let repo = open()?;
24611×
    if as_json {
24621×
        println!(
2463
            "{}",
24641×
            json::arr(repo.workspaces()?.iter().map(|w| {
24651×
                json::obj([
24661×
                    ("id", json::s(&w.id.to_hex())),
24671×
                    ("path", json::s(&w.path.to_string_lossy())),
24681×
                    ("current", json::b(w.current)),
2469
                    (
24701×
                        "working_copy",
24711×
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2472
                    ),
2473
                ])
24741×
            }))
2475
        );
24761×
        return Ok(0);
24770×
    }
24780×
    for w in repo.workspaces()? {
24790×
        println!(
2480
            "{} {} {}{}",
24810×
            if w.current {
24820×
                ui::ok(ui::glyph("●", "*"))
2483
            } else {
24840×
                ui::dim(ui::glyph("○", "o"))
2485
            },
24860×
            ui::id(w.id.short(8)),
24870×
            ui::path(w.path.display()),
24880×
            w.working_copy
24890×
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
24900×
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2491
        );
2492
    }
24930×
    Ok(0)
24941×
}
2495
24960×
pub fn workspace_forget(spec: &str) -> Result<i32> {
24970×
    let repo = open()?;
24980×
    let all = repo.workspaces()?;
24990×
    let target = std::fs::canonicalize(spec).ok();
25000×
    let matches: Vec<_> = all
25010×
        .iter()
25020×
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
25030×
        .collect();
25040×
    let w = match matches.as_slice() {
25050×
        [w] => *w,
25060×
        [] => anyhow::bail!("no workspace matches {spec:?}"),
25070×
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2508
    };
25090×
    repo.workspace_forget(&w.id)?;
25100×
    println!(
2511
        "{} workspace {} at {}; its files were left in place.",
25120×
        ui::done("Forgot"),
25130×
        ui::id(w.id.short(8)),
25140×
        ui::path(w.path.display())
2515
    );
25160×
    Ok(0)
25170×
}
2518
25190×
pub fn lock(path: &str) -> Result<i32> {
25200×
    let repo = open()?;
25210×
    repo.lock_path(path)?;
25220×
    println!(
2523
        "{} {} {}",
25240×
        ui::done("Locked"),
25250×
        ui::path(path),
25260×
        ui::dim("(advisory, local)")
2527
    );
25280×
    Ok(0)
25290×
}
2530
25310×
pub fn unlock(path: &str) -> Result<i32> {
25320×
    let repo = open()?;
25330×
    repo.unlock_path(path)?;
25340×
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
25350×
    Ok(0)
25360×
}
2537
25380×
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
25390×
    let repo = open()?;
25400×
    let h = repo.resolve_change(change)?;
25410×
    let (h1, h2) = repo.split(&h, paths)?;
25420×
    let c1 = repo.store().get_change_meta(&h1)?;
25430×
    let c2 = repo.store().get_change_meta(&h2)?;
25440×
    println!(
2545
        "{} into {} {} and {} {}",
25460×
        ui::done("Split"),
25470×
        ui::id(c1.change_id.short(8)),
25480×
        ui::hash(format!("#{}", h1.short(12))),
25490×
        ui::id(c2.change_id.short(8)),
25500×
        ui::hash(format!("#{}", h2.short(12)))
2551
    );
25520×
    Ok(0)
25530×
}
2554
25556×
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
25566×
    let mut heads = Vec::new();
25576×
    for c in changes {
25586×
        heads.extend(repo.resolve_heads(c)?);
2559
    }
25606×
    Ok(heads)
25616×
}
2562
25636×
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
25646×
    let repo = open()?;
25656×
    repo.snapshot_status("oxy bookmark create")?;
25666×
    let heads = if changes.is_empty() {
25673×
        None
2568
    } else {
25693×
        let named = heads_from(&repo, changes)?;
25703×
        let (_, wc) = repo.working_copy()?;
25713×
        let gap = repo.state_gap(&wc.deps, &named)?;
25723×
        if upto {
25731×
            Some(gap.upto)
25742×
        } else if only || gap.earlier.is_empty() {
25751×
            Some(named)
2576
        } else {
25771×
            anyhow::bail!(
2578
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2579
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2580
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2581
                 or --only for just {0} and what it depends on.",
25821×
                changes.join(" "),
25831×
                plural(gap.earlier.len(), "change"),
25841×
                listed_changes(&repo, &gap.earlier)
2585
            );
2586
        }
2587
    };
25885×
    let heads = repo.bookmark_create(name, heads.as_deref())?;
25895×
    println!(
2590
        "{} bookmark {} {} {}",
25915×
        ui::done("Created"),
25925×
        ui::bookmark(name),
25935×
        ui::dim(ui::glyph("→", "->")),
25945×
        ui::dim(plural(heads.len(), "head"))
2595
    );
25965×
    println!(
2597
        "  {} {}",
25985×
        ui::note(),
25995×
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2600
    );
26015×
    Ok(0)
26026×
}
2603
2604
/// Up to five changes, newest last, as `  #hash subject` lines.
26052×
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
26062×
    let shown = changes.len().min(5);
26072×
    let mut lines: Vec<String> = changes[changes.len() - shown..]
26082×
        .iter()
26092×
        .map(|h| {
26102×
            let subject = repo
26112×
                .store()
26122×
                .get_change(h)
26132×
                .map(|c| subject_of(&c.message).to_string())
26142×
                .unwrap_or_default();
26152×
            format!("  #{} {subject}", h.short(12))
26162×
        })
26172×
        .collect();
26182×
    if changes.len() > shown {
26190×
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
26202×
    }
26212×
    lines.join("\n")
26222×
}
2623
26243×
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
26253×
    let repo = open()?;
26263×
    repo.snapshot_status("oxy bookmark set")?;
26273×
    let named = heads_from(&repo, changes)?;
2628
    // What the bookmark holds now and the new heads would leave out.
26293×
    let current = repo
26303×
        .bookmarks()?
26313×
        .into_iter()
26326×
        .find(|b| b.name == name)
26333×
        .map(|b| b.heads)
26343×
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
26353×
    let gap = repo.state_gap(&current, &named)?;
2636
    // A fast-forward: the new heads hold the bookmark's newest head, so
2637
    // what they leave out is older work nothing since has built on, such
2638
    // as an early change no later one depends on (oxygen#78). Keep it, as
2639
    // --upto does, and say so.
26403×
    let newest = current
26413×
        .iter()
26428×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m.hlc, *h)))
26433×
        .max()
26443×
        .map(|(_, h)| h);
2645
    // Ahead, too: a head the bookmark holds already (it would only drop
2646
    // the others) is not a move forward.
26473×
    let ahead = repo
26483×
        .load_state_history(&current)
26493×
        .is_ok_and(|st| named.iter().any(|h| !st.contains(h)));
26503×
    let forward = !only
26513×
        && ahead
26521×
        && !gap.earlier.is_empty()
26531×
        && newest.is_some_and(|n| {
26541×
            repo.load_state_history(&named)
26551×
                .is_ok_and(|st| st.contains(&n))
26561×
        });
26573×
    let heads = if upto {
26581×
        gap.upto
26592×
    } else if forward {
26601×
        println!(
2661
            "  {} {}",
26621×
            ui::note(),
26631×
            ui::dim(format!(
2664
                "{} builds on {name}'s newest head; keeping {} it holds that {0} does not depend on",
26651×
                changes.join(" "),
26661×
                plural(gap.earlier.len(), "change")
2667
            ))
2668
        );
26691×
        gap.upto
26701×
    } else if only || gap.earlier.is_empty() {
26710×
        named
2672
    } else {
26731×
        anyhow::bail!(
2674
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2675
             A state is its heads and what they depend on, not everything recorded before them.\n\
2676
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2677
             or --only for just {0} and what it depends on.",
26781×
            changes.join(" "),
26791×
            plural(gap.earlier.len(), "change"),
26801×
            listed_changes(&repo, &gap.earlier)
2681
        );
2682
    };
26832×
    let heads = repo.bookmark_set(name, &heads)?;
26842×
    println!(
2685
        "{} bookmark {} {} {}",
26862×
        ui::done("Moved"),
26872×
        ui::bookmark(name),
26882×
        ui::dim(ui::glyph("→", "->")),
26892×
        ui::dim(plural(heads.len(), "head"))
2690
    );
26912×
    Ok(0)
26923×
}
2693
26940×
pub fn bookmark_delete(name: &str) -> Result<i32> {
26950×
    let repo = open()?;
26960×
    repo.bookmark_delete(name)?;
26970×
    println!(
2698
        "{} bookmark {} {}",
26990×
        ui::done("Deleted"),
27000×
        ui::bookmark(name),
27010×
        ui::dim("(its changes stay until unreachable)")
2702
    );
27030×
    Ok(0)
27040×
}
2705
2706
/// Heads with their metadata, newest first.
27070×
fn heads_newest_first(
27080×
    repo: &Repo,
27090×
    heads: &[oxy_core::hash::ChangeHash],
27100×
) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> {
27110×
    let mut out: Vec<_> = heads
27120×
        .iter()
27130×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m)))
27140×
        .collect();
27150×
    out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc));
27160×
    out
27170×
}
2718
2719
/// One head as a line: id, hash, author, when, subject.
27200×
fn print_head(
27210×
    repo: &Repo,
27220×
    indent: &str,
27230×
    h: &oxy_core::hash::ChangeHash,
27240×
    m: &oxy_core::state::ChangeMeta,
27250×
) {
27260×
    println!(
2727
        "{indent}{} {} {}{}{}{}{}",
27280×
        ui::id(m.change_id.short(8)),
27290×
        ui::dim(format!("#{}", &h.to_hex()[..8])),
27300×
        author_name(repo, m),
27310×
        ui::sep(),
27320×
        ui::dim(ui::ago(m.hlc.wall_ms)),
27330×
        ui::sep(),
27340×
        ui::subject(subject_of(&m.message))
2735
    );
27360×
}
2737
27380×
pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result<i32> {
27390×
    let repo = open()?;
27400×
    let name = name.unwrap_or(&repo.config.bookmark).to_string();
27410×
    let view = repo.view()?;
27420×
    let st = match view.bookmarks.get(&name) {
27430×
        Some(st) => *st,
27440×
        None => match oxy_core::repo::remote_bookmark(&view, &name) {
27450×
            Some((_, _, st)) => st,
27460×
            None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"),
2747
        },
2748
    };
27490×
    let heads = repo.store().get_state(&st)?.heads;
27500×
    let shown = heads_newest_first(&repo, &heads);
27510×
    if as_json {
27520×
        println!(
2753
            "{}",
27540×
            json::obj([
27550×
                ("name", json::s(&name)),
27560×
                ("current", json::b(name == repo.config.bookmark)),
2757
                (
27580×
                    "heads",
27590×
                    json::arr(shown.iter().map(|(h, m)| {
27600×
                        json::obj([
27610×
                            ("hash", json::s(&h.to_hex())),
27620×
                            ("id", json::s(&m.change_id.to_string())),
27630×
                            ("author", json::s(&author_name(&repo, m))),
27640×
                            ("time_ms", json::n(m.hlc.wall_ms)),
27650×
                            ("subject", json::s(subject_of(&m.message))),
27660×
                        ])
27670×
                    }))
2768
                ),
2769
            ])
2770
        );
27710×
        return Ok(0);
27720×
    }
27730×
    println!(
2774
        "{} {}{}{}",
27750×
        ui::ok(ui::glyph("●", "*")),
27760×
        ui::bookmark(&name),
27770×
        ui::sep(),
27780×
        ui::dim(plural(heads.len(), "head"))
2779
    );
27800×
    for (h, m) in &shown {
27810×
        print_head(&repo, "  ", h, m);
27820×
    }
27830×
    if heads.len() > 1 {
27840×
        println!(
27850×
            "  {}",
27860×
            ui::dim("None depends on another: the bookmark is all of them and their dependencies.")
27870×
        );
27880×
    }
27890×
    Ok(0)
27900×
}
2791
27925×
pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result<i32> {
27935×
    let repo = open()?;
27945×
    let remote_only = repo.remote_only_bookmarks()?;
27955×
    if as_json {
27965×
        let mut items: Vec<String> = repo
27975×
            .bookmarks()?
27985×
            .into_iter()
279913×
            .map(|b| {
280013×
                json::obj([
280113×
                    ("name", json::s(&b.name)),
280213×
                    ("heads", json::hashes(&b.heads)),
280313×
                    ("current", json::b(b.current)),
280413×
                    ("ahead", json::opt(b.ahead, json::n)),
280513×
                    ("behind", json::opt(b.behind, json::n)),
280613×
                    ("remote", json::opt(b.remote.as_deref(), json::s)),
280713×
                ])
280813×
            })
28095×
            .collect();
28105×
        if all {
28110×
            items.extend(remote_only.iter().map(|b| {
28120×
                json::obj([
28130×
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
28140×
                    ("heads", json::hashes(&b.heads)),
28150×
                    ("current", json::b(false)),
28160×
                    ("ahead", "null".into()),
28170×
                    ("behind", "null".into()),
28180×
                    ("remote", json::s(&b.remote)),
28190×
                ])
28200×
            }));
28215×
        }
28225×
        println!("{}", json::arr(items));
28235×
        return Ok(0);
28240×
    }
28250×
    for b in repo.bookmarks()? {
28260×
        let mark = if b.current {
28270×
            ui::ok(ui::glyph("●", "*"))
2828
        } else {
28290×
            ui::dim(ui::glyph("○", "o"))
2830
        };
28310×
        let mut tail = String::new();
28320×
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
28330×
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
28340×
        }
28350×
        if let Some(n) = b.behind.filter(|n| *n > 0) {
28360×
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
28370×
        }
2838
        // Which remote, when there is a choice (oxygen#83).
28390×
        if !tail.is_empty() && repo.config.remotes.len() > 1 {
28400×
            if let Some(r) = &b.remote {
28410×
                tail += &ui::dim(format!(" {r}"));
28420×
            }
28430×
        }
28440×
        let shown = heads_newest_first(&repo, &b.heads);
2845
        // The newest head's subject, so a busy bookmark shows its latest work.
28460×
        let head = match shown.first() {
28470×
            Some(_) if verbose => String::new(),
28480×
            Some((_, m)) if b.heads.len() > 1 => format!(
2849
                "{} {}",
28500×
                ui::dim("newest"),
28510×
                ui::subject(subject_of(&m.message))
2852
            ),
28530×
            Some((_, m)) => ui::subject(subject_of(&m.message)),
28540×
            None => ui::dim("(empty)"),
2855
        };
28560×
        let head = if head.is_empty() {
28570×
            head
2858
        } else {
28590×
            format!("  {head}")
2860
        };
28610×
        println!(
2862
            "{mark} {}{}{}{tail}{head}",
28630×
            ui::bookmark(&b.name),
28640×
            ui::sep(),
28650×
            ui::dim(plural(b.heads.len(), "head"))
2866
        );
28670×
        if verbose {
28680×
            for (h, m) in &shown {
28690×
                print_head(&repo, "    ", h, m);
28700×
            }
28710×
        }
2872
    }
28730×
    if remote_only.is_empty() {
28740×
        return Ok(0);
28750×
    }
28760×
    if !all {
28770×
        println!(
2878
            "{}",
28790×
            ui::dim(format!(
2880
                "  and {} only on a remote: oxy bookmark list --all",
28810×
                plural(remote_only.len(), "bookmark")
2882
            ))
2883
        );
28840×
        return Ok(0);
28850×
    }
28860×
    for b in &remote_only {
28870×
        println!(
28880×
            "{} {}{}{}",
28890×
            ui::dim(ui::glyph("◌", ".")),
28900×
            ui::dim(format!("{}/{}", b.remote, b.name)),
28910×
            ui::sep(),
28920×
            ui::dim(plural(b.heads.len(), "head"))
28930×
        );
28940×
    }
28950×
    println!(
2896
        "  {} {}",
28970×
        ui::note(),
28980×
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2899
    );
29000×
    Ok(0)
29015×
}
2902
29033×
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
29043×
    let mut repo = open()?;
29053×
    let from = repo.config.bookmark.clone();
29063×
    let (local, created_from) = repo.local_bookmark_for(name)?;
29073×
    if let Some(remote) = created_from {
29080×
        println!(
29090×
            "{} {} from {}",
29100×
            ui::done("Created"),
29110×
            ui::bookmark(&local),
29120×
            ui::dim(format!("{remote}/{local}"))
29130×
        );
29143×
    }
29153×
    let name = local.as_str();
2916
    // Only behind its remote: take the remote's state, so the switch does
2917
    // not check out a stale one (oxygen#74).
29183×
    if let Some(n) = repo.catch_up_bookmark(name)? {
29190×
        println!(
29200×
            "{} {} with {}: {} it lacked",
29210×
            ui::done("Caught up"),
29220×
            ui::bookmark(name),
29230×
            ui::dim(format!("{}/{name}", repo.default_remote())),
29240×
            plural(n, "change")
29250×
        );
29263×
    }
29273×
    let sp = ui::spinner(&format!("Switching to {name}…"));
29283×
    let (r, carried) = if carry {
29290×
        repo.bookmark_switch_carry(name)?
2930
    } else {
29313×
        (repo.bookmark_switch(name, discard)?, vec![])
2932
    };
29333×
    sp.done(&format!(
2934
        "{} to {}: {} written, {} removed{}",
29353×
        ui::done("Switched"),
29363×
        ui::bookmark(name),
29373×
        plural(r.written, "file"),
2938
        r.removed,
29393×
        if carried.is_empty() {
29403×
            String::new()
2941
        } else {
29420×
            format!("; carried {}", plural(carried.len(), "changed path"))
2943
        }
2944
    ));
29453×
    print_removed(&r);
29463×
    print_carried(&carried);
29473×
    if r.conflicted {
29480×
        println!(
29490×
            "  {} {}",
29500×
            ui::caution(),
29510×
            ui::warn("this state has conflicts; see oxy status")
29520×
        );
29533×
    }
2954
    // Say when the new state leaves out work the old one had: a state is
2955
    // its heads and what they depend on, which can be far less than a Git
2956
    // user expects.
29573×
    if r.lacks > 0 {
29581×
        println!(
29591×
            "  {} {}",
29601×
            ui::note(),
29611×
            ui::dim(format!(
29621×
                "{name} lacks {} that {from} has",
29631×
                plural(r.lacks, "change")
29641×
            ))
29651×
        );
29662×
    }
29673×
    super::sync::subrepos_behind(&repo);
29683×
    where_now(&repo);
29693×
    Ok(0)
29703×
}
2971
29720×
pub fn merge(bookmark: &str) -> Result<i32> {
29730×
    let repo = open()?;
29740×
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
29750×
    let r = repo.merge(bookmark)?;
29760×
    if !r.changed {
29770×
        sp.done(&format!(
29780×
            "{} {}",
29790×
            ui::ok(ui::glyph("✔", "*")),
29800×
            ui::dim(format!(
29810×
                "{} already contains {bookmark}",
29820×
                repo.config.bookmark
29830×
            ))
29840×
        ));
29850×
        return Ok(0);
29860×
    }
29870×
    sp.done(&format!(
2988
        "{} {} into {}: now {}{}",
29890×
        ui::done("Merged"),
29900×
        ui::bookmark(bookmark),
29910×
        ui::bookmark(&repo.config.bookmark),
29920×
        plural(r.heads.len(), "head"),
29930×
        ui::dim(if r.checked_out {
29940×
            "; working copy updated"
2995
        } else {
29960×
            "; run oxy checkout to update the working copy"
2997
        })
2998
    ));
29990×
    let snap = repo.snapshot("oxy merge")?;
30000×
    if snap.base_snapshot.is_conflicted() {
30010×
        println!(
30020×
            "  {} {}",
30030×
            ui::caution(),
30040×
            ui::warn("the result has conflicts; see oxy status")
30050×
        );
30060×
    }
30070×
    where_now(&repo);
30080×
    Ok(0)
30090×
}
3010
30110×
pub fn squash(change: &str, into: &str) -> Result<i32> {
30120×
    let repo = open()?;
30130×
    let c = repo.resolve_change(change)?;
30140×
    let d = repo.resolve_change(into)?;
30150×
    let sp = ui::spinner("Squashing…");
30160×
    let h = repo.squash(&c, &d)?;
30170×
    let new = repo.store().get_change_meta(&h)?;
30180×
    sp.done(&format!(
30190×
        "{} into {} {}  {}",
30200×
        ui::done("Squashed"),
30210×
        ui::id(new.change_id.short(8)),
30220×
        ui::hash(format!("#{}", h.short(12))),
30230×
        ui::subject(subject_of(&new.message))
30240×
    ));
30250×
    Ok(0)
30260×
}
3027
30280×
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
30290×
    let repo = open()?;
30300×
    let c = repo.resolve_change(change)?;
30310×
    let mut heads = Vec::new();
30320×
    for o in onto {
30330×
        heads.extend(repo.resolve_heads(o)?);
3034
    }
30350×
    let sp = ui::spinner("Rebasing…");
30360×
    let h = match repo.rebase(&c, &heads) {
30370×
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
30380×
            let r = repo.rebase_into_working_copy(&c, &heads)?;
30390×
            sp.done(&format!(
30400×
                "{} {} into {}: now {}",
30410×
                ui::done("Merged"),
30420×
                onto.join(" "),
30430×
                ui::bookmark(&repo.config.bookmark),
30440×
                plural(r.heads.len(), "head"),
30450×
            ));
30460×
            if r.checked_out {
30470×
                println!(
30480×
                    "  {} {}",
30490×
                    ui::caution(),
30500×
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
30510×
                );
30520×
            } else {
30530×
                println!(
30540×
                    "  {} {}",
30550×
                    ui::caution(),
30560×
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
30570×
                );
30580×
            }
30590×
            where_now(&repo);
30600×
            return Ok(0);
3061
        }
30620×
        other => other?,
3063
    };
30640×
    let new = repo.store().get_change_meta(&h)?;
30650×
    sp.done(&format!(
30660×
        "{} {} {}  {}",
30670×
        ui::done("Rebased"),
30680×
        ui::id(new.change_id.short(8)),
30690×
        ui::hash(format!("#{}", h.short(12))),
30700×
        ui::dim(format!(
30710×
            "now depends on {}",
30720×
            plural(new.deps.len(), "change")
30730×
        ))
30740×
    ));
30750×
    where_now(&repo);
30760×
    Ok(0)
30770×
}
3078
3079
#[cfg(test)]
3080
mod tests {
3081
    use super::*;
3082
3083
    #[test]
30841×
    fn id_prefixes_agree_with_the_whole_list() {
3085
        // Ids that share long prefixes, and some that differ only in a
3086
        // half byte, from a fixed sequence.
30871×
        let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
30887999×
        let mut next = || {
30897999×
            x ^= x << 13;
30907999×
            x ^= x >> 7;
30917999×
            x ^= x << 17;
30927999×
            x
30937999×
        };
30941×
        let mut ids: Vec<[u8; 16]> = Vec::new();
30951×
        for _ in 0..2000 {
30962000×
            let mut id = [0u8; 16];
30972000×
            id[..8].copy_from_slice(&next().to_le_bytes());
30982000×
            id[8..].copy_from_slice(&next().to_le_bytes());
30992000×
            let share = (next() % 4) as usize;
31002000×
            if let Some(prev) = ids.last() {
31011999×
                id[..share].copy_from_slice(&prev[..share]);
31021999×
                if next() % 2 == 0 {
3103973×
                    id[share] = (prev[share] & 0xf0) | (id[share] & 0x0f);
31041026×
                }
31051×
            }
31062000×
            ids.push(id);
3107
        }
31084000×
        let hex = |id: &[u8; 16]| oxy_core::ids::ChangeId(*id).to_hex();
31091×
        let whole = unique_prefixes(ids.iter().map(hex));
31101×
        let some = id_prefixes(ids.clone(), ids.iter().copied());
31112000×
        for id in &ids {
31122000×
            assert_eq!(some[id], whole[&hex(id)], "{}", hex(id));
3113
        }
31141×
    }
3115
}