OXYGENHUB

Coverage / src/cli/workspace.rs 39.0%

979 of 2512 lines run, 96 of 355 functions · run #394 on proposal/151 · 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×
            let resolved = matches!(
3100×
                snap.statuses
3110×
                    .iter()
3120×
                    .find(|s| s.path == *p)
3130×
                    .map(|s| s.status),
314
                Some(ChangeStatus::Resolved)
315
            );
3160×
            let both = if resolved {
3170×
                0
318
            } else {
3190×
                snap.base.both_sides(&f.node).iter().flatten().count()
320
            };
3210×
            if both > 0 {
3220×
                println!(
323
                    "     {}",
3240×
                    ui::dim(format!(
325
                        "{} adjacent {}: `oxy resolve --both {p}` keeps both sides, earliest first",
326
                        both,
3270×
                        if both == 1 { "insertion" } else { "insertions" }
328
                    ))
329
                );
3300×
            }
3310×
        }
332
    }
3330×
    Ok(2)
3348×
}
335
33626×
pub fn commit(
33726×
    message: &str,
33826×
    depends_on: &[String],
33926×
    paths: &[String],
34026×
    interactive: bool,
34126×
    hunks: &[usize],
34226×
) -> Result<i32> {
34326×
    let repo = open()?;
34426×
    let mut deps = Vec::new();
34526×
    for d in depends_on {
3460×
        deps.push(repo.resolve_change(d)?);
347
    }
34826×
    let selection = if !hunks.is_empty() {
3491×
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
35025×
    } else if interactive {
3510×
        let (_, hunks) = repo.hunks()?;
3520×
        if hunks.is_empty() {
3530×
            anyhow::bail!("nothing to commit: the working copy matches its base");
3540×
        }
3550×
        let hunks: Vec<_> = hunks
3560×
            .into_iter()
3570×
            .filter(|h| {
3580×
                paths.is_empty()
3590×
                    || paths.iter().any(|p| {
3600×
                        h.path == *p || h.path.starts_with(&format!("{}/", p.trim_end_matches('/')))
3610×
                    })
3620×
            })
3630×
            .collect();
3640×
        let mut chosen = Vec::new();
3650×
        let stdin = std::io::stdin();
3660×
        let mut take_rest = false;
3670×
        for (n, h) in hunks.iter().enumerate() {
3680×
            if take_rest {
3690×
                chosen.push(h.index);
3700×
                continue;
3710×
            }
3720×
            println!(
373
                "{} {} {}",
3740×
                ui::section(format!("hunk {} of {}", n + 1, hunks.len())),
3750×
                ui::path(&h.path),
3760×
                ui::dim(format!("(#{})", h.index))
377
            );
3780×
            for line in h.text.lines() {
3790×
                let styled = if line.starts_with('+') {
3800×
                    ui::ok(line)
3810×
                } else if line.starts_with('-') {
3820×
                    ui::err(line)
383
                } else {
3840×
                    ui::dim(line)
385
                };
3860×
                println!("  {styled}");
387
            }
388
            loop {
3890×
                print!(
390
                    "{} ",
3910×
                    ui::warn("Commit this hunk? [y]es [n]o [a]ll remaining [q]uit:")
392
                );
393
                use std::io::Write as _;
3940×
                std::io::stdout().flush()?;
3950×
                let mut answer = String::new();
3960×
                if stdin.read_line(&mut answer)? == 0 {
3970×
                    anyhow::bail!("aborted");
3980×
                }
3990×
                match answer.trim() {
4000×
                    "y" | "Y" => {
4010×
                        chosen.push(h.index);
4020×
                        break;
403
                    }
4040×
                    "n" | "N" | "" => break,
4050×
                    "a" | "A" => {
4060×
                        chosen.push(h.index);
4070×
                        take_rest = true;
4080×
                        break;
409
                    }
4100×
                    "q" | "Q" => anyhow::bail!("aborted; nothing committed"),
4110×
                    _ => continue,
412
                }
413
            }
414
        }
4150×
        if chosen.is_empty() {
4160×
            anyhow::bail!("no hunks chosen; nothing committed");
4170×
        }
4180×
        oxy_core::repo::Selection::Hunks(chosen)
41925×
    } else if paths.is_empty() {
42023×
        oxy_core::repo::Selection::All
421
    } else {
4222×
        oxy_core::repo::Selection::Paths(paths.to_vec())
423
    };
42426×
    let sp = ui::spinner("Committing…");
42526×
    let (h, partial) = repo.commit_selection_partial(message, &deps, &selection)?;
426
    // The metadata only: a first commit's change holds the whole tree.
42726×
    let meta = repo.store().get_change_meta(&h)?;
42826×
    sp.done(&format!(
42926×
        "{} {} {}  {}",
43026×
        ui::done("Committed"),
43126×
        ui::id(meta.change_id.short(8)),
43226×
        ui::hash(format!("#{}", h.short(12))),
43326×
        ui::subject(subject_of(message))
43426×
    ));
43526×
    print_untracked_nested(&repo, &repo.untracked_nested());
43626×
    print_skipped_large(&repo);
437
    // Only a commit that took part of the working copy leaves anything.
43826×
    if partial {
4392×
        let rest = repo.snapshot_status("oxy commit")?;
4402×
        if !rest.statuses.is_empty() {
4412×
            println!(
4422×
                "  {} {}",
4432×
                ui::note(),
4442×
                ui::dim(format!(
4452×
                    "{} left uncommitted",
4462×
                    plural(rest.statuses.len(), "path")
4472×
                ))
4482×
            );
4492×
        }
45024×
    }
45126×
    where_now(&repo);
45226×
    Ok(0)
45326×
}
454
4550×
pub fn blame(path: &str, json: bool) -> Result<i32> {
4560×
    let repo = open()?;
4570×
    let lines = repo.blame(path)?;
4580×
    if json {
4590×
        let items = lines.iter().map(|l| {
4600×
            format!(
461
                "{{\"line\":{},\"change_id\":{},\"hash\":{},\"index\":{},\"author\":{},\"when_ms\":{}}}",
462
                l.line,
4630×
                oxy_core::repo::json_str(&l.change_id.to_hex()),
4640×
                oxy_core::repo::json_str(&l.hash.to_hex()),
465
                l.index,
4660×
                oxy_core::repo::json_str(&l.author),
467
                l.when_ms
468
            )
4690×
        });
4700×
        println!("{}", oxy_core::repo::json_array(items));
4710×
        return Ok(0);
4720×
    }
4730×
    let width = lines
4740×
        .iter()
4750×
        .map(|l| l.author.chars().count())
4760×
        .max()
4770×
        .unwrap_or(0)
4780×
        .min(20);
4790×
    let digits = lines.len().to_string().len();
4800×
    let _t = oxy_core::timing::phase("blame: print");
481
    // Most lines share their change with many others: each change's id,
482
    // author and age are formatted once, and the lines go out through one
483
    // buffered lock on stdout.
4840×
    let mut prefix: std::collections::HashMap<oxy_core::hash::ChangeHash, String> =
4850×
        std::collections::HashMap::new();
4860×
    let bar = ui::dim(ui::glyph("│", "|"));
4870×
    let mut out = std::io::BufWriter::with_capacity(1 << 16, std::io::stdout().lock());
4880×
    for l in &lines {
4890×
        let p = prefix.entry(l.hash).or_insert_with(|| {
4900×
            let author: String = l.author.chars().take(20).collect();
4910×
            format!(
492
                "{} {} {}",
4930×
                ui::id(l.change_id.short(8)),
4940×
                ui::author(format!("{author:<width$}")),
4950×
                ui::dim(ui::ago(l.when_ms))
496
            )
4970×
        });
4980×
        let text = String::from_utf8_lossy(&l.text);
4990×
        if writeln!(
5000×
            out,
501
            "{p} {:>digits$}{bar} {}",
502
            l.line,
5030×
            text.trim_end_matches('\n')
504
        )
5050×
        .is_err()
506
        {
507
            // A closed pipe (blame | head): stop quietly.
5080×
            return Ok(0);
5090×
        }
510
    }
5110×
    let _ = out.flush();
5120×
    Ok(0)
5130×
}
514
5150×
fn bisect_report(repo: &Repo, step: &oxy_core::repo::BisectStep) -> Result<i32> {
516
    use oxy_core::repo::BisectStep::*;
5170×
    match step {
5180×
        NeedMarks { good, bad } => {
5190×
            println!(
520
                "{} {} {}",
5210×
                ui::note(),
5220×
                ui::dim(format!("{good} good, {bad} bad;")),
5230×
                ui::dim(if *good == 0 {
5240×
                    "mark a known-good change or bookmark: oxy bisect good CHANGE"
525
                } else {
5260×
                    "mark a known-bad change or bookmark: oxy bisect bad CHANGE"
527
                })
528
            );
5290×
            Ok(0)
530
        }
531
        Testing {
5320×
            heads,
5330×
            remaining,
5340×
            steps_left,
535
        } => {
5360×
            println!(
537
                "{} {} {}",
5380×
                ui::done("Testing"),
5390×
                ui::dim(format!(
540
                    "{} in the state under test;",
5410×
                    plural(heads.len(), "head")
542
                )),
5430×
                ui::dim(format!(
544
                    "{remaining} candidates left, about {steps_left} more steps"
545
                ))
546
            );
5470×
            println!(
548
                "  {} {}",
5490×
                ui::note(),
5500×
                ui::dim("run your test, then oxy bisect good | bad | skip")
551
            );
5520×
            Ok(0)
553
        }
5540×
        Found { culprit } => {
5550×
            let c = repo.store().get_change(culprit)?;
5560×
            println!(
557
                "{} {} {}  {}",
5580×
                ui::done("Found"),
5590×
                ui::id(short_id(&c)),
5600×
                ui::hash(format!("#{}", culprit.short(12))),
5610×
                ui::subject(subject_of(&c.message))
562
            );
5630×
            println!("  {} {}", ui::note(), ui::dim("the first change whose inclusion makes the state bad; oxy bisect reset to return"));
5640×
            Ok(0)
565
        }
5660×
        Inconclusive { candidates } => {
5670×
            println!(
568
                "{} {}",
5690×
                ui::caution(),
5700×
                ui::warn(format!(
571
                    "every remaining candidate was skipped ({}); oxy bisect reset to return",
5720×
                    plural(candidates.len(), "change")
573
                ))
574
            );
5750×
            Ok(1)
576
        }
577
    }
5780×
}
579
5800×
pub fn bisect_start() -> Result<i32> {
5810×
    let repo = open()?;
5820×
    repo.bisect_start()?;
5830×
    println!(
584
        "{} bisect; {}",
5850×
        ui::done("Started"),
5860×
        ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE")
587
    );
5880×
    Ok(0)
5890×
}
590
5910×
pub fn bisect_mark(good: Option<bool>, changes: &[String]) -> Result<i32> {
5920×
    let repo = open()?;
5930×
    let mut heads = Vec::new();
5940×
    for c in changes {
5950×
        heads.extend(repo.resolve_heads(c)?);
596
    }
5970×
    let step = repo.bisect_mark(good, &heads)?;
5980×
    bisect_report(&repo, &step)
5990×
}
600
6010×
pub fn bisect_run(command: &[String]) -> Result<i32> {
6020×
    let repo = open()?;
6030×
    let step = repo.bisect_run(command)?;
6040×
    bisect_report(&repo, &step)
6050×
}
606
6071×
pub fn bisect_status(as_json: bool) -> Result<i32> {
6081×
    let repo = open()?;
6091×
    if as_json {
610
        use oxy_core::repo::BisectStep::*;
6111×
        let v = match repo.bisect_status()? {
6121×
            None => "null".to_string(),
6130×
            Some(NeedMarks { good, bad }) => json::obj([
6140×
                ("state", json::s("need-marks")),
6150×
                ("good", json::n(good)),
6160×
                ("bad", json::n(bad)),
6170×
            ]),
618
            Some(Testing {
6190×
                heads,
6200×
                remaining,
6210×
                steps_left,
6220×
            }) => json::obj([
6230×
                ("state", json::s("testing")),
6240×
                ("heads", json::hashes(&heads)),
6250×
                ("remaining", json::n(remaining)),
6260×
                ("steps_left", json::n(steps_left)),
6270×
            ]),
6280×
            Some(Found { culprit }) => json::obj([
6290×
                ("state", json::s("found")),
6300×
                ("culprit", json::s(&culprit.to_hex())),
6310×
            ]),
6320×
            Some(Inconclusive { candidates }) => json::obj([
6330×
                ("state", json::s("inconclusive")),
6340×
                ("candidates", json::hashes(&candidates)),
6350×
            ]),
636
        };
6371×
        println!("{v}");
6381×
        return Ok(0);
6390×
    }
6400×
    match repo.bisect_status()? {
641
        None => {
6420×
            println!("{}", ui::dim("No bisect in progress."));
6430×
            Ok(0)
644
        }
6450×
        Some(step) => bisect_report(&repo, &step),
646
    }
6471×
}
648
6490×
pub fn bisect_reset() -> Result<i32> {
6500×
    let repo = open()?;
6510×
    repo.bisect_reset()?;
6520×
    println!("{} bisect; working copy restored", ui::done("Reset"));
6530×
    Ok(0)
6540×
}
655
656
/// The log: one entry per change, newest first, joined by a rail. The
657
/// default view is the subject and a metadata line; `verbose` adds the full
658
/// message, dependencies, and the authenticating key.
65914×
fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
66014×
    Ok(match repo.authenticate_change(h)? {
6619×
        SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]),
662
        SignatureStatus::Valid {
6635×
            key,
6645×
            name,
6655×
            email,
6665×
            sealed,
6675×
            revoked,
6685×
        } => json::obj([
6695×
            ("status", json::s(if sealed { "sealed" } else { "signed" })),
6705×
            ("key", json::s(&key.to_hex())),
6715×
            ("name", json::s(&name)),
6725×
            ("email", json::s(&email)),
6735×
            ("revoked", json::b(revoked)),
674
        ]),
6750×
        SignatureStatus::Invalid(why) => {
6760×
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
677
        }
678
    })
67914×
}
680
68118×
fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result<String> {
68218×
    let c = &e.change;
68318×
    Ok(json::obj([
68418×
        ("hash", json::s(&e.hash.to_hex())),
68518×
        ("change_id", json::s(&c.change_id.to_hex())),
68618×
        ("author", json::s(&author_name(repo, c))),
68718×
        ("author_key", json::s(&c.author.to_hex())),
688
        (
68918×
            "via",
69018×
            match via(
69118×
                repo,
69218×
                &repo.authenticate_change_known(&e.hash, Some(c))?,
69318×
                &c.author,
694
            ) {
6950×
                Some(v) => json::obj([
6960×
                    ("name", json::s(&v.name)),
6970×
                    ("email", json::s(&v.email)),
6980×
                    ("key", json::s(&v.key.to_hex())),
6990×
                    ("scope", json::opt(v.scope.as_deref(), json::s)),
7000×
                    ("expires_ms", json::opt(v.expires, json::n)),
7010×
                    ("revoked", json::b(v.revoked)),
7020×
                ]),
70318×
                None => "null".to_string(),
704
            },
705
        ),
70618×
        ("when_ms", json::n(c.hlc.wall_ms)),
70718×
        ("message", json::s(&c.message)),
70818×
        ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())),
70918×
        ("deps", json::hashes(&c.deps)),
71018×
        ("head", json::b(e.is_head)),
71118×
        ("working_copy", json::b(e.is_working_copy)),
712
        (
71318×
            "signature",
71418×
            if e.is_working_copy {
7154×
                "null".into()
716
            } else {
71714×
                signature_json(repo, &e.hash)?
718
            },
719
        ),
720
    ]))
72118×
}
722
723
/// `START,END:PATH` for `oxy log -L`.
7242×
fn parse_line_range(spec: &str) -> Result<(usize, usize, &str)> {
7252×
    let bad = || anyhow::anyhow!("-L {spec}: expected START,END:PATH, as 10,24:src/lib.rs");
7262×
    let (range, path) = spec.split_once(':').ok_or_else(bad)?;
7272×
    let (a, b) = range.split_once(',').ok_or_else(bad)?;
728
    Ok((
7291×
        a.trim().parse().map_err(|_| bad())?,
7301×
        b.trim().parse().map_err(|_| bad())?,
7311×
        path,
732
    ))
7332×
}
734
7358×
pub fn log(
7368×
    revset: Option<&str>,
7378×
    limit: Option<usize>,
7388×
    verbose: bool,
7398×
    path: Option<&str>,
7408×
    lines: Option<&str>,
7418×
    as_json: bool,
7428×
) -> Result<i32> {
7438×
    let repo = open()?;
744
    // Whether the working copy is clean and conflicted: from the manifest
745
    // when it proves the working copy clean, else from a snapshot.
746
    // The working copy as last recorded, without looking at the files (as
747
    // Git's log does not): whether its change holds edits, and whether its
748
    // base was conflicted. `oxy status` is what checks the disk.
7498×
    let conflicted = !repo.is_at_op() && repo.recorded_conflicted()?;
7508×
    let listing = oxy_core::timing::phase("log: entries");
7518×
    let entries = match (path, lines) {
7528×
        _ if revset.is_some() => repo.log_revset(revset.unwrap_or_default())?,
7532×
        (_, Some(spec)) => {
7542×
            let (first, last, p) = parse_line_range(spec)?;
7551×
            let (_, wc) = repo.working_copy()?;
7561×
            let base = repo.load_state_history(&wc.deps)?.maximal(&wc.deps);
7571×
            repo.line_history(&base, p, first, last)?
758
        }
7591×
        (Some(p), None) => repo.log_for_path(p)?,
7605×
        (None, None) => repo.log()?,
761
    };
7627×
    drop(listing);
7637×
    let _print = oxy_core::timing::phase("log: print");
7647×
    if as_json {
7656×
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
7666×
        let mut items = Vec::new();
76717×
        for e in entries.iter().take(shown) {
76817×
            items.push(log_entry_json(&repo, e)?);
769
        }
7706×
        println!(
771
            "{}",
7726×
            json::obj([
7736×
                ("bookmark", json::s(&repo.config.bookmark)),
7746×
                ("total", json::n(entries.len())),
7756×
                ("changes", json::arr(items))
7766×
            ])
777
        );
7786×
        return Ok(0);
7791×
    }
7801×
    let total = entries.len();
7811×
    let shown = limit.unwrap_or(total).min(total);
782
    // Lay out a little past what is shown, so edges into the cut are drawn.
7831×
    let window: Vec<(ChangeHash, Vec<ChangeHash>)> = entries
7841×
        .iter()
7851×
        .take((shown + MAX_EDGE).min(total))
7864×
        .map(|e| (e.hash, e.change.deps.clone()))
7871×
        .collect();
7881×
    let rows = oxy_core::lanes::graph(&window, MAX_EDGE);
789
    // Highlight the shortest prefix that names each change: against the
790
    // whole log, which is what `resolve_change` searches.
791
    let everything;
7921×
    let all = if path.is_some() || lines.is_some() || revset.is_some() {
7930×
        everything = repo.log()?;
7940×
        &everything
795
    } else {
7961×
        &entries
797
    };
7981×
    let prefixes = oxy_core::timing::phase("log: id prefixes");
7991×
    let id_prefix = id_prefixes(
8001×
        all.iter().map(|e| e.change.change_id.0).collect(),
8011×
        entries.iter().take(shown).map(|e| e.change.change_id.0),
802
    );
8031×
    drop(prefixes);
8041×
    let labels = reference_labels(&repo)?;
8054×
    for (e, row) in entries.iter().take(shown).zip(&rows) {
8064×
        let c = &e.change;
8074×
        let bullet = ui::log_bullet(
8084×
            e.is_working_copy,
8094×
            e.is_head,
8104×
            e.is_working_copy && conflicted,
811
        );
8124×
        let id = c.change_id.to_hex();
8134×
        let n = id_prefix.get(&c.change_id.0).copied().unwrap_or(8).min(8);
8144×
        let mut head = vec![format!("{}{}", ui::id(&id[..n]), ui::dim(&id[n..8]))];
8154×
        head.push(ui::author(author_name(&repo, c)));
8164×
        head.push(ui::dim(ui::ago(c.hlc.wall_ms)));
8174×
        if let Some(names) = labels.get(&e.hash) {
8182×
            head.push(names.join(" "));
8192×
        }
8204×
        if c.kind == ChangeKind::Resolution {
8210×
            head.push(ui::warn("resolution"));
8224×
        }
8234×
        if !e.is_working_copy {
8243×
            head.push(ui::hash(format!("#{}", e.hash.short(8))));
8253×
            let status = repo.authenticate_change_known(&e.hash, Some(c))?;
8263×
            if let Some(agent) = via(&repo, &status, &c.author) {
8270×
                head.push(ui::dim(format!("via {}", agent.name)));
8283×
            }
8293×
            head.push(signature_mark_of(&status));
8301×
        }
8314×
        println!("{}{}", node_line(row, &bullet), head.join(" "));
8324×
        let subject = if e.is_working_copy && c.message.is_empty() {
8331×
            let edited = repo
8341×
                .store()
8351×
                .get_change(&e.hash)
8361×
                .is_ok_and(|w| !w.tree_ops.is_empty() || !w.edits.is_empty());
8371×
            ui::dim(if edited {
8380×
                "(working copy, uncommitted changes)"
839
            } else {
8401×
                "(working copy)"
841
            })
8423×
        } else if c.message.trim().is_empty() {
8430×
            ui::dim("(no description)")
844
        } else {
8453×
            subject_of(&c.message).to_string()
846
        };
8474×
        println!("{}{subject}", below_line(row));
8484×
        if verbose {
8490×
            let rail = continuation(row);
8500×
            if !e.is_working_copy {
8510×
                println!(
852
                    "{rail}{}",
8530×
                    ui::dim(format!(
854
                        "{} {}",
8550×
                        when(c.hlc.wall_ms),
8560×
                        signature_line(&repo, &e.hash)?
857
                    ))
858
                );
8590×
            }
8600×
            if !c.deps.is_empty() {
8610×
                println!(
8620×
                    "{rail}{} {}",
8630×
                    ui::dim(ui::glyph("↳", "->")),
8640×
                    ui::dim(deps_of(&c.deps))
8650×
                );
8660×
            }
8670×
            let body: Vec<&str> = c
8680×
                .message
8690×
                .lines()
8700×
                .skip(1)
8710×
                .skip_while(|l| l.trim().is_empty())
8720×
                .collect();
8730×
            for line in body {
8740×
                println!("{rail}  {line}");
8750×
            }
8764×
        }
877
    }
8781×
    if shown < total {
8790×
        if let Some(last) = rows.get(shown.saturating_sub(1)) {
8800×
            let cut: String = last
8810×
                .below
8820×
                .iter()
8830×
                .map(|c| match c {
8840×
                    Cell::Blank | Cell::Elided | Cell::JoinRight => "  ",
8850×
                    _ => "~ ",
8860×
                })
8870×
                .collect();
8880×
            if cut.trim().is_empty() {
8890×
                println!("{}", ui::dim("~"));
8900×
            } else {
8910×
                println!("{}", ui::dim(cut.trim_end()));
8920×
            }
8930×
        }
8940×
        println!(
895
            "{}",
8960×
            ui::dim(format!(
897
                "{} {} more; pass -n to see them",
8980×
                ui::glyph("…", "..."),
8990×
                total - shown
900
            ))
901
        );
9021×
    }
9031×
    Ok(0)
9048×
}
905
906
/// Rows a drawn edge may span in `oxy log`; a longer one is elided (`~`).
907
const MAX_EDGE: usize = 12;
908
909
use oxy_core::hash::ChangeHash;
910
use oxy_core::lanes::{Cell, GraphRow};
911
912
/// A graph cell, two columns wide.
9136×
fn cell(c: Cell) -> &'static str {
9146×
    match c {
9151×
        Cell::Blank => "  ",
9163×
        Cell::Line => ui::glyph("│ ", "| "),
9170×
        Cell::Elided => "~ ",
9181×
        Cell::JoinLeft => ui::glyph("├─", "|-"),
9190×
        Cell::JoinPass => ui::glyph("──", "--"),
9200×
        Cell::JoinCross => ui::glyph("┼─", "+-"),
9211×
        Cell::JoinRight => ui::glyph("╯ ", "' "),
922
    }
9236×
}
924
925
/// The graph part of a change's own line, its bullet in its column.
9264×
fn node_line(row: &GraphRow, bullet: &str) -> String {
9274×
    let width = row
9284×
        .passing
9294×
        .iter()
9304×
        .copied()
9314×
        .max()
9324×
        .unwrap_or(0)
9334×
        .max(row.column)
9344×
        + 1;
9354×
    let mut out = String::new();
9365×
    for c in 0..width {
9375×
        if c == row.column {
9384×
            out.push_str(bullet);
9394×
            out.push(' ');
9404×
        } else if row.passing.contains(&c) {
9411×
            out.push_str(&ui::dim(cell(Cell::Line)));
9421×
        } else {
9430×
            out.push_str("  ");
9440×
        }
945
    }
9464×
    out.push(' ');
9474×
    out
9484×
}
949
950
/// The graph part of the line under a change: lanes carrying on, a join,
951
/// or `~` for an elided edge.
9524×
fn below_line(row: &GraphRow) -> String {
9535×
    let g: String = row.below.iter().map(|c| cell(*c)).collect();
9544×
    format!("{} ", ui::dim(g))
9554×
}
956
957
/// The graph part of any further line of a change (`-v`).
9580×
fn continuation(row: &GraphRow) -> String {
9590×
    let g: String = row
9600×
        .below
9610×
        .iter()
9620×
        .map(|c| match c {
9630×
            Cell::Line | Cell::JoinLeft | Cell::JoinCross => cell(Cell::Line),
9640×
            _ => "  ",
9650×
        })
9660×
        .collect();
9670×
    format!("{} ", ui::dim(g))
9680×
}
969
970
/// For each hex ID, the length of its shortest prefix no other ID shares.
971
/// The shortest prefix, in hex digits, that names each of `wanted` among
972
/// `all`: worked out for the few shown rather than for the whole history.
9732×
fn id_prefixes(
9742×
    mut all: Vec<[u8; 16]>,
9752×
    wanted: impl Iterator<Item = [u8; 16]>,
9762×
) -> std::collections::HashMap<[u8; 16], usize> {
9772×
    all.sort_unstable();
9782×
    all.dedup();
979
    // Hex digits two ids share at the start.
9804004×
    let common = |a: &[u8; 16], b: &[u8; 16]| {
98110720×
        let bytes = a.iter().zip(b).take_while(|(x, y)| x == y).count();
9824004×
        match (a.get(bytes), b.get(bytes)) {
9834004×
            (Some(x), Some(y)) if x >> 4 == y >> 4 => 2 * bytes + 1,
9841858×
            _ => 2 * bytes,
985
        }
9864004×
    };
9872×
    let mut out = std::collections::HashMap::new();
9882004×
    for id in wanted {
9892004×
        let Ok(i) = all.binary_search(&id) else {
9900×
            continue;
991
        };
9922004×
        let before = i.checked_sub(1).map_or(0, |j| common(&all[j], &id));
9932004×
        let after = all.get(i + 1).map_or(0, |n| common(&id, n));
9942004×
        out.insert(id, before.max(after) + 1);
995
    }
9962×
    out
9972×
}
998
9991×
fn unique_prefixes(ids: impl Iterator<Item = String>) -> std::collections::HashMap<String, usize> {
10001×
    let mut v: Vec<String> = ids.collect();
10011×
    v.sort();
10021×
    v.dedup();
100319576×
    let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
10041×
    let mut out = std::collections::HashMap::with_capacity(v.len());
10052000×
    for i in 0..v.len() {
10062000×
        let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 };
10072000×
        let after = if i + 1 < v.len() {
10081999×
            common(&v[i], &v[i + 1])
1009
        } else {
10101×
            0
1011
        };
10122000×
        out.insert(v[i].clone(), before.max(after) + 1);
1013
    }
10141×
    out
10151×
}
1016
1017
/// Bookmark, remote bookmark and tag names to show beside the changes they
1018
/// point at. A name is shown on each head of its state; one with more than
1019
/// three heads names too much of the log to help, so it is left out (oxy
1020
/// bookmark list shows it). A remote bookmark at the same state as the
1021
/// local one of that name is not repeated.
10221×
fn reference_labels(repo: &Repo) -> Result<std::collections::HashMap<ChangeHash, Vec<String>>> {
1023
    const MAX_HEADS: usize = 3;
10241×
    let view = repo.view()?;
10251×
    let mut out: std::collections::HashMap<ChangeHash, Vec<String>> = Default::default();
10261×
    let mut add = |heads: Vec<ChangeHash>, label: String| {
10271×
        if heads.len() <= MAX_HEADS {
10282×
            for h in heads {
10292×
                out.entry(h).or_default().push(label.clone());
10302×
            }
10310×
        }
10321×
    };
10331×
    for (name, st) in &view.bookmarks {
10341×
        add(repo.store().get_state(st)?.heads, ui::bookmark(name));
1035
    }
10361×
    for (remote, bookmarks) in &view.remotes {
10370×
        for (name, st) in bookmarks {
10380×
            if view.bookmarks.get(name) == Some(st) {
10390×
                continue;
10400×
            }
10410×
            add(
10420×
                repo.store().get_state(st)?.heads,
10430×
                ui::dim(format!("{remote}/{name}")),
1044
            );
1045
        }
1046
    }
10471×
    for t in repo.tags()? {
10480×
        add(t.heads.clone(), ui::warn(&t.name));
10490×
    }
10501×
    Ok(out)
10511×
}
1052
10531×
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
10541×
    let repo = open()?;
10551×
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
10561×
    if as_json {
10571×
        let files = repo.diff_files(hash.as_ref())?;
10583×
        let items = files.iter().map(|f| {
10593×
            json::obj([
10603×
                ("path", json::s(&f.path)),
10613×
                ("kind", json::s(&f.kind)),
10623×
                ("from", json::opt(f.from.as_deref(), json::s)),
1063
                (
10643×
                    "hunks",
10653×
                    json::arr(f.hunks.iter().map(|h| {
10663×
                        json::obj([
10673×
                            ("base_line", json::n(h.base_line)),
1068
                            (
10693×
                                "added",
10703×
                                json::arr(
10713×
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
1072
                                ),
1073
                            ),
1074
                            (
10753×
                                "removed",
10763×
                                json::arr(h.removed.iter().map(|(n, l)| {
10770×
                                    json::obj([
10780×
                                        ("line", json::n(*n)),
10790×
                                        ("text", json::s(&String::from_utf8_lossy(l))),
10800×
                                    ])
10810×
                                })),
1082
                            ),
1083
                        ])
10843×
                    })),
1085
                ),
1086
            ])
10873×
        });
10881×
        println!(
1089
            "{}",
10901×
            json::obj([
10911×
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
10921×
                ("files", json::arr(items))
1093
            ])
1094
        );
10951×
        return Ok(0);
10960×
    }
10970×
    match hash {
10980×
        Some(h) => {
10990×
            let c = repo.store().get_change(&h)?;
11000×
            let (base, snapshot) = repo.change_base(&c)?;
11010×
            print!("{}", render_change(&c, &base, &snapshot));
1102
        }
1103
        None => {
1104
            // Nothing changed: nothing to show, and no base to load.
11050×
            let Some((wc, base, snapshot)) = repo.working_copy_with_base_unless_unchanged()? else {
11060×
                return Ok(0);
1107
            };
11080×
            let text = {
11090×
                let _t = oxy_core::timing::phase("diff: render the change");
11100×
                render_change(&wc, &base, &snapshot)
1111
            };
11120×
            print!("{text}");
1113
            // The process ends here: freeing the base's tree and graphs
1114
            // one by one would only cost time (about 27 ms on Linux).
11150×
            std::mem::forget((wc, base, snapshot));
1116
        }
1117
    }
11180×
    Ok(0)
11191×
}
1120
11212×
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
11222×
    let repo = open()?;
11232×
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
11242×
    let bytes = match repo.file_at(path, heads.as_deref()) {
11252×
        Ok(b) => b,
1126
        // -r CHANGE reads that change's dependency closure, not the
1127
        // bookmark it is on: say so when the bookmark has the file
1128
        // (oxygen#76).
11290×
        Err(e) => match change {
11300×
            Some(c)
11310×
                if !repo.view()?.bookmarks.contains_key(c)
11320×
                    && repo.tag_heads(c)?.is_none()
11330×
                    && repo.file_at(path, None).is_ok() =>
1134
            {
11350×
                anyhow::bail!(
1136
                    "{path} is not in {c}'s dependency closure (the change and what it \
1137
                     depends on); it is on the bookmark: try -r {}, or --at-op OP for the \
1138
                     state at an operation",
1139
                    repo.config.bookmark
1140
                )
1141
            }
11420×
            _ => return Err(e.into()),
1143
        },
1144
    };
1145
    use std::io::Write as _;
11462×
    std::io::stdout().write_all(&bytes)?;
11472×
    Ok(0)
11482×
}
1149
11501×
pub fn root(as_json: bool) -> Result<i32> {
11511×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
11520×
        if as_json {
11530×
            println!("null");
11540×
        }
11550×
        return Ok(1);
1156
    };
11571×
    if as_json {
11581×
        println!(
11591×
            "{}",
11601×
            json::obj([
11611×
                ("root", json::s(&repo.root().to_string_lossy())),
11621×
                ("workspace", json::s(&repo.workspace().to_hex())),
11631×
                ("bookmark", json::s(&repo.config.bookmark))
11641×
            ])
11651×
        );
11661×
    } else {
11670×
        println!("{}", repo.root().display());
11680×
    }
11691×
    Ok(0)
11701×
}
1171
11721×
pub fn version(as_json: bool) -> Result<i32> {
11731×
    if as_json {
11741×
        println!(
11751×
            "{}",
11761×
            json::obj([
11771×
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
11781×
                // What was built: a release's or install's `oxy describe`,
11791×
                // a Flow build's heads, or "local build".
11801×
                ("build", json::s(env!("OXY_BUILD_ID"))),
11811×
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
11821×
                ("format", json::n(2))
11831×
            ])
11841×
        );
11851×
    } else {
11860×
        println!(
11870×
            "oxy {} (repository format 2, protocol {})",
11880×
            env!("OXY_VERSION_LONG"),
11890×
            oxy_core::protocol::PROTOCOL_VERSION
11900×
        );
11910×
    }
11921×
    Ok(0)
11931×
}
1194
11952×
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
11962×
    let repo = open()?;
11972×
    if paths.is_empty() && hunks.is_empty() {
11980×
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
11992×
    }
12002×
    let mut n = 0;
12012×
    if !hunks.is_empty() {
12021×
        n += repo.discard_hunks(hunks)?;
12031×
    }
12042×
    if !paths.is_empty() {
12051×
        n += repo.discard(paths)?;
12061×
    }
12072×
    println!(
1208
        "{} {} restored to the working copy's base",
12092×
        ui::done("Discarded"),
12102×
        plural(n, "path")
1211
    );
12122×
    Ok(0)
12132×
}
1214
12152×
pub fn hunks(as_json: bool) -> Result<i32> {
12162×
    let repo = open()?;
12172×
    let (_, hunks) = repo.hunks()?;
12182×
    if as_json {
12192×
        println!(
1220
            "{}",
12215×
            json::arr(hunks.iter().map(|h| json::obj([
12225×
                ("index", json::n(h.index)),
12235×
                ("path", json::s(&h.path)),
12245×
                ("text", json::s(&h.text))
12255×
            ])))
1226
        );
12272×
        return Ok(0);
12280×
    }
12290×
    if hunks.is_empty() {
12300×
        println!(
12310×
            "{}",
12320×
            ui::dim("No hunks: the working copy matches its base.")
12330×
        );
12340×
    }
12350×
    for h in &hunks {
12360×
        println!(
1237
            "{} {}",
12380×
            ui::section(format!("hunk {}", h.index)),
12390×
            ui::path(&h.path)
1240
        );
12410×
        for line in h.text.lines() {
12420×
            let styled = if line.starts_with('+') {
12430×
                ui::ok(line)
12440×
            } else if line.starts_with('-') {
12450×
                ui::err(line)
1246
            } else {
12470×
                ui::dim(line)
1248
            };
12490×
            println!("  {styled}");
1250
        }
1251
    }
12520×
    Ok(0)
12532×
}
1254
12553×
pub fn show(change: Option<&str>, revset: Option<&str>, stat: bool, as_json: bool) -> Result<i32> {
12563×
    let repo = open()?;
12573×
    repo.snapshot_status("oxy show")?;
12583×
    let Some(r) = revset else {
12593×
        let h = repo.resolve_change(change.unwrap_or("@"))?;
12603×
        return show_one(&repo, h, as_json, false, stat);
1261
    };
1262
    // Several changes: a JSON array, or the changes one after another.
12630×
    let hashes = repo.revset(r)?.hashes;
12640×
    if as_json {
12650×
        print!("[");
12660×
        for (i, h) in hashes.iter().enumerate() {
12670×
            if i > 0 {
12680×
                print!(",");
12690×
            }
12700×
            show_one(&repo, *h, true, true, stat)?;
1271
        }
12720×
        println!("]");
12730×
        return Ok(0);
12740×
    }
12750×
    if hashes.is_empty() {
12760×
        println!("{}", ui::dim(format!("No change matches {r:?}.")));
12770×
        return Ok(0);
12780×
    }
12790×
    for (i, h) in hashes.iter().enumerate() {
12800×
        if i > 0 {
12810×
            println!();
12820×
        }
12830×
        show_one(&repo, *h, false, false, stat)?;
1284
    }
12850×
    Ok(0)
12863×
}
1287
1288
/// Lines added and removed in one file's diff.
12892×
fn counts(f: &oxy_core::repo::FileDiff) -> (usize, usize) {
12902×
    f.hunks
12912×
        .iter()
12922×
        .fold((0, 0), |(a, r), h| (a + h.added.len(), r + h.removed.len()))
12932×
}
1294
1295
/// What `--stat` prints (oxygen#119): each file the change touched, its
1296
/// lines added and removed, then the total.
12971×
fn print_stat(files: &[oxy_core::repo::FileDiff]) {
12981×
    let width = files
12991×
        .iter()
13001×
        .map(|f| f.path.chars().count())
13011×
        .max()
13021×
        .unwrap_or(0)
13031×
        .min(60);
13041×
    let (mut added, mut removed) = (0, 0);
13051×
    for f in files {
13061×
        let (a, r) = counts(f);
13071×
        added += a;
13081×
        removed += r;
13091×
        let path = match &f.from {
13100×
            Some(from) => format!("{from} → {}", f.path),
13111×
            None => f.path.clone(),
1312
        };
13131×
        println!(
1314
            " {path:<width$}  {} {}  {}",
13151×
            ui::ok(format!("{:>6}", format!("+{a}"))),
13161×
            ui::err(format!("{:>6}", format!("-{r}"))),
13171×
            ui::dim(&f.kind)
1318
        );
1319
    }
13201×
    println!(
1321
        " {}",
13221×
        ui::dim(format!(
1323
            "{} changed, {added} added, {removed} removed",
13241×
            plural(files.len(), "file")
1325
        ))
1326
    );
13271×
}
1328
1329
/// One change, as `oxy show` prints it; `inline` JSON goes without its
1330
/// newline, for an array. `stat` lists the files instead of the diff.
13313×
fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool, stat: bool) -> Result<i32> {
13323×
    let c = repo.store().get_change(&h)?;
13333×
    if as_json {
13341×
        let files = repo.diff_files(Some(&h))?;
13351×
        let heads = repo.bookmark_heads()?;
13361×
        let entry = oxy_core::repo::LogEntry {
13371×
            hash: h,
13381×
            change: oxy_core::state::ChangeMeta::of(&c),
13391×
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
13401×
            is_head: heads.contains(&h),
13411×
        };
13421×
        let mut body = log_entry_json(repo, &entry)?;
13431×
        body.pop();
13441×
        body.push_str(&format!(
1345
            ",{}:{}}}",
13461×
            json::s("files"),
13471×
            json::arr(files.iter().map(|f| {
13481×
                let (a, r) = counts(f);
13491×
                json::obj([
13501×
                    ("path", json::s(&f.path)),
13511×
                    ("kind", json::s(&f.kind)),
13521×
                    ("from", json::opt(f.from.as_deref(), json::s)),
13531×
                    ("added", a.to_string()),
13541×
                    ("removed", r.to_string()),
13551×
                ])
13561×
            }))
1357
        ));
13581×
        if inline {
13590×
            print!("{body}");
13601×
        } else {
13611×
            println!("{body}");
13621×
        }
13631×
        return Ok(0);
13642×
    }
13652×
    println!(
1366
        "{} {} {}",
13672×
        ui::section("change"),
13682×
        ui::id(short_id(&c)),
13692×
        ui::hash(format!("#{h}"))
1370
    );
13712×
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1372
    // Fetched but not pulled (oxygen#56): say where it is.
13732×
    if let Some(at) = repo.remote_only_location(&h)? {
13740×
        println!(
13750×
            "{}",
13760×
            ui::kv(
13770×
                "only in",
13780×
                ui::warn(format!(
13790×
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
13800×
                ))
13810×
            )
13820×
        );
13832×
    }
13842×
    let meta = oxy_core::state::ChangeMeta::of(&c);
13852×
    let status = repo.authenticate_change_known(&h, Some(&meta))?;
13862×
    println!("{}", ui::kv("author", ui::author(author_name(repo, &meta))));
13872×
    if let Some(agent) = via(repo, &status, &meta.author) {
13880×
        println!("{}", ui::kv("via", agent.line()));
13892×
    }
13902×
    println!(
1391
        "{}",
13922×
        ui::kv(
13932×
            "date",
13942×
            format!(
1395
                "{} {}",
13962×
                when(c.hlc.wall_ms),
13972×
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1398
            )
1399
        )
1400
    );
14012×
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
14022×
    println!("{}", ui::kv("sig", signature_line(repo, &h)?));
14032×
    println!();
14045×
    for line in (if c.message.is_empty() {
14050×
        "(no description)"
1406
    } else {
14072×
        &c.message
1408
    })
14092×
    .lines()
14105×
    {
14115×
        println!("    {line}");
14125×
    }
14132×
    println!();
14142×
    if stat {
14151×
        print_stat(&repo.diff_files(Some(&h))?);
1416
    } else {
14171×
        print!("{}", repo.describe_change(&h)?);
1418
    }
14192×
    Ok(0)
14203×
}
1421
14220×
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
14230×
    let repo = open()?;
1424
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1425
    // BRANCH` is: checking its files out under another bookmark's name
1426
    // made the next commit move the wrong bookmark (oxygen#60).
14270×
    if let [name] = changes {
14280×
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
14290×
            drop(repo);
14300×
            return bookmark_switch(name, discard, carry);
14310×
        }
14320×
    }
14330×
    let heads = if changes.is_empty() {
14340×
        repo.bookmark_heads()?
1435
    } else {
14360×
        let mut heads = Vec::new();
14370×
        for c in changes {
14380×
            heads.extend(repo.resolve_heads(c)?);
1439
        }
14400×
        heads
1441
    };
14420×
    let spec = if changes.is_empty() {
14430×
        repo.config.bookmark.clone()
1444
    } else {
14450×
        changes.join(" ")
1446
    };
14470×
    let sp = ui::spinner(&format!("Checking out {spec}…"));
14480×
    let command = format!("oxy checkout {spec}");
14490×
    let (r, carried) = if carry {
14500×
        repo.checkout_carry(&heads, &spec, &command)?
1451
    } else {
14520×
        (repo.checkout(&heads, discard, &command)?, vec![])
1453
    };
14540×
    sp.done(&format!(
1455
        "{} on {}: {} written, {} removed{}",
14560×
        ui::done("Working copy"),
14570×
        ui::bookmark(&spec),
14580×
        plural(r.written, "file"),
1459
        r.removed,
14600×
        if carried.is_empty() {
14610×
            String::new()
1462
        } else {
14630×
            format!("; carried {}", plural(carried.len(), "changed path"))
1464
        }
1465
    ));
14660×
    print_removed(&r);
14670×
    for n in &r.notes {
14680×
        println!("  {} {n}", ui::note());
14690×
    }
14700×
    print_kept_both(&r);
14710×
    if r.conflicted {
14720×
        println!(
14730×
            "  {} {}",
14740×
            ui::caution(),
14750×
            ui::warn("this state has conflicts; see oxy status")
14760×
        );
14770×
    }
14780×
    where_now(&repo);
14790×
    Ok(0)
14800×
}
1481
1482
/// Union files (`merge=union`, oxygen#145) a checkout settled itself.
14833×
fn print_kept_both(r: &oxy_core::repo::CheckoutReport) {
14843×
    for k in &r.kept_both {
14850×
        let how = if k.identical.len() == k.settled.len() {
14860×
            "kept one of its identical sides"
14870×
        } else if k.identical.is_empty() {
14880×
            "kept both sides (merge=union)"
1489
        } else {
14900×
            "kept one of identical sides and both of others (merge=union)"
1491
        };
14920×
        println!(
1493
            "  {} settled {}: {how}; the next commit records it",
14940×
            ui::note(),
14950×
            ui::path(&k.path)
1496
        );
1497
    }
14983×
}
1499
15001×
pub fn resolve(paths: &[String], both: bool, reverse: bool, as_json: bool) -> Result<i32> {
15011×
    let repo = open()?;
15021×
    let mut snap = repo.snapshot("oxy resolve")?;
15031×
    let paths: Vec<String> = paths
15041×
        .iter()
15051×
        .map(|p| p.trim_start_matches("./").trim_end_matches('/').to_string())
15061×
        .collect();
15071×
    if both {
1508
        // Adjacent insertions (oxygen#121): every side kept, in order.
15090×
        let kept = repo.keep_both(&snap, &paths, reverse)?;
15100×
        if !as_json {
15110×
            for k in &kept {
15120×
                if !k.settled.is_empty() {
15130×
                    let n: Vec<String> = k.settled.iter().map(|n| n.to_string()).collect();
15140×
                    println!("kept both  {}: conflict {}", k.path, n.join(", "));
15150×
                }
15160×
                for (n, why) in &k.left {
15170×
                    println!("markers    {}: conflict {n}: {why}", k.path);
15180×
                }
1519
            }
15200×
        }
15210×
        snap = repo.snapshot("oxy resolve")?;
15221×
    } else if !paths.is_empty() {
1523
        // A replace conflict has no markers to edit out: the user says which
1524
        // content wins (oxygen#140, spec §9.3), and the snapshot builds it.
15250×
        repo.choose_resolutions(&snap.base_snapshot, &paths)?;
15260×
        snap = repo.snapshot("oxy resolve")?;
15271×
    }
15281×
    if as_json {
15291×
        println!("{}", repo.status_json(&snap)?);
15301×
        return Ok(if snap.base_snapshot.is_conflicted() {
15310×
            2
1532
        } else {
15331×
            0
1534
        });
15350×
    }
15360×
    if !snap.base_snapshot.is_conflicted() {
15370×
        println!("The working copy's base has no conflicts.");
15380×
        return Ok(0);
15390×
    }
15400×
    let mut remaining = 0;
15410×
    for (p, f) in &snap.base_snapshot.files {
15420×
        if !f.is_conflicted() {
15430×
            continue;
15440×
        }
15450×
        match snap
15460×
            .statuses
15470×
            .iter()
15480×
            .find(|s| s.path == *p)
15490×
            .map(|s| s.status)
1550
        {
15510×
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
15520×
            Some(ChangeStatus::ConflictEdited) => {
15530×
                remaining += 1;
15540×
                println!("markers    {p}");
15550×
            }
15560×
            _ => {
15570×
                remaining += 1;
15580×
                println!("unresolved {p}");
15590×
            }
1560
        }
1561
    }
15620×
    for c in &snap.base_snapshot.tree.conflicts {
15630×
        remaining += 1;
15640×
        println!("tree       {c:?}");
15650×
    }
15660×
    if remaining == 0 {
15670×
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
15680×
        Ok(0)
1569
    } else {
15700×
        Ok(2)
1571
    }
15721×
}
1573
15740×
pub fn undo() -> Result<i32> {
15750×
    let repo = open()?;
15760×
    let u = repo.undo()?;
15770×
    println!("{} {}", ui::done("Undone:"), u.command);
15780×
    for c in &u.changes {
15790×
        println!("  {} {}", ui::note(), change_words(&repo, c));
15800×
    }
15810×
    if u.others_kept > 0 {
15820×
        let s = if u.others_kept == 1 { "" } else { "s" };
15830×
        println!(
1584
            "  {} {}",
15850×
            ui::note(),
15860×
            ui::dim(format!(
1587
                "{} newer operation{s} from other workspaces left as they are",
1588
                u.others_kept
1589
            ))
1590
        );
15910×
    }
15920×
    for (bookmark, remote) in &u.pushed {
15930×
        println!(
15940×
            "  {} {}",
15950×
            ui::caution(),
15960×
            ui::warn(format!(
15970×
                "{remote}/{bookmark} already has what this undid: undone here only; the next push of {bookmark} needs --force to take it back there"
15980×
            ))
15990×
        );
16000×
    }
16010×
    where_now(&repo);
16020×
    Ok(0)
16030×
}
1604
16051×
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
16061×
    let repo = open()?;
16071×
    let ops = repo.op_log()?;
1608
    // What each operation changed, against the one before it.
160911×
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
161011×
        match ops.get(i + 1) {
161110×
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
16121×
            None => Ok(vec![]),
1613
        }
161411×
    };
16151×
    if as_json {
16161×
        let mut items = Vec::new();
161711×
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
161811×
            let summary: Vec<String> = changes_of(i)?
161911×
                .iter()
162011×
                .map(|c| change_words(&repo, c))
162111×
                .collect();
162211×
            items.push(json::obj([
162311×
                ("id", json::s(&r.to_hex())),
162411×
                ("when_ms", json::n(op.hlc.wall_ms)),
162511×
                ("command", json::s(&op.command)),
162611×
                ("snapshot", json::b(op.is_snapshot())),
162711×
                ("current", json::b(i == 0)),
162811×
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1629
            ]));
1630
        }
16311×
        println!("{}", json::arr(items));
16321×
        return Ok(0);
16330×
    }
16340×
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
16350×
    let id = |r: &oxy_core::hash::ObjectRef| {
16360×
        let hex = r.to_hex();
16370×
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
16380×
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
16390×
    };
16400×
    let rail = ui::dim(ui::glyph("│", "|"));
16410×
    let (mut i, mut shown) = (0, 0);
16420×
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
16430×
        let (r, op) = &ops[i];
16440×
        let bullet = if i == 0 {
16450×
            ui::ok(ui::glyph("@", "@"))
1646
        } else {
16470×
            ui::dim(ui::glyph("○", "o"))
1648
        };
1649
        // A run of snapshots folds into one entry.
16500×
        let mut run = 1;
16510×
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
16520×
            run += 1;
16530×
        }
16540×
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
16550×
        if op.is_snapshot() {
16560×
            let span = if run > 1 {
16570×
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1658
            } else {
16590×
                String::new()
1660
            };
16610×
            println!(
1662
                "{bullet}  {}{} {when}",
16630×
                id(r),
16640×
                if span.is_empty() {
16650×
                    String::new()
1666
                } else {
16670×
                    format!(" {span}")
1668
                }
1669
            );
16700×
            println!(
1671
                "{rail}  {}",
16720×
                ui::dim(if run == 1 {
16730×
                    "working-copy snapshot".to_string()
1674
                } else {
16750×
                    format!("{run} working-copy snapshots")
1676
                })
1677
            );
1678
        } else {
16790×
            println!("{bullet}  {} {when}", id(r));
16800×
            let words: Vec<String> = changes_of(i)?
16810×
                .iter()
16820×
                .map(|c| change_words(&repo, c))
16830×
                .collect();
16840×
            let summary = if words.is_empty() {
16850×
                if i + 1 == ops.len() {
16860×
                    "created the repository".to_string()
1687
                } else {
16880×
                    "no bookmark or working-copy change".to_string()
1689
                }
1690
            } else {
16910×
                words.join("; ")
1692
            };
16930×
            println!(
1694
                "{rail}  {}",
16950×
                if i == 0 {
16960×
                    ui::subject(&summary)
1697
                } else {
16980×
                    summary
1699
                }
1700
            );
17010×
            let cmd = op.command.lines().next().unwrap_or("");
17020×
            let cmd: String = cmd.chars().take(100).collect();
17030×
            println!("{rail}  {}", ui::dim(cmd));
1704
        }
17050×
        i += run;
17060×
        shown += 1;
1707
    }
17080×
    if i < ops.len() {
17090×
        println!(
17100×
            "{}",
17110×
            ui::dim(format!(
17120×
                "{} {} older; pass -n to see more",
17130×
                ui::glyph("…", "..."),
17140×
                plural(ops.len() - i, "operation")
17150×
            ))
17160×
        );
17170×
    }
17180×
    Ok(0)
17191×
}
1720
1721
/// One change an operation made, in words.
172211×
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1723
    use oxy_core::repo::ViewChange::*;
17242×
    match c {
17250×
        BookmarkCreated { name, heads } => {
17260×
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1727
        }
17280×
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
17292×
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
17301×
        BookmarkMoved { name, from, to } => format!(
1731
            "{name}: {from} {} {}",
17321×
            ui::glyph("→", "->"),
17331×
            plural(*to, "head")
1734
        ),
17351×
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
17360×
        TagCreated { name } => format!("tagged {name}"),
17370×
        TagDeleted { name } => format!("removed tag {name}"),
17380×
        Policy => "trust policy changed".to_string(),
17398×
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
17408×
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
17410×
            Err(_) => "working copy moved".to_string(),
1742
        },
1743
    }
174411×
}
1745
17460×
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
17470×
    let repo = open()?;
17480×
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
17490×
    let r = repo.op_restore(op, discard)?;
17500×
    sp.done(&format!(
17510×
        "{} to operation {} {}",
17520×
        ui::done("Restored"),
17530×
        ui::hash(r.op.short(12)),
17540×
        ui::dim(r.command.lines().next().unwrap_or(""))
17550×
    ));
17560×
    println!(
1757
        "  {} {}",
17580×
        ui::note(),
17590×
        ui::dim(format!(
1760
            "{} written, {} removed; oxy undo goes back again",
17610×
            plural(r.checkout.written, "file"),
1762
            r.checkout.removed
1763
        ))
1764
    );
17650×
    where_now(&repo);
17660×
    Ok(0)
17670×
}
1768
17690×
pub fn op_revert(op: &str) -> Result<i32> {
17700×
    let repo = open()?;
17710×
    let r = repo.op_revert(op)?;
17720×
    let view = repo.view()?;
17730×
    let names: Vec<String> = r
17740×
        .reverted
17750×
        .iter()
17760×
        .map(|n| {
17770×
            if view.bookmarks.contains_key(n) {
17780×
                ui::bookmark(n)
1779
            } else {
17800×
                format!("{} (removed)", ui::bookmark(n))
1781
            }
17820×
        })
17830×
        .collect();
17840×
    println!(
1785
        "{} operation {} {}",
17860×
        ui::done("Reverted"),
17870×
        ui::hash(r.op.short(12)),
17880×
        ui::dim(r.command.lines().next().unwrap_or(""))
1789
    );
17900×
    println!(
1791
        "  {} {}",
17920×
        ui::note(),
17930×
        ui::dim(format!("as before it: {}", names.join(", ")))
1794
    );
17950×
    if !r.kept.is_empty() {
17960×
        println!(
17970×
            "  {} {}",
17980×
            ui::caution(),
17990×
            ui::warn(format!(
18000×
                "left as they are, having moved again since: {}",
18010×
                r.kept.join(", ")
18020×
            ))
18030×
        );
18040×
    }
18050×
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
18060×
        println!(
18070×
            "  {} {}",
18080×
            ui::note(),
18090×
            ui::dim("the working copy has work of its own: oxy checkout to move it")
18100×
        );
18110×
    }
18120×
    where_now(&repo);
18130×
    Ok(0)
18140×
}
1815
1816
/// Where the working copy and bookmark are now, after a command moved
1817
/// them (as jj says "Working copy now at").
181831×
pub fn where_now(repo: &Repo) {
181931×
    let Ok((_, wc)) = repo.working_copy() else {
18200×
        return;
1821
    };
182231×
    let heads = repo.bookmark_heads().unwrap_or_default();
182331×
    let newest = heads
182431×
        .iter()
182543×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
182631×
        .max_by_key(|(m, _)| m.hlc);
182731×
    println!(
1828
        "  {} {}",
182931×
        ui::dim(format!("{:<13}", "Working copy")),
183031×
        ui::id(wc.change_id.short(8))
1831
    );
183231×
    let tail = match newest {
183331×
        Some((m, _)) => format!(
1834
            ", newest {} {}",
183531×
            ui::id(m.change_id.short(8)),
183631×
            subject_of(&m.message)
1837
        ),
18380×
        None => String::new(),
1839
    };
184031×
    println!(
1841
        "  {} {}: {}{tail}",
184231×
        ui::dim(format!("{:<13}", "Bookmark")),
184331×
        ui::bookmark(&repo.config.bookmark),
184431×
        plural(heads.len(), "head")
1845
    );
184631×
}
1847
18480×
pub fn gc(now: bool, expire_snapshots: bool) -> Result<i32> {
18490×
    let mut repo = open()?;
18500×
    if expire_snapshots {
18510×
        repo.config.snapshot_retention_days = 0;
18520×
    }
18530×
    let sp = ui::spinner("Packing and pruning…");
18540×
    let r = repo.gc_with(now, &mut |phase| sp.set(&format!("{phase}…")))?;
18550×
    sp.clear();
18560×
    if r.packed.objects > 0 {
18570×
        println!(
18580×
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
18590×
            plural(r.packed.objects, "object"),
18600×
            r.packed.raw_bytes,
18610×
            r.packed.packed_bytes,
18620×
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
18630×
        );
18640×
    }
18650×
    println!(
1866
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
18670×
        plural(r.reachable, "object"),
18680×
        plural(r.pruned.objects, "unreachable object"),
1869
        r.pruned.bytes,
18700×
        if r.pruned.deferred > 0 {
18710×
            format!(
1872
                "; {} deferred by the grace period (use --now)",
18730×
                plural(r.pruned.deferred, "object")
1874
            )
1875
        } else {
18760×
            String::new()
1877
        },
18780×
        if r.merged_packs > 0 {
18790×
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1880
        } else {
18810×
            String::new()
1882
        },
18830×
        plural(repo.store().pack_count(), "pack")
1884
    );
1885
    // What earlier repacks replaced stays an hour for readers still using
1886
    // it (oxygenhub#249); a collection after that deletes it.
18870×
    let kept = if r.retired.kept > 0 {
18880×
        format!(
1889
            "{} retired less than an hour ago kept for readers",
18900×
            plural(r.retired.kept, "file")
1891
        )
1892
    } else {
18930×
        String::new()
1894
    };
18950×
    if r.retired.packs + r.retired.loose > 0 {
18960×
        println!(
1897
            "Deleted {} and {} retired by earlier repacks{}.",
18980×
            plural(r.retired.packs, "pack"),
18990×
            plural(r.retired.loose, "loose object"),
19000×
            if kept.is_empty() {
19010×
                String::new()
1902
            } else {
19030×
                format!("; {kept}")
1904
            }
1905
        );
19060×
    } else if !kept.is_empty() {
19070×
        println!("{kept}.");
19080×
    }
19090×
    Ok(0)
19100×
}
1911
1912
/// `oxy gc --remote NAME`: fold a store remote's bundles into one.
19132×
pub fn gc_remote(name: &str, now: bool) -> Result<i32> {
19142×
    let repo = open()?;
19152×
    let sp = ui::spinner(&format!("Folding {name}'s bundles…"));
19162×
    let r = repo.gc_remote(name, now)?;
19171×
    sp.clear();
19181×
    if r.merged > 0 {
19191×
        println!(
19201×
            "{} {} into one of {} bytes ({})",
19211×
            ui::done("Folded"),
19221×
            plural(r.merged, "bundle"),
19231×
            r.bundle_bytes,
19241×
            plural(r.changes, "change")
19251×
        );
19261×
    } else {
19270×
        println!(
19280×
            "{} {}",
19290×
            ui::note(),
19300×
            ui::dim("nothing to fold: one bundle holds everything")
19310×
        );
19320×
    }
19331×
    println!(
1934
        "  {} {}",
19351×
        ui::note(),
19361×
        ui::dim(format!(
1937
            "removed {}{}",
19381×
            plural(r.deleted, "superseded bundle"),
19391×
            if r.deferred > 0 {
19400×
                format!(
1941
                    "; {} kept for readers that may still fetch them (use --now)",
19420×
                    plural(r.deferred, "bundle")
1943
                )
1944
            } else {
19451×
                String::new()
1946
            }
1947
        ))
1948
    );
19491×
    Ok(0)
19502×
}
1951
1952
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
19530×
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1954
    use oxy_core::repo::Health;
19550×
    let repo = open()?;
19560×
    let sp = ui::spinner(if offline {
19570×
        "Checking…"
1958
    } else {
19590×
        "Checking, and contacting remotes…"
1960
    });
19610×
    let r = repo.doctor(!offline);
19620×
    sp.clear();
19630×
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
19640×
    let word = |h: Health| match h {
19650×
        Health::Ok => "ok",
19660×
        Health::Warn => "warning",
19670×
        Health::Fail => "fail",
19680×
    };
19690×
    if as_json {
19700×
        let checks: Vec<String> = r
19710×
            .checks
19720×
            .iter()
19730×
            .map(|c| {
19740×
                json::obj([
19750×
                    ("area", json::s(&c.area)),
19760×
                    ("health", json::s(word(c.health))),
19770×
                    ("message", json::s(&c.message)),
19780×
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
19790×
                ])
19800×
            })
19810×
            .collect();
19820×
        println!(
1983
            "{}",
19840×
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1985
        );
19860×
        return Ok(code);
19870×
    }
19880×
    let mut last = "";
19890×
    for c in &r.checks {
19900×
        if c.area != last {
19910×
            println!("{}", ui::section(&c.area));
19920×
            last = &c.area;
19930×
        }
19940×
        let mark = match c.health {
19950×
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
19960×
            Health::Warn => ui::caution(),
19970×
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1998
        };
19990×
        println!("  {mark} {}", c.message);
20000×
        if let Some(h) = &c.hint {
20010×
            println!("    {} {}", ui::dim("→"), ui::dim(h));
20020×
        }
2003
    }
20040×
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
20050×
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
20060×
    if fails + warns == 0 {
20070×
        println!("{}", ui::done("Everything looks right."));
20080×
    } else {
20090×
        println!(
2010
            "{} {}, {}.",
20110×
            if fails > 0 {
20120×
                ui::err(ui::glyph("✖", "x"))
2013
            } else {
20140×
                ui::caution()
2015
            },
20160×
            plural(fails, "problem"),
20170×
            plural(warns, "warning")
2018
        );
2019
    }
20200×
    Ok(code)
20210×
}
2022
2023
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
20240×
pub fn fsck(as_json: bool) -> Result<i32> {
2025
    use oxy_core::repo::Severity;
20260×
    let repo = open()?;
20270×
    let sp = ui::spinner("Checking every object…");
20280×
    let r = repo.fsck()?;
20290×
    sp.clear();
20300×
    let code = if r.errors() > 0 { 1 } else { 0 };
20310×
    if as_json {
20320×
        let problems: Vec<String> = r
20330×
            .problems
20340×
            .iter()
20350×
            .map(|p| {
20360×
                json::obj([
2037
                    (
2038
                        "severity",
20390×
                        json::s(match p.severity {
20400×
                            Severity::Error => "error",
20410×
                            Severity::Warning => "warning",
2042
                        }),
2043
                    ),
2044
                    (
20450×
                        "object",
20460×
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
2047
                    ),
20480×
                    ("what", json::s(&p.what)),
2049
                ])
20500×
            })
20510×
            .collect();
20520×
        println!(
2053
            "{}",
20540×
            json::obj([
20550×
                ("ok", json::b(code == 0)),
20560×
                ("objects", json::n(r.objects)),
20570×
                ("ops", json::n(r.ops)),
20580×
                ("changes", json::n(r.changes)),
20590×
                ("signed", json::n(r.signed)),
20600×
                ("unsigned", json::n(r.unsigned)),
20610×
                ("checkpoints", json::n(r.checkpoints)),
20620×
                ("attestations", json::n(r.attestations)),
20630×
                ("errors", json::n(r.errors())),
20640×
                ("warnings", json::n(r.warnings())),
20650×
                ("problems", json::arr(problems)),
20660×
            ])
2067
        );
20680×
        return Ok(code);
20690×
    }
20700×
    println!(
2071
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
20720×
        plural(r.objects, "object"),
20730×
        plural(r.ops, "operation"),
20740×
        plural(r.changes, "change"),
2075
        r.signed,
2076
        r.unsigned,
20770×
        plural(r.checkpoints, "checkpoint"),
20780×
        plural(r.attestations, "attestation"),
2079
    );
20800×
    for p in &r.problems {
20810×
        let obj = p
20820×
            .object
20830×
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
20840×
            .unwrap_or_default();
20850×
        match p.severity {
20860×
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
20870×
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
2088
        }
2089
    }
20900×
    if r.problems.is_empty() {
20910×
        println!("{}", ui::done("No problems found."));
20920×
    } else if code == 0 {
20930×
        println!(
20940×
            "{}",
20950×
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
20960×
        );
20970×
    } else {
20980×
        println!(
20990×
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
21000×
            ui::err(ui::glyph("✖", "x")),
21010×
            plural(r.errors(), "error"),
21020×
            plural(r.warnings(), "warning")
21030×
        );
21040×
    }
21050×
    Ok(code)
21060×
}
2107
2108
/// The head the working copy sits on, for commands that default to it. With
2109
/// several heads beneath the working copy, the most recently made one is
2110
/// chosen and announced.
21110×
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
21120×
    let snap = repo.snapshot_status("oxy")?;
21130×
    let base = snap.base.maximal(&snap.wc.deps);
21140×
    match base.as_slice() {
21150×
        [] => anyhow::bail!("the working copy sits on no change yet"),
21160×
        [h] => Ok(*h),
21170×
        many => {
21180×
            let latest = many
21190×
                .iter()
21200×
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
21210×
                .copied()
21220×
                .unwrap();
21230×
            let c = repo.store().get_change(&latest)?;
21240×
            println!(
2125
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
21260×
                short_id(&c),
21270×
                latest.short(12),
21280×
                many.len()
2129
            );
21300×
            Ok(latest)
2131
        }
2132
    }
21330×
}
2134
2135
/// `oxy describe` without -m: the working copy's name for a build.
21364×
pub fn describe_name(as_json: bool) -> Result<i32> {
21374×
    let repo = open()?;
21384×
    let d = repo.describe_working_copy()?;
21394×
    if as_json {
21403×
        println!(
2141
            "{}",
21423×
            json::obj([
21433×
                ("describe", json::s(&d.line())),
21443×
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
21453×
                ("distance", json::n(d.distance)),
21463×
                ("bookmark", json::s(&d.bookmark)),
21473×
                ("change", json::s(&d.change.to_hex())),
21483×
                ("hash", json::s(&d.hash.to_hex())),
21493×
                ("dirty", json::b(d.dirty)),
2150
            ])
2151
        );
21521×
    } else {
21531×
        println!("{}", d.line());
21541×
    }
21554×
    Ok(0)
21564×
}
2157
21580×
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
21590×
    let repo = open()?;
21600×
    let h = match change {
21610×
        Some(c) => repo.resolve_change(c)?,
21620×
        None => current_head(&repo)?,
2163
    };
21640×
    let new = repo.describe(&h, message)?;
21650×
    let c = repo.store().get_change_meta(&new)?;
21660×
    println!(
2167
        "{} {} {}  {}",
21680×
        ui::done("Described"),
21690×
        ui::id(c.change_id.short(8)),
21700×
        ui::hash(format!("#{}", new.short(12))),
21710×
        ui::subject(subject_of(message))
2172
    );
21730×
    Ok(0)
21740×
}
2175
21760×
pub fn amend(message: Option<&str>, into: Option<&str>, paths: &[String]) -> Result<i32> {
21770×
    let repo = open()?;
21780×
    let before = repo.view()?;
21790×
    let new = match into {
21800×
        Some(spec) => {
21810×
            let target = repo.resolve_change(spec)?;
21820×
            repo.amend_into(&target, message)?
2183
        }
21840×
        None if !paths.is_empty() => repo.amend_paths(message, paths)?,
21850×
        None => repo.amend(message)?,
2186
    };
21870×
    let c = repo.store().get_change_meta(&new)?;
21880×
    println!(
2189
        "{} {} {}  {}",
21900×
        ui::done("Amended"),
21910×
        ui::id(c.change_id.short(8)),
21920×
        ui::hash(format!("#{}", new.short(12))),
21930×
        ui::subject(subject_of(&c.message))
2194
    );
2195
    // Rewriting what a remote already has means the next push replaces it
2196
    // there (oxygen#99): say so now, not when the push is refused.
21970×
    let bookmark = repo.config.bookmark.clone();
21980×
    let (had, has) = (
21990×
        repo.heads_of(&before, &bookmark)?,
22000×
        repo.heads_of(&repo.view()?, &bookmark)?,
2201
    );
22020×
    for (remote, bookmarks) in &before.remotes {
22030×
        let Some(st) = bookmarks.get(&bookmark) else {
22040×
            continue;
2205
        };
22060×
        let theirs = repo.store().get_state(st)?.heads;
22070×
        if theirs.iter().any(|h| had.contains(h) && !has.contains(h)) {
22080×
            println!(
22090×
                "  {} {}",
22100×
                ui::caution(),
22110×
                ui::warn(format!(
22120×
                    "{remote}/{bookmark} has the change as it was: the next push of {bookmark} needs --force to replace it"
22130×
                ))
22140×
            );
22150×
        }
2216
    }
22170×
    where_now(&repo);
22180×
    Ok(0)
22190×
}
2220
22210×
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
22220×
    let repo = open()?;
22230×
    let Some(r) = revset else {
22240×
        let h = repo.resolve_change(change.unwrap_or_default())?;
22250×
        abandon_one(&repo, h)?;
22260×
        where_now(&repo);
22270×
        return Ok(0);
2228
    };
2229
    // A revset: say what it selects, refuse an empty set, ask above a few.
22300×
    let selected = repo.revset(r)?;
22310×
    let wc = repo.working_copy().ok().map(|(h, _)| h);
22320×
    let hashes: Vec<ChangeHash> = selected
22330×
        .hashes
22340×
        .iter()
22350×
        .copied()
22360×
        .filter(|h| Some(*h) != wc)
22370×
        .collect();
22380×
    if hashes.is_empty() {
22390×
        anyhow::bail!("{r:?} selects no change to abandon");
22400×
    }
22410×
    println!(
2242
        "{} {} selects {}:",
22430×
        ui::section("abandon"),
22440×
        ui::id(r),
22450×
        plural(hashes.len(), "change")
2246
    );
22470×
    for h in &hashes {
22480×
        if let Some(m) = selected.metas.get(h) {
22490×
            println!(
22500×
                "  {} {}  {}",
22510×
                ui::id(m.change_id.short(8)),
22520×
                ui::hash(format!("#{}", h.short(12))),
22530×
                subject_of(&m.message)
22540×
            );
22550×
        }
2256
    }
2257
    const ASK_ABOVE: usize = 5;
22580×
    if hashes.len() > ASK_ABOVE && !yes {
22590×
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
22600×
    }
2261
    // Newest first: abandoning a change rewrites what depends on it, so a
2262
    // later member is found again by its ChangeId.
22630×
    let mut done = 0;
22640×
    for h in &hashes {
22650×
        let Some(m) = selected.metas.get(h) else {
22660×
            continue;
2267
        };
22680×
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
22690×
            Ok(h) => h,
22700×
            Err(_) => continue,
2271
        };
22720×
        abandon_one(&repo, now)?;
22730×
        done += 1;
2274
    }
22750×
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
22760×
    where_now(&repo);
22770×
    Ok(0)
22780×
}
2279
22800×
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
22810×
    let c = repo.store().get_change_meta(&h)?;
22820×
    let notes = repo.abandon(&h)?;
22830×
    println!(
2284
        "{} {} {}  {}",
22850×
        ui::done("Abandoned"),
22860×
        ui::id(c.change_id.short(8)),
22870×
        ui::hash(format!("#{}", h.short(12))),
22880×
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
2289
    );
22900×
    for n in notes {
22910×
        println!("  {} {n}", ui::note());
22920×
    }
22930×
    Ok(())
22940×
}
2295
22960×
pub fn checkpoint() -> Result<i32> {
22970×
    let repo = open()?;
22980×
    let sp = ui::spinner("Writing checkpoint…");
22990×
    let (r, changes, bytes) = repo.checkpoint()?;
23000×
    sp.done(&format!(
23010×
        "{} {} of {} ({} bytes) for {}",
23020×
        ui::done("Checkpoint"),
23030×
        ui::hash(format!("#{}", r.short(12))),
23040×
        plural(changes, "change"),
23050×
        bytes,
23060×
        ui::id(&repo.config.bookmark)
23070×
    ));
23080×
    Ok(0)
23090×
}
2310
2311
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
23120×
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
23130×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
23140×
        return Ok(1);
2315
    };
23160×
    let info = repo.quick_status()?;
23170×
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
23180×
        oxy_core::repo::GLYPH_PROMPT_FORMAT
2319
    } else {
23200×
        format
2321
    };
23220×
    let line = match color {
23230×
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
23240×
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
23250×
        Some(_) => info.format_colored(fmt, ("", "")),
23260×
        None => info.format(fmt),
2327
    };
23280×
    println!("{line}");
23290×
    Ok(0)
23300×
}
2331
23320×
pub fn sparse(paths: &[String]) -> Result<i32> {
23330×
    let mut repo = open()?;
23340×
    if paths.is_empty() {
23350×
        if repo.config.sparse_paths.is_empty() {
23360×
            println!("No sparse filter: the whole tree is materialized.");
23370×
        } else {
23380×
            println!("{}", ui::heading("Sparse filter"));
23390×
            for p in &repo.config.sparse_paths {
23400×
                println!("  {}", ui::path(p));
23410×
            }
2342
        }
23430×
        return Ok(0);
23440×
    }
23450×
    let snap = repo.snapshot("oxy sparse")?;
23460×
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
23470×
        anyhow::bail!(
2348
            "the working copy has changes; commit them before changing the sparse filter"
2349
        );
23500×
    }
23510×
    repo.config.set("filter.paths", &paths.join(","))?;
23520×
    repo.save_config()?;
23530×
    let heads = repo.bookmark_heads()?;
23540×
    let sp = ui::spinner("Re-checking out with the new filter…");
23550×
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
23560×
    sp.done(&format!(
23570×
        "{} {}: {} written, {} removed",
23580×
        ui::done("Sparse filter set to"),
23590×
        ui::path(paths.join(",")),
23600×
        plural(r.written, "file"),
23610×
        r.removed
23620×
    ));
23630×
    Ok(0)
23640×
}
2365
23662×
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
23672×
    let repo = open()?;
23682×
    repo.snapshot_status("oxy tag")?;
23692×
    let heads = if changes.is_empty() {
23702×
        repo.bookmark_heads()?
2371
    } else {
23720×
        let mut heads = Vec::new();
23730×
        for c in changes {
23740×
            heads.extend(repo.resolve_heads(c)?);
2375
        }
23760×
        heads
2377
    };
23782×
    let t = repo.tag_create(name, &heads, message)?;
23792×
    println!(
2380
        "{} {} {} {} ({}){}",
23812×
        ui::done("Tagged"),
23822×
        ui::bookmark(&t.name),
23832×
        ui::dim(ui::glyph("→", "->")),
23842×
        ui::hash(format!("#{}", t.state.short(12))),
23852×
        plural(t.heads.len(), "head"),
23862×
        t.signer
23872×
            .map(|s| format!(", signed by {s}"))
23882×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2389
    );
23902×
    Ok(0)
23912×
}
2392
23930×
pub fn tag_delete(name: &str, reason: &str) -> Result<i32> {
23940×
    let repo = open()?;
23950×
    let t = repo.tag_delete(name, reason)?;
23960×
    println!(
2397
        "{} {} {} {}{}",
23980×
        ui::done("Withdrew"),
23990×
        ui::bookmark(&t.name),
24000×
        ui::dim(ui::glyph("→", "->")),
24010×
        ui::hash(format!("#{}", t.state.short(12))),
24020×
        t.signer
24030×
            .map(|s| format!(", signed by {s}"))
24040×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2405
    );
24060×
    println!(
2407
        "  {} {}",
24080×
        ui::note(),
24090×
        ui::dim("`oxy push` sends the withdrawal to a remote that has the tag; the name is not used again")
2410
    );
24110×
    Ok(0)
24120×
}
2413
24141×
pub fn tag_list(as_json: bool) -> Result<i32> {
24151×
    let repo = open()?;
24161×
    let tags = repo.tags()?;
24171×
    if as_json {
24181×
        println!(
2419
            "{}",
24201×
            json::arr(tags.iter().map(|t| {
24211×
                json::obj([
24221×
                    ("name", json::s(&t.name)),
24231×
                    ("state", json::s(&t.state.to_hex())),
24241×
                    ("heads", json::hashes(&t.heads)),
24251×
                    ("message", json::s(&t.message)),
2426
                    (
24271×
                        "signer",
24281×
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2429
                    ),
2430
                ])
24311×
            }))
2432
        );
24331×
        return Ok(0);
24340×
    }
24350×
    if tags.is_empty() {
24360×
        println!("{}", ui::dim("No tags."));
24370×
    }
24380×
    for t in tags {
24390×
        println!(
2440
            "{} {} {}{}{}{}",
24410×
            ui::ok(ui::glyph("⚑", "#")),
24420×
            ui::bookmark(&t.name),
2443
            // The heads, as `oxy log` shows changes, not the state hash.
24440×
            ui::hash(
24450×
                t.heads
24460×
                    .iter()
24470×
                    .map(|h| format!("#{}", h.short(12)))
24480×
                    .collect::<Vec<_>>()
24490×
                    .join(" ")
2450
            ),
24510×
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
24520×
            if t.message.is_empty() {
24530×
                String::new()
2454
            } else {
24550×
                format!("  {}", ui::subject(subject_of(&t.message)))
2456
            },
24570×
            t.signer
24580×
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
24590×
                .unwrap_or_default()
2460
        );
2461
    }
24620×
    Ok(0)
24631×
}
2464
2465
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2466
/// and workspace add take as "be on this bookmark" (oxygen#60).
24670×
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
24680×
    Ok(repo.view()?.bookmarks.contains_key(name)
24690×
        || repo
24700×
            .remote_only_bookmarks()?
24710×
            .iter()
24720×
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
24730×
}
2474
24750×
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
24760×
    let repo = open()?;
2477
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2478
    // this workspace's bookmark with that one's files.
24790×
    if let [name] = changes {
24800×
        if names_bookmark(&repo, name)? {
24810×
            let (local, _) = repo.local_bookmark_for(name)?;
24820×
            let heads = repo.resolve_heads(&local)?;
24830×
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
24840×
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
24850×
            sp.done(&format!(
24860×
                "{} {} (workspace {}) on {}",
24870×
                ui::done("Workspace created at"),
24880×
                ui::path(ws.root().display()),
24890×
                ui::id(ws.workspace().short(8)),
24900×
                ui::bookmark(&local)
24910×
            ));
24920×
            return Ok(0);
24930×
        }
24940×
    }
24950×
    let heads = if changes.is_empty() {
24960×
        None
2497
    } else {
24980×
        let mut heads = Vec::new();
24990×
        for c in changes {
25000×
            heads.extend(repo.resolve_heads(c)?);
2501
        }
25020×
        Some(heads)
2503
    };
25040×
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
25050×
    let ws = repo.workspace_add(path, heads.as_deref())?;
25060×
    sp.done(&format!(
25070×
        "{} {} (workspace {})",
25080×
        ui::done("Workspace created at"),
25090×
        ui::path(ws.root().display()),
25100×
        ui::id(ws.workspace().short(8))
25110×
    ));
25120×
    Ok(0)
25130×
}
2514
25151×
pub fn workspace_list(as_json: bool) -> Result<i32> {
25161×
    let repo = open()?;
25171×
    if as_json {
25181×
        println!(
2519
            "{}",
25201×
            json::arr(repo.workspaces()?.iter().map(|w| {
25211×
                json::obj([
25221×
                    ("id", json::s(&w.id.to_hex())),
25231×
                    ("path", json::s(&w.path.to_string_lossy())),
25241×
                    ("current", json::b(w.current)),
2525
                    (
25261×
                        "working_copy",
25271×
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2528
                    ),
2529
                ])
25301×
            }))
2531
        );
25321×
        return Ok(0);
25330×
    }
25340×
    for w in repo.workspaces()? {
25350×
        println!(
2536
            "{} {} {}{}",
25370×
            if w.current {
25380×
                ui::ok(ui::glyph("●", "*"))
2539
            } else {
25400×
                ui::dim(ui::glyph("○", "o"))
2541
            },
25420×
            ui::id(w.id.short(8)),
25430×
            ui::path(w.path.display()),
25440×
            w.working_copy
25450×
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
25460×
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2547
        );
2548
    }
25490×
    Ok(0)
25501×
}
2551
25520×
pub fn workspace_forget(spec: &str) -> Result<i32> {
25530×
    let repo = open()?;
25540×
    let all = repo.workspaces()?;
25550×
    let target = std::fs::canonicalize(spec).ok();
25560×
    let matches: Vec<_> = all
25570×
        .iter()
25580×
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
25590×
        .collect();
25600×
    let w = match matches.as_slice() {
25610×
        [w] => *w,
25620×
        [] => anyhow::bail!("no workspace matches {spec:?}"),
25630×
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2564
    };
25650×
    repo.workspace_forget(&w.id)?;
25660×
    println!(
2567
        "{} workspace {} at {}; its files were left in place.",
25680×
        ui::done("Forgot"),
25690×
        ui::id(w.id.short(8)),
25700×
        ui::path(w.path.display())
2571
    );
25720×
    Ok(0)
25730×
}
2574
25750×
pub fn lock(path: &str) -> Result<i32> {
25760×
    let repo = open()?;
25770×
    repo.lock_path(path)?;
25780×
    println!(
2579
        "{} {} {}",
25800×
        ui::done("Locked"),
25810×
        ui::path(path),
25820×
        ui::dim("(advisory, local)")
2583
    );
25840×
    Ok(0)
25850×
}
2586
25870×
pub fn unlock(path: &str) -> Result<i32> {
25880×
    let repo = open()?;
25890×
    repo.unlock_path(path)?;
25900×
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
25910×
    Ok(0)
25920×
}
2593
25940×
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
25950×
    let repo = open()?;
25960×
    let h = repo.resolve_change(change)?;
25970×
    let (h1, h2) = repo.split(&h, paths)?;
25980×
    let c1 = repo.store().get_change_meta(&h1)?;
25990×
    let c2 = repo.store().get_change_meta(&h2)?;
26000×
    println!(
2601
        "{} into {} {} and {} {}",
26020×
        ui::done("Split"),
26030×
        ui::id(c1.change_id.short(8)),
26040×
        ui::hash(format!("#{}", h1.short(12))),
26050×
        ui::id(c2.change_id.short(8)),
26060×
        ui::hash(format!("#{}", h2.short(12)))
2607
    );
26080×
    Ok(0)
26090×
}
2610
26116×
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
26126×
    let mut heads = Vec::new();
26136×
    for c in changes {
26146×
        heads.extend(repo.resolve_heads(c)?);
2615
    }
26166×
    Ok(heads)
26176×
}
2618
26196×
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
26206×
    let repo = open()?;
26216×
    repo.snapshot_status("oxy bookmark create")?;
26226×
    let heads = if changes.is_empty() {
26233×
        None
2624
    } else {
26253×
        let named = heads_from(&repo, changes)?;
26263×
        let (_, wc) = repo.working_copy()?;
26273×
        let gap = repo.state_gap(&wc.deps, &named)?;
26283×
        if upto {
26291×
            Some(gap.upto)
26302×
        } else if only || gap.earlier.is_empty() {
26311×
            Some(named)
2632
        } else {
26331×
            anyhow::bail!(
2634
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2635
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2636
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2637
                 or --only for just {0} and what it depends on.",
26381×
                changes.join(" "),
26391×
                plural(gap.earlier.len(), "change"),
26401×
                listed_changes(&repo, &gap.earlier)
2641
            );
2642
        }
2643
    };
26445×
    let heads = repo.bookmark_create(name, heads.as_deref())?;
26455×
    println!(
2646
        "{} bookmark {} {} {}",
26475×
        ui::done("Created"),
26485×
        ui::bookmark(name),
26495×
        ui::dim(ui::glyph("→", "->")),
26505×
        ui::dim(plural(heads.len(), "head"))
2651
    );
26525×
    println!(
2653
        "  {} {}",
26545×
        ui::note(),
26555×
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2656
    );
26575×
    Ok(0)
26586×
}
2659
2660
/// Up to five changes, newest last, as `  #hash subject` lines.
26612×
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
26622×
    let shown = changes.len().min(5);
26632×
    let mut lines: Vec<String> = changes[changes.len() - shown..]
26642×
        .iter()
26652×
        .map(|h| {
26662×
            let subject = repo
26672×
                .store()
26682×
                .get_change(h)
26692×
                .map(|c| subject_of(&c.message).to_string())
26702×
                .unwrap_or_default();
26712×
            format!("  #{} {subject}", h.short(12))
26722×
        })
26732×
        .collect();
26742×
    if changes.len() > shown {
26750×
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
26762×
    }
26772×
    lines.join("\n")
26782×
}
2679
26803×
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
26813×
    let repo = open()?;
26823×
    repo.snapshot_status("oxy bookmark set")?;
26833×
    let named = heads_from(&repo, changes)?;
2684
    // What the bookmark holds now and the new heads would leave out.
26853×
    let current = repo
26863×
        .bookmarks()?
26873×
        .into_iter()
26886×
        .find(|b| b.name == name)
26893×
        .map(|b| b.heads)
26903×
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
26913×
    let gap = repo.state_gap(&current, &named)?;
2692
    // A fast-forward: the new heads hold the bookmark's newest head, so
2693
    // what they leave out is older work nothing since has built on, such
2694
    // as an early change no later one depends on (oxygen#78). Keep it, as
2695
    // --upto does, and say so.
26963×
    let newest = current
26973×
        .iter()
26988×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m.hlc, *h)))
26993×
        .max()
27003×
        .map(|(_, h)| h);
2701
    // Ahead, too: a head the bookmark holds already (it would only drop
2702
    // the others) is not a move forward.
27033×
    let ahead = repo
27043×
        .load_state_history(&current)
27053×
        .is_ok_and(|st| named.iter().any(|h| !st.contains(h)));
27063×
    let forward = !only
27073×
        && ahead
27081×
        && !gap.earlier.is_empty()
27091×
        && newest.is_some_and(|n| {
27101×
            repo.load_state_history(&named)
27111×
                .is_ok_and(|st| st.contains(&n))
27121×
        });
27133×
    let heads = if upto {
27141×
        gap.upto
27152×
    } else if forward {
27161×
        println!(
2717
            "  {} {}",
27181×
            ui::note(),
27191×
            ui::dim(format!(
2720
                "{} builds on {name}'s newest head; keeping {} it holds that {0} does not depend on",
27211×
                changes.join(" "),
27221×
                plural(gap.earlier.len(), "change")
2723
            ))
2724
        );
27251×
        gap.upto
27261×
    } else if only || gap.earlier.is_empty() {
27270×
        named
2728
    } else {
27291×
        anyhow::bail!(
2730
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2731
             A state is its heads and what they depend on, not everything recorded before them.\n\
2732
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2733
             or --only for just {0} and what it depends on.",
27341×
            changes.join(" "),
27351×
            plural(gap.earlier.len(), "change"),
27361×
            listed_changes(&repo, &gap.earlier)
2737
        );
2738
    };
27392×
    let heads = repo.bookmark_set(name, &heads)?;
27402×
    println!(
2741
        "{} bookmark {} {} {}",
27422×
        ui::done("Moved"),
27432×
        ui::bookmark(name),
27442×
        ui::dim(ui::glyph("→", "->")),
27452×
        ui::dim(plural(heads.len(), "head"))
2746
    );
27472×
    Ok(0)
27483×
}
2749
27500×
pub fn bookmark_delete(name: &str) -> Result<i32> {
27510×
    let repo = open()?;
27520×
    repo.bookmark_delete(name)?;
27530×
    println!(
2754
        "{} bookmark {} {}",
27550×
        ui::done("Deleted"),
27560×
        ui::bookmark(name),
27570×
        ui::dim("(its changes stay until unreachable)")
2758
    );
27590×
    Ok(0)
27600×
}
2761
2762
/// Heads with their metadata, newest first.
27630×
fn heads_newest_first(
27640×
    repo: &Repo,
27650×
    heads: &[oxy_core::hash::ChangeHash],
27660×
) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> {
27670×
    let mut out: Vec<_> = heads
27680×
        .iter()
27690×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m)))
27700×
        .collect();
27710×
    out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc));
27720×
    out
27730×
}
2774
2775
/// One head as a line: id, hash, author, when, subject.
27760×
fn print_head(
27770×
    repo: &Repo,
27780×
    indent: &str,
27790×
    h: &oxy_core::hash::ChangeHash,
27800×
    m: &oxy_core::state::ChangeMeta,
27810×
) {
27820×
    println!(
2783
        "{indent}{} {} {}{}{}{}{}",
27840×
        ui::id(m.change_id.short(8)),
27850×
        ui::dim(format!("#{}", &h.to_hex()[..8])),
27860×
        author_name(repo, m),
27870×
        ui::sep(),
27880×
        ui::dim(ui::ago(m.hlc.wall_ms)),
27890×
        ui::sep(),
27900×
        ui::subject(subject_of(&m.message))
2791
    );
27920×
}
2793
27940×
pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result<i32> {
27950×
    let repo = open()?;
27960×
    let name = name.unwrap_or(&repo.config.bookmark).to_string();
27970×
    let view = repo.view()?;
27980×
    let st = match view.bookmarks.get(&name) {
27990×
        Some(st) => *st,
28000×
        None => match oxy_core::repo::remote_bookmark(&view, &name) {
28010×
            Some((_, _, st)) => st,
28020×
            None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"),
2803
        },
2804
    };
28050×
    let heads = repo.store().get_state(&st)?.heads;
28060×
    let shown = heads_newest_first(&repo, &heads);
28070×
    if as_json {
28080×
        println!(
2809
            "{}",
28100×
            json::obj([
28110×
                ("name", json::s(&name)),
28120×
                ("current", json::b(name == repo.config.bookmark)),
2813
                (
28140×
                    "heads",
28150×
                    json::arr(shown.iter().map(|(h, m)| {
28160×
                        json::obj([
28170×
                            ("hash", json::s(&h.to_hex())),
28180×
                            ("id", json::s(&m.change_id.to_string())),
28190×
                            ("author", json::s(&author_name(&repo, m))),
28200×
                            ("time_ms", json::n(m.hlc.wall_ms)),
28210×
                            ("subject", json::s(subject_of(&m.message))),
28220×
                        ])
28230×
                    }))
2824
                ),
2825
            ])
2826
        );
28270×
        return Ok(0);
28280×
    }
28290×
    println!(
2830
        "{} {}{}{}",
28310×
        ui::ok(ui::glyph("●", "*")),
28320×
        ui::bookmark(&name),
28330×
        ui::sep(),
28340×
        ui::dim(plural(heads.len(), "head"))
2835
    );
28360×
    for (h, m) in &shown {
28370×
        print_head(&repo, "  ", h, m);
28380×
    }
28390×
    if heads.len() > 1 {
28400×
        println!(
28410×
            "  {}",
28420×
            ui::dim("None depends on another: the bookmark is all of them and their dependencies.")
28430×
        );
28440×
    }
28450×
    Ok(0)
28460×
}
2847
28485×
pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result<i32> {
28495×
    let repo = open()?;
28505×
    let remote_only = repo.remote_only_bookmarks()?;
28515×
    if as_json {
28525×
        let mut items: Vec<String> = repo
28535×
            .bookmarks()?
28545×
            .into_iter()
285513×
            .map(|b| {
285613×
                json::obj([
285713×
                    ("name", json::s(&b.name)),
285813×
                    ("heads", json::hashes(&b.heads)),
285913×
                    ("current", json::b(b.current)),
286013×
                    ("ahead", json::opt(b.ahead, json::n)),
286113×
                    ("behind", json::opt(b.behind, json::n)),
286213×
                    ("remote", json::opt(b.remote.as_deref(), json::s)),
286313×
                ])
286413×
            })
28655×
            .collect();
28665×
        if all {
28670×
            items.extend(remote_only.iter().map(|b| {
28680×
                json::obj([
28690×
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
28700×
                    ("heads", json::hashes(&b.heads)),
28710×
                    ("current", json::b(false)),
28720×
                    ("ahead", "null".into()),
28730×
                    ("behind", "null".into()),
28740×
                    ("remote", json::s(&b.remote)),
28750×
                ])
28760×
            }));
28775×
        }
28785×
        println!("{}", json::arr(items));
28795×
        return Ok(0);
28800×
    }
28810×
    for b in repo.bookmarks()? {
28820×
        let mark = if b.current {
28830×
            ui::ok(ui::glyph("●", "*"))
2884
        } else {
28850×
            ui::dim(ui::glyph("○", "o"))
2886
        };
28870×
        let mut tail = String::new();
28880×
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
28890×
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
28900×
        }
28910×
        if let Some(n) = b.behind.filter(|n| *n > 0) {
28920×
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
28930×
        }
2894
        // Which remote, when there is a choice (oxygen#83).
28950×
        if !tail.is_empty() && repo.config.remotes.len() > 1 {
28960×
            if let Some(r) = &b.remote {
28970×
                tail += &ui::dim(format!(" {r}"));
28980×
            }
28990×
        }
29000×
        let shown = heads_newest_first(&repo, &b.heads);
2901
        // The newest head's subject, so a busy bookmark shows its latest work.
29020×
        let head = match shown.first() {
29030×
            Some(_) if verbose => String::new(),
29040×
            Some((_, m)) if b.heads.len() > 1 => format!(
2905
                "{} {}",
29060×
                ui::dim("newest"),
29070×
                ui::subject(subject_of(&m.message))
2908
            ),
29090×
            Some((_, m)) => ui::subject(subject_of(&m.message)),
29100×
            None => ui::dim("(empty)"),
2911
        };
29120×
        let head = if head.is_empty() {
29130×
            head
2914
        } else {
29150×
            format!("  {head}")
2916
        };
29170×
        println!(
2918
            "{mark} {}{}{}{tail}{head}",
29190×
            ui::bookmark(&b.name),
29200×
            ui::sep(),
29210×
            ui::dim(plural(b.heads.len(), "head"))
2922
        );
29230×
        if verbose {
29240×
            for (h, m) in &shown {
29250×
                print_head(&repo, "    ", h, m);
29260×
            }
29270×
        }
2928
    }
29290×
    if remote_only.is_empty() {
29300×
        return Ok(0);
29310×
    }
29320×
    if !all {
29330×
        println!(
2934
            "{}",
29350×
            ui::dim(format!(
2936
                "  and {} only on a remote: oxy bookmark list --all",
29370×
                plural(remote_only.len(), "bookmark")
2938
            ))
2939
        );
29400×
        return Ok(0);
29410×
    }
29420×
    for b in &remote_only {
29430×
        println!(
29440×
            "{} {}{}{}",
29450×
            ui::dim(ui::glyph("◌", ".")),
29460×
            ui::dim(format!("{}/{}", b.remote, b.name)),
29470×
            ui::sep(),
29480×
            ui::dim(plural(b.heads.len(), "head"))
29490×
        );
29500×
    }
29510×
    println!(
2952
        "  {} {}",
29530×
        ui::note(),
29540×
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2955
    );
29560×
    Ok(0)
29575×
}
2958
29593×
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
29603×
    let mut repo = open()?;
29613×
    let from = repo.config.bookmark.clone();
29623×
    let (local, created_from) = repo.local_bookmark_for(name)?;
29633×
    if let Some(remote) = created_from {
29640×
        println!(
29650×
            "{} {} from {}",
29660×
            ui::done("Created"),
29670×
            ui::bookmark(&local),
29680×
            ui::dim(format!("{remote}/{local}"))
29690×
        );
29703×
    }
29713×
    let name = local.as_str();
2972
    // Only behind its remote: take the remote's state, so the switch does
2973
    // not check out a stale one (oxygen#74).
29743×
    if let Some(n) = repo.catch_up_bookmark(name)? {
29750×
        println!(
29760×
            "{} {} with {}: {} it lacked",
29770×
            ui::done("Caught up"),
29780×
            ui::bookmark(name),
29790×
            ui::dim(format!("{}/{name}", repo.default_remote())),
29800×
            plural(n, "change")
29810×
        );
29823×
    }
29833×
    let sp = ui::spinner(&format!("Switching to {name}…"));
29843×
    let (r, carried) = if carry {
29850×
        repo.bookmark_switch_carry(name)?
2986
    } else {
29873×
        (repo.bookmark_switch(name, discard)?, vec![])
2988
    };
29893×
    sp.done(&format!(
2990
        "{} to {}: {} written, {} removed{}",
29913×
        ui::done("Switched"),
29923×
        ui::bookmark(name),
29933×
        plural(r.written, "file"),
2994
        r.removed,
29953×
        if carried.is_empty() {
29963×
            String::new()
2997
        } else {
29980×
            format!("; carried {}", plural(carried.len(), "changed path"))
2999
        }
3000
    ));
30013×
    print_removed(&r);
30023×
    print_carried(&carried);
30033×
    print_kept_both(&r);
30043×
    if r.conflicted {
30050×
        println!(
30060×
            "  {} {}",
30070×
            ui::caution(),
30080×
            ui::warn("this state has conflicts; see oxy status")
30090×
        );
30103×
    }
3011
    // Say when the new state leaves out work the old one had: a state is
3012
    // its heads and what they depend on, which can be far less than a Git
3013
    // user expects.
30143×
    if r.lacks > 0 {
30151×
        println!(
30161×
            "  {} {}",
30171×
            ui::note(),
30181×
            ui::dim(format!(
30191×
                "{name} lacks {} that {from} has",
30201×
                plural(r.lacks, "change")
30211×
            ))
30221×
        );
30232×
    }
30243×
    super::sync::subrepos_behind(&repo);
30253×
    where_now(&repo);
30263×
    Ok(0)
30273×
}
3028
30290×
pub fn merge(bookmark: &str) -> Result<i32> {
30300×
    let repo = open()?;
30310×
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
30320×
    let r = repo.merge(bookmark)?;
30330×
    if !r.changed {
30340×
        sp.done(&format!(
30350×
            "{} {}",
30360×
            ui::ok(ui::glyph("✔", "*")),
30370×
            ui::dim(format!(
30380×
                "{} already contains {bookmark}",
30390×
                repo.config.bookmark
30400×
            ))
30410×
        ));
30420×
        return Ok(0);
30430×
    }
30440×
    sp.done(&format!(
3045
        "{} {} into {}: now {}{}",
30460×
        ui::done("Merged"),
30470×
        ui::bookmark(bookmark),
30480×
        ui::bookmark(&repo.config.bookmark),
30490×
        plural(r.heads.len(), "head"),
30500×
        ui::dim(if r.checked_out {
30510×
            "; working copy updated"
3052
        } else {
30530×
            "; run oxy checkout to update the working copy"
3054
        })
3055
    ));
30560×
    let snap = repo.snapshot("oxy merge")?;
30570×
    if snap.base_snapshot.is_conflicted() {
30580×
        println!(
30590×
            "  {} {}",
30600×
            ui::caution(),
30610×
            ui::warn("the result has conflicts; see oxy status")
30620×
        );
30630×
    }
30640×
    where_now(&repo);
30650×
    Ok(0)
30660×
}
3067
30680×
pub fn squash(change: &str, into: &str) -> Result<i32> {
30690×
    let repo = open()?;
30700×
    let c = repo.resolve_change(change)?;
30710×
    let d = repo.resolve_change(into)?;
30720×
    let sp = ui::spinner("Squashing…");
30730×
    let h = repo.squash(&c, &d)?;
30740×
    let new = repo.store().get_change_meta(&h)?;
30750×
    sp.done(&format!(
30760×
        "{} into {} {}  {}",
30770×
        ui::done("Squashed"),
30780×
        ui::id(new.change_id.short(8)),
30790×
        ui::hash(format!("#{}", h.short(12))),
30800×
        ui::subject(subject_of(&new.message))
30810×
    ));
30820×
    Ok(0)
30830×
}
3084
30850×
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
30860×
    let repo = open()?;
30870×
    let c = repo.resolve_change(change)?;
30880×
    let mut heads = Vec::new();
30890×
    for o in onto {
30900×
        heads.extend(repo.resolve_heads(o)?);
3091
    }
30920×
    let sp = ui::spinner("Rebasing…");
30930×
    let h = match repo.rebase(&c, &heads) {
30940×
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
30950×
            let r = repo.rebase_into_working_copy(&c, &heads)?;
30960×
            sp.done(&format!(
30970×
                "{} {} into {}: now {}",
30980×
                ui::done("Merged"),
30990×
                onto.join(" "),
31000×
                ui::bookmark(&repo.config.bookmark),
31010×
                plural(r.heads.len(), "head"),
31020×
            ));
31030×
            if r.checked_out {
31040×
                println!(
31050×
                    "  {} {}",
31060×
                    ui::caution(),
31070×
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
31080×
                );
31090×
            } else {
31100×
                println!(
31110×
                    "  {} {}",
31120×
                    ui::caution(),
31130×
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
31140×
                );
31150×
            }
31160×
            where_now(&repo);
31170×
            return Ok(0);
3118
        }
31190×
        other => other?,
3120
    };
31210×
    let new = repo.store().get_change_meta(&h)?;
31220×
    sp.done(&format!(
31230×
        "{} {} {}  {}",
31240×
        ui::done("Rebased"),
31250×
        ui::id(new.change_id.short(8)),
31260×
        ui::hash(format!("#{}", h.short(12))),
31270×
        ui::dim(format!(
31280×
            "now depends on {}",
31290×
            plural(new.deps.len(), "change")
31300×
        ))
31310×
    ));
31320×
    where_now(&repo);
31330×
    Ok(0)
31340×
}
3135
3136
#[cfg(test)]
3137
mod tests {
3138
    use super::*;
3139
3140
    #[test]
31411×
    fn id_prefixes_agree_with_the_whole_list() {
3142
        // Ids that share long prefixes, and some that differ only in a
3143
        // half byte, from a fixed sequence.
31441×
        let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
31457999×
        let mut next = || {
31467999×
            x ^= x << 13;
31477999×
            x ^= x >> 7;
31487999×
            x ^= x << 17;
31497999×
            x
31507999×
        };
31511×
        let mut ids: Vec<[u8; 16]> = Vec::new();
31521×
        for _ in 0..2000 {
31532000×
            let mut id = [0u8; 16];
31542000×
            id[..8].copy_from_slice(&next().to_le_bytes());
31552000×
            id[8..].copy_from_slice(&next().to_le_bytes());
31562000×
            let share = (next() % 4) as usize;
31572000×
            if let Some(prev) = ids.last() {
31581999×
                id[..share].copy_from_slice(&prev[..share]);
31591999×
                if next() % 2 == 0 {
3160973×
                    id[share] = (prev[share] & 0xf0) | (id[share] & 0x0f);
31611026×
                }
31621×
            }
31632000×
            ids.push(id);
3164
        }
31654000×
        let hex = |id: &[u8; 16]| oxy_core::ids::ChangeId(*id).to_hex();
31661×
        let whole = unique_prefixes(ids.iter().map(hex));
31671×
        let some = id_prefixes(ids.clone(), ids.iter().copied());
31682000×
        for id in &ids {
31692000×
            assert_eq!(some[id], whole[&hex(id)], "{}", hex(id));
3170
        }
31711×
    }
3172
}