OXYGENHUB

Coverage / src/cli/workspace.rs 40.3%

1012 of 2513 lines run, 98 of 355 functions · run #423 on main · run missed

1
//! Commands that act on the local repository and working copy.
2
3
use super::format::{
4
    author_name, deps_line, deps_of, plural, short_id, signature_line, signature_mark_of,
5
    subject_of, via, when,
6
};
7
use super::json;
8
use super::open;
9
use super::ui;
10
use anyhow::Result;
11
use oxy_core::objects::ChangeKind;
12
use oxy_core::repo::SignatureStatus;
13
use oxy_core::repo::{render_change, ChangeStatus, Repo};
14
use std::io::Write;
15
use std::path::PathBuf;
16
1717×
pub fn init(path: Option<PathBuf>, bare: bool, store: Option<&str>) -> Result<i32> {
1817×
    let path = path.unwrap_or(std::env::current_dir()?);
1917×
    let repo = Repo::init_new(&path, bare, store)?;
2017×
    println!(
21
        "{} {}oxy repository in {}",
2217×
        ui::done("Initialized"),
2317×
        if bare { "bare " } else { "" },
2417×
        ui::path(repo.root().display())
25
    );
2617×
    println!(
27
        "{}",
2817×
        ui::kv("bookmark", ui::bookmark(&repo.config.bookmark))
29
    );
3017×
    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×
        );
4217×
    }
4317×
    println!(
44
        "{}",
4517×
        ui::kv(
4617×
            "author",
4717×
            format!(
48
                "{} <{}>",
4917×
                ui::author(&repo.config.author_name),
50
                repo.config.author_email
51
            )
52
        )
53
    );
5417×
    Ok(0)
5517×
}
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.
7137×
fn print_skipped_large(repo: &Repo) {
7237×
    let skipped = repo.skipped_large();
7337×
    if skipped.is_empty() {
7437×
        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
    );
10037×
}
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.
15537×
fn print_untracked_nested(repo: &Repo, nested: &[String]) {
15637×
    if nested.is_empty() {
15735×
        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
    );
18637×
}
187
188
/// The working copy's changed paths, or that it is clean.
1896×
fn print_statuses(statuses: &[oxy_core::repo::PathStatus]) {
1906×
    if statuses.is_empty() {
1914×
        println!(
192
            "  {} {}",
1934×
            ui::ok(ui::glyph("✔", "*")),
1944×
            ui::dim("nothing to commit, working copy clean")
195
        );
1964×
        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×
    }
2066×
}
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).
2106×
fn print_behind(repo: &Repo) {
2116×
    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×
        );
2216×
    }
2226×
}
223
22411×
pub fn status(json: bool) -> Result<i32> {
22511×
    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.
22811×
    let known = if json {
2295×
        None
230
    } else {
2316×
        repo.status_by_manifest()?
232
    };
23311×
    if let Some(statuses) = known {
2344×
        let (_, wc) = repo.working_copy()?;
2354×
        let heads = repo.bookmark_heads()?;
2364×
        println!(
237
            "{} {}{}working copy {}{}{}",
2384×
            ui::dim("On"),
2394×
            ui::bookmark(&repo.config.bookmark),
2404×
            ui::sep(),
2414×
            ui::id(wc.change_id.short(8)),
2424×
            ui::sep(),
2434×
            ui::dim(plural(heads.len(), "head"))
244
        );
2454×
        print_behind(&repo);
2464×
        print_statuses(&statuses);
2474×
        print_untracked_nested(&repo, &repo.untracked_nested());
2484×
        print_skipped_large(&repo);
2494×
        return Ok(0);
2507×
    }
2517×
    let sp = ui::spinner("Snapshotting the working copy…");
2527×
    let snap = repo.snapshot_status("oxy status")?;
2537×
    let heads = {
2547×
        let _t = oxy_core::timing::phase("status: heads");
2557×
        repo.bookmark_heads()?
256
    };
2577×
    let _drop = oxy_core::timing::phase("status: print and drop");
2587×
    sp.clear();
2597×
    if json {
2605×
        println!("{}", repo.status_json(&snap)?);
2615×
        return Ok(if snap.base_snapshot.is_conflicted() {
2620×
            2
263
        } else {
2645×
            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)
33411×
}
335
33631×
pub fn commit(
33731×
    message: &str,
33831×
    depends_on: &[String],
33931×
    paths: &[String],
34031×
    interactive: bool,
34131×
    hunks: &[usize],
34231×
) -> Result<i32> {
34331×
    let repo = open()?;
34431×
    let mut deps = Vec::new();
34531×
    for d in depends_on {
3460×
        deps.push(repo.resolve_change(d)?);
347
    }
34831×
    let selection = if !hunks.is_empty() {
3491×
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
35030×
    } 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)
41930×
    } else if paths.is_empty() {
42027×
        oxy_core::repo::Selection::All
421
    } else {
4223×
        oxy_core::repo::Selection::Paths(paths.to_vec())
423
    };
42431×
    let sp = ui::spinner("Committing…");
42531×
    let (h, partial) = repo.commit_selection_partial(message, &deps, &selection)?;
426
    // The metadata only: a first commit's change holds the whole tree.
42731×
    let meta = repo.store().get_change_meta(&h)?;
42831×
    sp.done(&format!(
42931×
        "{} {} {}  {}",
43031×
        ui::done("Committed"),
43131×
        ui::id(meta.change_id.short(8)),
43231×
        ui::hash(format!("#{}", h.short(12))),
43331×
        ui::subject(subject_of(message))
43431×
    ));
43531×
    print_untracked_nested(&repo, &repo.untracked_nested());
43631×
    print_skipped_large(&repo);
437
    // Only a commit that took part of the working copy leaves anything.
43831×
    if partial {
4393×
        let rest = repo.snapshot_status("oxy commit")?;
4403×
        if !rest.statuses.is_empty() {
4413×
            println!(
4423×
                "  {} {}",
4433×
                ui::note(),
4443×
                ui::dim(format!(
4453×
                    "{} left uncommitted",
4463×
                    plural(rest.statuses.len(), "path")
4473×
                ))
4483×
            );
4493×
        }
45028×
    }
45131×
    where_now(&repo);
45231×
    Ok(0)
45331×
}
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.
65916×
fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
66016×
    Ok(match repo.authenticate_change(h)? {
6619×
        SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]),
662
        SignatureStatus::Valid {
6637×
            key,
6647×
            name,
6657×
            email,
6667×
            sealed,
6677×
            revoked,
6687×
        } => json::obj([
6697×
            ("status", json::s(if sealed { "sealed" } else { "signed" })),
6707×
            ("key", json::s(&key.to_hex())),
6717×
            ("name", json::s(&name)),
6727×
            ("email", json::s(&email)),
6737×
            ("revoked", json::b(revoked)),
674
        ]),
6750×
        SignatureStatus::Invalid(why) => {
6760×
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
677
        }
678
    })
67916×
}
680
68122×
fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result<String> {
68222×
    let c = &e.change;
68322×
    Ok(json::obj([
68422×
        ("hash", json::s(&e.hash.to_hex())),
68522×
        ("change_id", json::s(&c.change_id.to_hex())),
68622×
        ("author", json::s(&author_name(repo, c))),
68722×
        ("author_key", json::s(&c.author.to_hex())),
688
        (
68922×
            "via",
69022×
            match via(
69122×
                repo,
69222×
                &repo.authenticate_change_known(&e.hash, Some(c))?,
69322×
                &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×
                ]),
70322×
                None => "null".to_string(),
704
            },
705
        ),
70622×
        ("when_ms", json::n(c.hlc.wall_ms)),
70722×
        ("message", json::s(&c.message)),
70822×
        ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())),
70922×
        ("deps", json::hashes(&c.deps)),
71022×
        ("head", json::b(e.is_head)),
71122×
        ("working_copy", json::b(e.is_working_copy)),
712
        (
71322×
            "signature",
71422×
            if e.is_working_copy {
7156×
                "null".into()
716
            } else {
71716×
                signature_json(repo, &e.hash)?
718
            },
719
        ),
720
    ]))
72122×
}
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
73510×
pub fn log(
73610×
    revset: Option<&str>,
73710×
    limit: Option<usize>,
73810×
    verbose: bool,
73910×
    path: Option<&str>,
74010×
    lines: Option<&str>,
74110×
    as_json: bool,
74210×
) -> Result<i32> {
74310×
    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.
74910×
    let conflicted = !repo.is_at_op() && repo.recorded_conflicted()?;
75010×
    let listing = oxy_core::timing::phase("log: entries");
75110×
    let entries = match (path, lines) {
75210×
        _ 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)?,
7607×
        (None, None) => repo.log()?,
761
    };
7629×
    drop(listing);
7639×
    let _print = oxy_core::timing::phase("log: print");
7649×
    if as_json {
7658×
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
7668×
        let mut items = Vec::new();
76721×
        for e in entries.iter().take(shown) {
76821×
            items.push(log_entry_json(&repo, e)?);
769
        }
7708×
        println!(
771
            "{}",
7728×
            json::obj([
7738×
                ("bookmark", json::s(&repo.config.bookmark)),
7748×
                ("total", json::n(entries.len())),
7758×
                ("changes", json::arr(items))
7768×
            ])
777
        );
7788×
        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)
90410×
}
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
11213×
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
11223×
    let repo = open()?;
11233×
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
11243×
    let bytes = match repo.file_at(path, heads.as_deref()) {
11253×
        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 _;
11463×
    std::io::stdout().write_all(&bytes)?;
11473×
    Ok(0)
11483×
}
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").
181836×
pub fn where_now(repo: &Repo) {
181936×
    let Ok((_, wc)) = repo.working_copy() else {
18200×
        return;
1821
    };
182236×
    let heads = repo.bookmark_heads().unwrap_or_default();
182336×
    let newest = heads
182436×
        .iter()
182549×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
182636×
        .max_by_key(|(m, _)| m.hlc);
182736×
    println!(
1828
        "  {} {}",
182936×
        ui::dim(format!("{:<13}", "Working copy")),
183036×
        ui::id(wc.change_id.short(8))
1831
    );
183236×
    let tail = match newest {
183336×
        Some((m, _)) => format!(
1834
            ", newest {} {}",
183536×
            ui::id(m.change_id.short(8)),
183636×
            subject_of(&m.message)
1837
        ),
18380×
        None => String::new(),
1839
    };
184036×
    println!(
1841
        "  {} {}: {}{tail}",
184236×
        ui::dim(format!("{:<13}", "Bookmark")),
184336×
        ui::bookmark(&repo.config.bookmark),
184436×
        plural(heads.len(), "head")
1845
    );
184636×
}
1847
18481×
pub fn gc(now: bool, expire_snapshots: bool) -> Result<i32> {
18491×
    let mut repo = open()?;
18501×
    if expire_snapshots {
18510×
        repo.config.snapshot_retention_days = 0;
18521×
    }
18531×
    let sp = ui::spinner("Packing and pruning…");
1854
    // Cylinder's artifacts are named from outside the history: keep them.
18551×
    let artifacts = cylinder::roots(&repo)?;
18565×
    let r = repo.gc_keeping(now, &artifacts, &mut |phase| sp.set(&format!("{phase}…")))?;
18571×
    sp.clear();
18581×
    if r.packed.objects > 0 {
18591×
        println!(
18601×
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
18611×
            plural(r.packed.objects, "object"),
18621×
            r.packed.raw_bytes,
18631×
            r.packed.packed_bytes,
18641×
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
18651×
        );
18661×
    }
18671×
    println!(
1868
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
18691×
        plural(r.reachable, "object"),
18701×
        plural(r.pruned.objects, "unreachable object"),
1871
        r.pruned.bytes,
18721×
        if r.pruned.deferred > 0 {
18730×
            format!(
1874
                "; {} deferred by the grace period (use --now)",
18750×
                plural(r.pruned.deferred, "object")
1876
            )
1877
        } else {
18781×
            String::new()
1879
        },
18801×
        if r.merged_packs > 0 {
18810×
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1882
        } else {
18831×
            String::new()
1884
        },
18851×
        plural(repo.store().pack_count(), "pack")
1886
    );
1887
    // What earlier repacks replaced stays an hour for readers still using
1888
    // it (oxygenhub#249); a collection after that deletes it.
18891×
    let kept = if r.retired.kept > 0 {
18900×
        format!(
1891
            "{} retired less than an hour ago kept for readers",
18920×
            plural(r.retired.kept, "file")
1893
        )
1894
    } else {
18951×
        String::new()
1896
    };
18971×
    if r.retired.packs + r.retired.loose > 0 {
18980×
        println!(
1899
            "Deleted {} and {} retired by earlier repacks{}.",
19000×
            plural(r.retired.packs, "pack"),
19010×
            plural(r.retired.loose, "loose object"),
19020×
            if kept.is_empty() {
19030×
                String::new()
1904
            } else {
19050×
                format!("; {kept}")
1906
            }
1907
        );
19081×
    } else if !kept.is_empty() {
19090×
        println!("{kept}.");
19101×
    }
19111×
    Ok(0)
19121×
}
1913
1914
/// `oxy gc --remote NAME`: fold a store remote's bundles into one.
19152×
pub fn gc_remote(name: &str, now: bool) -> Result<i32> {
19162×
    let repo = open()?;
19172×
    let sp = ui::spinner(&format!("Folding {name}'s bundles…"));
19182×
    let r = repo.gc_remote(name, now)?;
19191×
    sp.clear();
19201×
    if r.merged > 0 {
19211×
        println!(
19221×
            "{} {} into one of {} bytes ({})",
19231×
            ui::done("Folded"),
19241×
            plural(r.merged, "bundle"),
19251×
            r.bundle_bytes,
19261×
            plural(r.changes, "change")
19271×
        );
19281×
    } else {
19290×
        println!(
19300×
            "{} {}",
19310×
            ui::note(),
19320×
            ui::dim("nothing to fold: one bundle holds everything")
19330×
        );
19340×
    }
19351×
    println!(
1936
        "  {} {}",
19371×
        ui::note(),
19381×
        ui::dim(format!(
1939
            "removed {}{}",
19401×
            plural(r.deleted, "superseded bundle"),
19411×
            if r.deferred > 0 {
19420×
                format!(
1943
                    "; {} kept for readers that may still fetch them (use --now)",
19440×
                    plural(r.deferred, "bundle")
1945
                )
1946
            } else {
19471×
                String::new()
1948
            }
1949
        ))
1950
    );
19511×
    Ok(0)
19522×
}
1953
1954
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
19550×
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1956
    use oxy_core::repo::Health;
19570×
    let repo = open()?;
19580×
    let sp = ui::spinner(if offline {
19590×
        "Checking…"
1960
    } else {
19610×
        "Checking, and contacting remotes…"
1962
    });
19630×
    let r = repo.doctor(!offline);
19640×
    sp.clear();
19650×
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
19660×
    let word = |h: Health| match h {
19670×
        Health::Ok => "ok",
19680×
        Health::Warn => "warning",
19690×
        Health::Fail => "fail",
19700×
    };
19710×
    if as_json {
19720×
        let checks: Vec<String> = r
19730×
            .checks
19740×
            .iter()
19750×
            .map(|c| {
19760×
                json::obj([
19770×
                    ("area", json::s(&c.area)),
19780×
                    ("health", json::s(word(c.health))),
19790×
                    ("message", json::s(&c.message)),
19800×
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
19810×
                ])
19820×
            })
19830×
            .collect();
19840×
        println!(
1985
            "{}",
19860×
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1987
        );
19880×
        return Ok(code);
19890×
    }
19900×
    let mut last = "";
19910×
    for c in &r.checks {
19920×
        if c.area != last {
19930×
            println!("{}", ui::section(&c.area));
19940×
            last = &c.area;
19950×
        }
19960×
        let mark = match c.health {
19970×
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
19980×
            Health::Warn => ui::caution(),
19990×
            Health::Fail => ui::err(ui::glyph("✖", "x")),
2000
        };
20010×
        println!("  {mark} {}", c.message);
20020×
        if let Some(h) = &c.hint {
20030×
            println!("    {} {}", ui::dim("→"), ui::dim(h));
20040×
        }
2005
    }
20060×
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
20070×
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
20080×
    if fails + warns == 0 {
20090×
        println!("{}", ui::done("Everything looks right."));
20100×
    } else {
20110×
        println!(
2012
            "{} {}, {}.",
20130×
            if fails > 0 {
20140×
                ui::err(ui::glyph("✖", "x"))
2015
            } else {
20160×
                ui::caution()
2017
            },
20180×
            plural(fails, "problem"),
20190×
            plural(warns, "warning")
2020
        );
2021
    }
20220×
    Ok(code)
20230×
}
2024
2025
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
20260×
pub fn fsck(as_json: bool) -> Result<i32> {
2027
    use oxy_core::repo::Severity;
20280×
    let repo = open()?;
20290×
    let sp = ui::spinner("Checking every object…");
20300×
    let r = repo.fsck()?;
20310×
    sp.clear();
20320×
    let code = if r.errors() > 0 { 1 } else { 0 };
20330×
    if as_json {
20340×
        let problems: Vec<String> = r
20350×
            .problems
20360×
            .iter()
20370×
            .map(|p| {
20380×
                json::obj([
2039
                    (
2040
                        "severity",
20410×
                        json::s(match p.severity {
20420×
                            Severity::Error => "error",
20430×
                            Severity::Warning => "warning",
2044
                        }),
2045
                    ),
2046
                    (
20470×
                        "object",
20480×
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
2049
                    ),
20500×
                    ("what", json::s(&p.what)),
2051
                ])
20520×
            })
20530×
            .collect();
20540×
        println!(
2055
            "{}",
20560×
            json::obj([
20570×
                ("ok", json::b(code == 0)),
20580×
                ("objects", json::n(r.objects)),
20590×
                ("ops", json::n(r.ops)),
20600×
                ("changes", json::n(r.changes)),
20610×
                ("signed", json::n(r.signed)),
20620×
                ("unsigned", json::n(r.unsigned)),
20630×
                ("checkpoints", json::n(r.checkpoints)),
20640×
                ("attestations", json::n(r.attestations)),
20650×
                ("errors", json::n(r.errors())),
20660×
                ("warnings", json::n(r.warnings())),
20670×
                ("problems", json::arr(problems)),
20680×
            ])
2069
        );
20700×
        return Ok(code);
20710×
    }
20720×
    println!(
2073
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
20740×
        plural(r.objects, "object"),
20750×
        plural(r.ops, "operation"),
20760×
        plural(r.changes, "change"),
2077
        r.signed,
2078
        r.unsigned,
20790×
        plural(r.checkpoints, "checkpoint"),
20800×
        plural(r.attestations, "attestation"),
2081
    );
20820×
    for p in &r.problems {
20830×
        let obj = p
20840×
            .object
20850×
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
20860×
            .unwrap_or_default();
20870×
        match p.severity {
20880×
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
20890×
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
2090
        }
2091
    }
20920×
    if r.problems.is_empty() {
20930×
        println!("{}", ui::done("No problems found."));
20940×
    } else if code == 0 {
20950×
        println!(
20960×
            "{}",
20970×
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
20980×
        );
20990×
    } else {
21000×
        println!(
21010×
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
21020×
            ui::err(ui::glyph("✖", "x")),
21030×
            plural(r.errors(), "error"),
21040×
            plural(r.warnings(), "warning")
21050×
        );
21060×
    }
21070×
    Ok(code)
21080×
}
2109
2110
/// The head the working copy sits on, for commands that default to it. With
2111
/// several heads beneath the working copy, the most recently made one is
2112
/// chosen and announced.
21130×
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
21140×
    let snap = repo.snapshot_status("oxy")?;
21150×
    let base = snap.base.maximal(&snap.wc.deps);
21160×
    match base.as_slice() {
21170×
        [] => anyhow::bail!("the working copy sits on no change yet"),
21180×
        [h] => Ok(*h),
21190×
        many => {
21200×
            let latest = many
21210×
                .iter()
21220×
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
21230×
                .copied()
21240×
                .unwrap();
21250×
            let c = repo.store().get_change(&latest)?;
21260×
            println!(
2127
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
21280×
                short_id(&c),
21290×
                latest.short(12),
21300×
                many.len()
2131
            );
21320×
            Ok(latest)
2133
        }
2134
    }
21350×
}
2136
2137
/// `oxy describe` without -m: the working copy's name for a build.
21384×
pub fn describe_name(as_json: bool) -> Result<i32> {
21394×
    let repo = open()?;
21404×
    let d = repo.describe_working_copy()?;
21414×
    if as_json {
21423×
        println!(
2143
            "{}",
21443×
            json::obj([
21453×
                ("describe", json::s(&d.line())),
21463×
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
21473×
                ("distance", json::n(d.distance)),
21483×
                ("bookmark", json::s(&d.bookmark)),
21493×
                ("change", json::s(&d.change.to_hex())),
21503×
                ("hash", json::s(&d.hash.to_hex())),
21513×
                ("dirty", json::b(d.dirty)),
2152
            ])
2153
        );
21541×
    } else {
21551×
        println!("{}", d.line());
21561×
    }
21574×
    Ok(0)
21584×
}
2159
21600×
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
21610×
    let repo = open()?;
21620×
    let h = match change {
21630×
        Some(c) => repo.resolve_change(c)?,
21640×
        None => current_head(&repo)?,
2165
    };
21660×
    let new = repo.describe(&h, message)?;
21670×
    let c = repo.store().get_change_meta(&new)?;
21680×
    println!(
2169
        "{} {} {}  {}",
21700×
        ui::done("Described"),
21710×
        ui::id(c.change_id.short(8)),
21720×
        ui::hash(format!("#{}", new.short(12))),
21730×
        ui::subject(subject_of(message))
2174
    );
21750×
    Ok(0)
21760×
}
2177
21780×
pub fn amend(message: Option<&str>, into: Option<&str>, paths: &[String]) -> Result<i32> {
21790×
    let repo = open()?;
21800×
    let before = repo.view()?;
21810×
    let new = match into {
21820×
        Some(spec) => {
21830×
            let target = repo.resolve_change(spec)?;
21840×
            repo.amend_into(&target, message)?
2185
        }
21860×
        None if !paths.is_empty() => repo.amend_paths(message, paths)?,
21870×
        None => repo.amend(message)?,
2188
    };
21890×
    let c = repo.store().get_change_meta(&new)?;
21900×
    println!(
2191
        "{} {} {}  {}",
21920×
        ui::done("Amended"),
21930×
        ui::id(c.change_id.short(8)),
21940×
        ui::hash(format!("#{}", new.short(12))),
21950×
        ui::subject(subject_of(&c.message))
2196
    );
2197
    // Rewriting what a remote already has means the next push replaces it
2198
    // there (oxygen#99): say so now, not when the push is refused.
21990×
    let bookmark = repo.config.bookmark.clone();
22000×
    let (had, has) = (
22010×
        repo.heads_of(&before, &bookmark)?,
22020×
        repo.heads_of(&repo.view()?, &bookmark)?,
2203
    );
22040×
    for (remote, bookmarks) in &before.remotes {
22050×
        let Some(st) = bookmarks.get(&bookmark) else {
22060×
            continue;
2207
        };
22080×
        let theirs = repo.store().get_state(st)?.heads;
22090×
        if theirs.iter().any(|h| had.contains(h) && !has.contains(h)) {
22100×
            println!(
22110×
                "  {} {}",
22120×
                ui::caution(),
22130×
                ui::warn(format!(
22140×
                    "{remote}/{bookmark} has the change as it was: the next push of {bookmark} needs --force to replace it"
22150×
                ))
22160×
            );
22170×
        }
2218
    }
22190×
    where_now(&repo);
22200×
    Ok(0)
22210×
}
2222
22230×
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
22240×
    let repo = open()?;
22250×
    let Some(r) = revset else {
22260×
        let h = repo.resolve_change(change.unwrap_or_default())?;
22270×
        abandon_one(&repo, h)?;
22280×
        where_now(&repo);
22290×
        return Ok(0);
2230
    };
2231
    // A revset: say what it selects, refuse an empty set, ask above a few.
22320×
    let selected = repo.revset(r)?;
22330×
    let wc = repo.working_copy().ok().map(|(h, _)| h);
22340×
    let hashes: Vec<ChangeHash> = selected
22350×
        .hashes
22360×
        .iter()
22370×
        .copied()
22380×
        .filter(|h| Some(*h) != wc)
22390×
        .collect();
22400×
    if hashes.is_empty() {
22410×
        anyhow::bail!("{r:?} selects no change to abandon");
22420×
    }
22430×
    println!(
2244
        "{} {} selects {}:",
22450×
        ui::section("abandon"),
22460×
        ui::id(r),
22470×
        plural(hashes.len(), "change")
2248
    );
22490×
    for h in &hashes {
22500×
        if let Some(m) = selected.metas.get(h) {
22510×
            println!(
22520×
                "  {} {}  {}",
22530×
                ui::id(m.change_id.short(8)),
22540×
                ui::hash(format!("#{}", h.short(12))),
22550×
                subject_of(&m.message)
22560×
            );
22570×
        }
2258
    }
2259
    const ASK_ABOVE: usize = 5;
22600×
    if hashes.len() > ASK_ABOVE && !yes {
22610×
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
22620×
    }
2263
    // Newest first: abandoning a change rewrites what depends on it, so a
2264
    // later member is found again by its ChangeId.
22650×
    let mut done = 0;
22660×
    for h in &hashes {
22670×
        let Some(m) = selected.metas.get(h) else {
22680×
            continue;
2269
        };
22700×
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
22710×
            Ok(h) => h,
22720×
            Err(_) => continue,
2273
        };
22740×
        abandon_one(&repo, now)?;
22750×
        done += 1;
2276
    }
22770×
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
22780×
    where_now(&repo);
22790×
    Ok(0)
22800×
}
2281
22820×
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
22830×
    let c = repo.store().get_change_meta(&h)?;
22840×
    let notes = repo.abandon(&h)?;
22850×
    println!(
2286
        "{} {} {}  {}",
22870×
        ui::done("Abandoned"),
22880×
        ui::id(c.change_id.short(8)),
22890×
        ui::hash(format!("#{}", h.short(12))),
22900×
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
2291
    );
22920×
    for n in notes {
22930×
        println!("  {} {n}", ui::note());
22940×
    }
22950×
    Ok(())
22960×
}
2297
22980×
pub fn checkpoint() -> Result<i32> {
22990×
    let repo = open()?;
23000×
    let sp = ui::spinner("Writing checkpoint…");
23010×
    let (r, changes, bytes) = repo.checkpoint()?;
23020×
    sp.done(&format!(
23030×
        "{} {} of {} ({} bytes) for {}",
23040×
        ui::done("Checkpoint"),
23050×
        ui::hash(format!("#{}", r.short(12))),
23060×
        plural(changes, "change"),
23070×
        bytes,
23080×
        ui::id(&repo.config.bookmark)
23090×
    ));
23100×
    Ok(0)
23110×
}
2312
2313
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
23140×
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
23150×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
23160×
        return Ok(1);
2317
    };
23180×
    let info = repo.quick_status()?;
23190×
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
23200×
        oxy_core::repo::GLYPH_PROMPT_FORMAT
2321
    } else {
23220×
        format
2323
    };
23240×
    let line = match color {
23250×
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
23260×
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
23270×
        Some(_) => info.format_colored(fmt, ("", "")),
23280×
        None => info.format(fmt),
2329
    };
23300×
    println!("{line}");
23310×
    Ok(0)
23320×
}
2333
23340×
pub fn sparse(paths: &[String]) -> Result<i32> {
23350×
    let mut repo = open()?;
23360×
    if paths.is_empty() {
23370×
        if repo.config.sparse_paths.is_empty() {
23380×
            println!("No sparse filter: the whole tree is materialized.");
23390×
        } else {
23400×
            println!("{}", ui::heading("Sparse filter"));
23410×
            for p in &repo.config.sparse_paths {
23420×
                println!("  {}", ui::path(p));
23430×
            }
2344
        }
23450×
        return Ok(0);
23460×
    }
23470×
    let snap = repo.snapshot("oxy sparse")?;
23480×
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
23490×
        anyhow::bail!(
2350
            "the working copy has changes; commit them before changing the sparse filter"
2351
        );
23520×
    }
23530×
    repo.config.set("filter.paths", &paths.join(","))?;
23540×
    repo.save_config()?;
23550×
    let heads = repo.bookmark_heads()?;
23560×
    let sp = ui::spinner("Re-checking out with the new filter…");
23570×
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
23580×
    sp.done(&format!(
23590×
        "{} {}: {} written, {} removed",
23600×
        ui::done("Sparse filter set to"),
23610×
        ui::path(paths.join(",")),
23620×
        plural(r.written, "file"),
23630×
        r.removed
23640×
    ));
23650×
    Ok(0)
23660×
}
2367
23682×
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
23692×
    let repo = open()?;
23702×
    repo.snapshot_status("oxy tag")?;
23712×
    let heads = if changes.is_empty() {
23722×
        repo.bookmark_heads()?
2373
    } else {
23740×
        let mut heads = Vec::new();
23750×
        for c in changes {
23760×
            heads.extend(repo.resolve_heads(c)?);
2377
        }
23780×
        heads
2379
    };
23802×
    let t = repo.tag_create(name, &heads, message)?;
23812×
    println!(
2382
        "{} {} {} {} ({}){}",
23832×
        ui::done("Tagged"),
23842×
        ui::bookmark(&t.name),
23852×
        ui::dim(ui::glyph("→", "->")),
23862×
        ui::hash(format!("#{}", t.state.short(12))),
23872×
        plural(t.heads.len(), "head"),
23882×
        t.signer
23892×
            .map(|s| format!(", signed by {s}"))
23902×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2391
    );
23922×
    Ok(0)
23932×
}
2394
23950×
pub fn tag_delete(name: &str, reason: &str) -> Result<i32> {
23960×
    let repo = open()?;
23970×
    let t = repo.tag_delete(name, reason)?;
23980×
    println!(
2399
        "{} {} {} {}{}",
24000×
        ui::done("Withdrew"),
24010×
        ui::bookmark(&t.name),
24020×
        ui::dim(ui::glyph("→", "->")),
24030×
        ui::hash(format!("#{}", t.state.short(12))),
24040×
        t.signer
24050×
            .map(|s| format!(", signed by {s}"))
24060×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2407
    );
24080×
    println!(
2409
        "  {} {}",
24100×
        ui::note(),
24110×
        ui::dim("`oxy push` sends the withdrawal to a remote that has the tag; the name is not used again")
2412
    );
24130×
    Ok(0)
24140×
}
2415
24161×
pub fn tag_list(as_json: bool) -> Result<i32> {
24171×
    let repo = open()?;
24181×
    let tags = repo.tags()?;
24191×
    if as_json {
24201×
        println!(
2421
            "{}",
24221×
            json::arr(tags.iter().map(|t| {
24231×
                json::obj([
24241×
                    ("name", json::s(&t.name)),
24251×
                    ("state", json::s(&t.state.to_hex())),
24261×
                    ("heads", json::hashes(&t.heads)),
24271×
                    ("message", json::s(&t.message)),
2428
                    (
24291×
                        "signer",
24301×
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2431
                    ),
2432
                ])
24331×
            }))
2434
        );
24351×
        return Ok(0);
24360×
    }
24370×
    if tags.is_empty() {
24380×
        println!("{}", ui::dim("No tags."));
24390×
    }
24400×
    for t in tags {
24410×
        println!(
2442
            "{} {} {}{}{}{}",
24430×
            ui::ok(ui::glyph("⚑", "#")),
24440×
            ui::bookmark(&t.name),
2445
            // The heads, as `oxy log` shows changes, not the state hash.
24460×
            ui::hash(
24470×
                t.heads
24480×
                    .iter()
24490×
                    .map(|h| format!("#{}", h.short(12)))
24500×
                    .collect::<Vec<_>>()
24510×
                    .join(" ")
2452
            ),
24530×
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
24540×
            if t.message.is_empty() {
24550×
                String::new()
2456
            } else {
24570×
                format!("  {}", ui::subject(subject_of(&t.message)))
2458
            },
24590×
            t.signer
24600×
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
24610×
                .unwrap_or_default()
2462
        );
2463
    }
24640×
    Ok(0)
24651×
}
2466
2467
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2468
/// and workspace add take as "be on this bookmark" (oxygen#60).
24690×
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
24700×
    Ok(repo.view()?.bookmarks.contains_key(name)
24710×
        || repo
24720×
            .remote_only_bookmarks()?
24730×
            .iter()
24740×
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
24750×
}
2476
24770×
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
24780×
    let repo = open()?;
2479
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2480
    // this workspace's bookmark with that one's files.
24810×
    if let [name] = changes {
24820×
        if names_bookmark(&repo, name)? {
24830×
            let (local, _) = repo.local_bookmark_for(name)?;
24840×
            let heads = repo.resolve_heads(&local)?;
24850×
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
24860×
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
24870×
            sp.done(&format!(
24880×
                "{} {} (workspace {}) on {}",
24890×
                ui::done("Workspace created at"),
24900×
                ui::path(ws.root().display()),
24910×
                ui::id(ws.workspace().short(8)),
24920×
                ui::bookmark(&local)
24930×
            ));
24940×
            return Ok(0);
24950×
        }
24960×
    }
24970×
    let heads = if changes.is_empty() {
24980×
        None
2499
    } else {
25000×
        let mut heads = Vec::new();
25010×
        for c in changes {
25020×
            heads.extend(repo.resolve_heads(c)?);
2503
        }
25040×
        Some(heads)
2505
    };
25060×
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
25070×
    let ws = repo.workspace_add(path, heads.as_deref())?;
25080×
    sp.done(&format!(
25090×
        "{} {} (workspace {})",
25100×
        ui::done("Workspace created at"),
25110×
        ui::path(ws.root().display()),
25120×
        ui::id(ws.workspace().short(8))
25130×
    ));
25140×
    Ok(0)
25150×
}
2516
25171×
pub fn workspace_list(as_json: bool) -> Result<i32> {
25181×
    let repo = open()?;
25191×
    if as_json {
25201×
        println!(
2521
            "{}",
25221×
            json::arr(repo.workspaces()?.iter().map(|w| {
25231×
                json::obj([
25241×
                    ("id", json::s(&w.id.to_hex())),
25251×
                    ("path", json::s(&w.path.to_string_lossy())),
25261×
                    ("current", json::b(w.current)),
2527
                    (
25281×
                        "working_copy",
25291×
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2530
                    ),
2531
                ])
25321×
            }))
2533
        );
25341×
        return Ok(0);
25350×
    }
25360×
    for w in repo.workspaces()? {
25370×
        println!(
2538
            "{} {} {}{}",
25390×
            if w.current {
25400×
                ui::ok(ui::glyph("●", "*"))
2541
            } else {
25420×
                ui::dim(ui::glyph("○", "o"))
2543
            },
25440×
            ui::id(w.id.short(8)),
25450×
            ui::path(w.path.display()),
25460×
            w.working_copy
25470×
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
25480×
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2549
        );
2550
    }
25510×
    Ok(0)
25521×
}
2553
25540×
pub fn workspace_forget(spec: &str) -> Result<i32> {
25550×
    let repo = open()?;
25560×
    let all = repo.workspaces()?;
25570×
    let target = std::fs::canonicalize(spec).ok();
25580×
    let matches: Vec<_> = all
25590×
        .iter()
25600×
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
25610×
        .collect();
25620×
    let w = match matches.as_slice() {
25630×
        [w] => *w,
25640×
        [] => anyhow::bail!("no workspace matches {spec:?}"),
25650×
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2566
    };
25670×
    repo.workspace_forget(&w.id)?;
25680×
    println!(
2569
        "{} workspace {} at {}; its files were left in place.",
25700×
        ui::done("Forgot"),
25710×
        ui::id(w.id.short(8)),
25720×
        ui::path(w.path.display())
2573
    );
25740×
    Ok(0)
25750×
}
2576
25770×
pub fn lock(path: &str) -> Result<i32> {
25780×
    let repo = open()?;
25790×
    repo.lock_path(path)?;
25800×
    println!(
2581
        "{} {} {}",
25820×
        ui::done("Locked"),
25830×
        ui::path(path),
25840×
        ui::dim("(advisory, local)")
2585
    );
25860×
    Ok(0)
25870×
}
2588
25890×
pub fn unlock(path: &str) -> Result<i32> {
25900×
    let repo = open()?;
25910×
    repo.unlock_path(path)?;
25920×
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
25930×
    Ok(0)
25940×
}
2595
25960×
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
25970×
    let repo = open()?;
25980×
    let h = repo.resolve_change(change)?;
25990×
    let (h1, h2) = repo.split(&h, paths)?;
26000×
    let c1 = repo.store().get_change_meta(&h1)?;
26010×
    let c2 = repo.store().get_change_meta(&h2)?;
26020×
    println!(
2603
        "{} into {} {} and {} {}",
26040×
        ui::done("Split"),
26050×
        ui::id(c1.change_id.short(8)),
26060×
        ui::hash(format!("#{}", h1.short(12))),
26070×
        ui::id(c2.change_id.short(8)),
26080×
        ui::hash(format!("#{}", h2.short(12)))
2609
    );
26100×
    Ok(0)
26110×
}
2612
26136×
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
26146×
    let mut heads = Vec::new();
26156×
    for c in changes {
26166×
        heads.extend(repo.resolve_heads(c)?);
2617
    }
26186×
    Ok(heads)
26196×
}
2620
26216×
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
26226×
    let repo = open()?;
26236×
    repo.snapshot_status("oxy bookmark create")?;
26246×
    let heads = if changes.is_empty() {
26253×
        None
2626
    } else {
26273×
        let named = heads_from(&repo, changes)?;
26283×
        let (_, wc) = repo.working_copy()?;
26293×
        let gap = repo.state_gap(&wc.deps, &named)?;
26303×
        if upto {
26311×
            Some(gap.upto)
26322×
        } else if only || gap.earlier.is_empty() {
26331×
            Some(named)
2634
        } else {
26351×
            anyhow::bail!(
2636
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2637
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2638
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2639
                 or --only for just {0} and what it depends on.",
26401×
                changes.join(" "),
26411×
                plural(gap.earlier.len(), "change"),
26421×
                listed_changes(&repo, &gap.earlier)
2643
            );
2644
        }
2645
    };
26465×
    let heads = repo.bookmark_create(name, heads.as_deref())?;
26475×
    println!(
2648
        "{} bookmark {} {} {}",
26495×
        ui::done("Created"),
26505×
        ui::bookmark(name),
26515×
        ui::dim(ui::glyph("→", "->")),
26525×
        ui::dim(plural(heads.len(), "head"))
2653
    );
26545×
    println!(
2655
        "  {} {}",
26565×
        ui::note(),
26575×
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2658
    );
26595×
    Ok(0)
26606×
}
2661
2662
/// Up to five changes, newest last, as `  #hash subject` lines.
26632×
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
26642×
    let shown = changes.len().min(5);
26652×
    let mut lines: Vec<String> = changes[changes.len() - shown..]
26662×
        .iter()
26672×
        .map(|h| {
26682×
            let subject = repo
26692×
                .store()
26702×
                .get_change(h)
26712×
                .map(|c| subject_of(&c.message).to_string())
26722×
                .unwrap_or_default();
26732×
            format!("  #{} {subject}", h.short(12))
26742×
        })
26752×
        .collect();
26762×
    if changes.len() > shown {
26770×
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
26782×
    }
26792×
    lines.join("\n")
26802×
}
2681
26823×
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
26833×
    let repo = open()?;
26843×
    repo.snapshot_status("oxy bookmark set")?;
26853×
    let named = heads_from(&repo, changes)?;
2686
    // What the bookmark holds now and the new heads would leave out.
26873×
    let current = repo
26883×
        .bookmarks()?
26893×
        .into_iter()
26906×
        .find(|b| b.name == name)
26913×
        .map(|b| b.heads)
26923×
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
26933×
    let gap = repo.state_gap(&current, &named)?;
2694
    // A fast-forward: the new heads hold the bookmark's newest head, so
2695
    // what they leave out is older work nothing since has built on, such
2696
    // as an early change no later one depends on (oxygen#78). Keep it, as
2697
    // --upto does, and say so.
26983×
    let newest = current
26993×
        .iter()
27008×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m.hlc, *h)))
27013×
        .max()
27023×
        .map(|(_, h)| h);
2703
    // Ahead, too: a head the bookmark holds already (it would only drop
2704
    // the others) is not a move forward.
27053×
    let ahead = repo
27063×
        .load_state_history(&current)
27073×
        .is_ok_and(|st| named.iter().any(|h| !st.contains(h)));
27083×
    let forward = !only
27093×
        && ahead
27101×
        && !gap.earlier.is_empty()
27111×
        && newest.is_some_and(|n| {
27121×
            repo.load_state_history(&named)
27131×
                .is_ok_and(|st| st.contains(&n))
27141×
        });
27153×
    let heads = if upto {
27161×
        gap.upto
27172×
    } else if forward {
27181×
        println!(
2719
            "  {} {}",
27201×
            ui::note(),
27211×
            ui::dim(format!(
2722
                "{} builds on {name}'s newest head; keeping {} it holds that {0} does not depend on",
27231×
                changes.join(" "),
27241×
                plural(gap.earlier.len(), "change")
2725
            ))
2726
        );
27271×
        gap.upto
27281×
    } else if only || gap.earlier.is_empty() {
27290×
        named
2730
    } else {
27311×
        anyhow::bail!(
2732
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2733
             A state is its heads and what they depend on, not everything recorded before them.\n\
2734
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2735
             or --only for just {0} and what it depends on.",
27361×
            changes.join(" "),
27371×
            plural(gap.earlier.len(), "change"),
27381×
            listed_changes(&repo, &gap.earlier)
2739
        );
2740
    };
27412×
    let heads = repo.bookmark_set(name, &heads)?;
27422×
    println!(
2743
        "{} bookmark {} {} {}",
27442×
        ui::done("Moved"),
27452×
        ui::bookmark(name),
27462×
        ui::dim(ui::glyph("→", "->")),
27472×
        ui::dim(plural(heads.len(), "head"))
2748
    );
27492×
    Ok(0)
27503×
}
2751
27520×
pub fn bookmark_delete(name: &str) -> Result<i32> {
27530×
    let repo = open()?;
27540×
    repo.bookmark_delete(name)?;
27550×
    println!(
2756
        "{} bookmark {} {}",
27570×
        ui::done("Deleted"),
27580×
        ui::bookmark(name),
27590×
        ui::dim("(its changes stay until unreachable)")
2760
    );
27610×
    Ok(0)
27620×
}
2763
2764
/// Heads with their metadata, newest first.
27650×
fn heads_newest_first(
27660×
    repo: &Repo,
27670×
    heads: &[oxy_core::hash::ChangeHash],
27680×
) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> {
27690×
    let mut out: Vec<_> = heads
27700×
        .iter()
27710×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m)))
27720×
        .collect();
27730×
    out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc));
27740×
    out
27750×
}
2776
2777
/// One head as a line: id, hash, author, when, subject.
27780×
fn print_head(
27790×
    repo: &Repo,
27800×
    indent: &str,
27810×
    h: &oxy_core::hash::ChangeHash,
27820×
    m: &oxy_core::state::ChangeMeta,
27830×
) {
27840×
    println!(
2785
        "{indent}{} {} {}{}{}{}{}",
27860×
        ui::id(m.change_id.short(8)),
27870×
        ui::dim(format!("#{}", &h.to_hex()[..8])),
27880×
        author_name(repo, m),
27890×
        ui::sep(),
27900×
        ui::dim(ui::ago(m.hlc.wall_ms)),
27910×
        ui::sep(),
27920×
        ui::subject(subject_of(&m.message))
2793
    );
27940×
}
2795
27960×
pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result<i32> {
27970×
    let repo = open()?;
27980×
    let name = name.unwrap_or(&repo.config.bookmark).to_string();
27990×
    let view = repo.view()?;
28000×
    let st = match view.bookmarks.get(&name) {
28010×
        Some(st) => *st,
28020×
        None => match oxy_core::repo::remote_bookmark(&view, &name) {
28030×
            Some((_, _, st)) => st,
28040×
            None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"),
2805
        },
2806
    };
28070×
    let heads = repo.store().get_state(&st)?.heads;
28080×
    let shown = heads_newest_first(&repo, &heads);
28090×
    if as_json {
28100×
        println!(
2811
            "{}",
28120×
            json::obj([
28130×
                ("name", json::s(&name)),
28140×
                ("current", json::b(name == repo.config.bookmark)),
2815
                (
28160×
                    "heads",
28170×
                    json::arr(shown.iter().map(|(h, m)| {
28180×
                        json::obj([
28190×
                            ("hash", json::s(&h.to_hex())),
28200×
                            ("id", json::s(&m.change_id.to_string())),
28210×
                            ("author", json::s(&author_name(&repo, m))),
28220×
                            ("time_ms", json::n(m.hlc.wall_ms)),
28230×
                            ("subject", json::s(subject_of(&m.message))),
28240×
                        ])
28250×
                    }))
2826
                ),
2827
            ])
2828
        );
28290×
        return Ok(0);
28300×
    }
28310×
    println!(
2832
        "{} {}{}{}",
28330×
        ui::ok(ui::glyph("●", "*")),
28340×
        ui::bookmark(&name),
28350×
        ui::sep(),
28360×
        ui::dim(plural(heads.len(), "head"))
2837
    );
28380×
    for (h, m) in &shown {
28390×
        print_head(&repo, "  ", h, m);
28400×
    }
28410×
    if heads.len() > 1 {
28420×
        println!(
28430×
            "  {}",
28440×
            ui::dim("None depends on another: the bookmark is all of them and their dependencies.")
28450×
        );
28460×
    }
28470×
    Ok(0)
28480×
}
2849
28505×
pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result<i32> {
28515×
    let repo = open()?;
28525×
    let remote_only = repo.remote_only_bookmarks()?;
28535×
    if as_json {
28545×
        let mut items: Vec<String> = repo
28555×
            .bookmarks()?
28565×
            .into_iter()
285713×
            .map(|b| {
285813×
                json::obj([
285913×
                    ("name", json::s(&b.name)),
286013×
                    ("heads", json::hashes(&b.heads)),
286113×
                    ("current", json::b(b.current)),
286213×
                    ("ahead", json::opt(b.ahead, json::n)),
286313×
                    ("behind", json::opt(b.behind, json::n)),
286413×
                    ("remote", json::opt(b.remote.as_deref(), json::s)),
286513×
                ])
286613×
            })
28675×
            .collect();
28685×
        if all {
28690×
            items.extend(remote_only.iter().map(|b| {
28700×
                json::obj([
28710×
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
28720×
                    ("heads", json::hashes(&b.heads)),
28730×
                    ("current", json::b(false)),
28740×
                    ("ahead", "null".into()),
28750×
                    ("behind", "null".into()),
28760×
                    ("remote", json::s(&b.remote)),
28770×
                ])
28780×
            }));
28795×
        }
28805×
        println!("{}", json::arr(items));
28815×
        return Ok(0);
28820×
    }
28830×
    for b in repo.bookmarks()? {
28840×
        let mark = if b.current {
28850×
            ui::ok(ui::glyph("●", "*"))
2886
        } else {
28870×
            ui::dim(ui::glyph("○", "o"))
2888
        };
28890×
        let mut tail = String::new();
28900×
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
28910×
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
28920×
        }
28930×
        if let Some(n) = b.behind.filter(|n| *n > 0) {
28940×
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
28950×
        }
2896
        // Which remote, when there is a choice (oxygen#83).
28970×
        if !tail.is_empty() && repo.config.remotes.len() > 1 {
28980×
            if let Some(r) = &b.remote {
28990×
                tail += &ui::dim(format!(" {r}"));
29000×
            }
29010×
        }
29020×
        let shown = heads_newest_first(&repo, &b.heads);
2903
        // The newest head's subject, so a busy bookmark shows its latest work.
29040×
        let head = match shown.first() {
29050×
            Some(_) if verbose => String::new(),
29060×
            Some((_, m)) if b.heads.len() > 1 => format!(
2907
                "{} {}",
29080×
                ui::dim("newest"),
29090×
                ui::subject(subject_of(&m.message))
2910
            ),
29110×
            Some((_, m)) => ui::subject(subject_of(&m.message)),
29120×
            None => ui::dim("(empty)"),
2913
        };
29140×
        let head = if head.is_empty() {
29150×
            head
2916
        } else {
29170×
            format!("  {head}")
2918
        };
29190×
        println!(
2920
            "{mark} {}{}{}{tail}{head}",
29210×
            ui::bookmark(&b.name),
29220×
            ui::sep(),
29230×
            ui::dim(plural(b.heads.len(), "head"))
2924
        );
29250×
        if verbose {
29260×
            for (h, m) in &shown {
29270×
                print_head(&repo, "    ", h, m);
29280×
            }
29290×
        }
2930
    }
29310×
    if remote_only.is_empty() {
29320×
        return Ok(0);
29330×
    }
29340×
    if !all {
29350×
        println!(
2936
            "{}",
29370×
            ui::dim(format!(
2938
                "  and {} only on a remote: oxy bookmark list --all",
29390×
                plural(remote_only.len(), "bookmark")
2940
            ))
2941
        );
29420×
        return Ok(0);
29430×
    }
29440×
    for b in &remote_only {
29450×
        println!(
29460×
            "{} {}{}{}",
29470×
            ui::dim(ui::glyph("◌", ".")),
29480×
            ui::dim(format!("{}/{}", b.remote, b.name)),
29490×
            ui::sep(),
29500×
            ui::dim(plural(b.heads.len(), "head"))
29510×
        );
29520×
    }
29530×
    println!(
2954
        "  {} {}",
29550×
        ui::note(),
29560×
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2957
    );
29580×
    Ok(0)
29595×
}
2960
29613×
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
29623×
    let mut repo = open()?;
29633×
    let from = repo.config.bookmark.clone();
29643×
    let (local, created_from) = repo.local_bookmark_for(name)?;
29653×
    if let Some(remote) = created_from {
29660×
        println!(
29670×
            "{} {} from {}",
29680×
            ui::done("Created"),
29690×
            ui::bookmark(&local),
29700×
            ui::dim(format!("{remote}/{local}"))
29710×
        );
29723×
    }
29733×
    let name = local.as_str();
2974
    // Only behind its remote: take the remote's state, so the switch does
2975
    // not check out a stale one (oxygen#74).
29763×
    if let Some(n) = repo.catch_up_bookmark(name)? {
29770×
        println!(
29780×
            "{} {} with {}: {} it lacked",
29790×
            ui::done("Caught up"),
29800×
            ui::bookmark(name),
29810×
            ui::dim(format!("{}/{name}", repo.default_remote())),
29820×
            plural(n, "change")
29830×
        );
29843×
    }
29853×
    let sp = ui::spinner(&format!("Switching to {name}…"));
29863×
    let (r, carried) = if carry {
29870×
        repo.bookmark_switch_carry(name)?
2988
    } else {
29893×
        (repo.bookmark_switch(name, discard)?, vec![])
2990
    };
29913×
    sp.done(&format!(
2992
        "{} to {}: {} written, {} removed{}",
29933×
        ui::done("Switched"),
29943×
        ui::bookmark(name),
29953×
        plural(r.written, "file"),
2996
        r.removed,
29973×
        if carried.is_empty() {
29983×
            String::new()
2999
        } else {
30000×
            format!("; carried {}", plural(carried.len(), "changed path"))
3001
        }
3002
    ));
30033×
    print_removed(&r);
30043×
    print_carried(&carried);
30053×
    print_kept_both(&r);
30063×
    if r.conflicted {
30070×
        println!(
30080×
            "  {} {}",
30090×
            ui::caution(),
30100×
            ui::warn("this state has conflicts; see oxy status")
30110×
        );
30123×
    }
3013
    // Say when the new state leaves out work the old one had: a state is
3014
    // its heads and what they depend on, which can be far less than a Git
3015
    // user expects.
30163×
    if r.lacks > 0 {
30171×
        println!(
30181×
            "  {} {}",
30191×
            ui::note(),
30201×
            ui::dim(format!(
30211×
                "{name} lacks {} that {from} has",
30221×
                plural(r.lacks, "change")
30231×
            ))
30241×
        );
30252×
    }
30263×
    super::sync::subrepos_behind(&repo);
30273×
    where_now(&repo);
30283×
    Ok(0)
30293×
}
3030
30310×
pub fn merge(bookmark: &str) -> Result<i32> {
30320×
    let repo = open()?;
30330×
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
30340×
    let r = repo.merge(bookmark)?;
30350×
    if !r.changed {
30360×
        sp.done(&format!(
30370×
            "{} {}",
30380×
            ui::ok(ui::glyph("✔", "*")),
30390×
            ui::dim(format!(
30400×
                "{} already contains {bookmark}",
30410×
                repo.config.bookmark
30420×
            ))
30430×
        ));
30440×
        return Ok(0);
30450×
    }
30460×
    sp.done(&format!(
3047
        "{} {} into {}: now {}{}",
30480×
        ui::done("Merged"),
30490×
        ui::bookmark(bookmark),
30500×
        ui::bookmark(&repo.config.bookmark),
30510×
        plural(r.heads.len(), "head"),
30520×
        ui::dim(if r.checked_out {
30530×
            "; working copy updated"
3054
        } else {
30550×
            "; run oxy checkout to update the working copy"
3056
        })
3057
    ));
30580×
    let snap = repo.snapshot("oxy merge")?;
30590×
    if snap.base_snapshot.is_conflicted() {
30600×
        println!(
30610×
            "  {} {}",
30620×
            ui::caution(),
30630×
            ui::warn("the result has conflicts; see oxy status")
30640×
        );
30650×
    }
30660×
    where_now(&repo);
30670×
    Ok(0)
30680×
}
3069
30700×
pub fn squash(change: &str, into: &str) -> Result<i32> {
30710×
    let repo = open()?;
30720×
    let c = repo.resolve_change(change)?;
30730×
    let d = repo.resolve_change(into)?;
30740×
    let sp = ui::spinner("Squashing…");
30750×
    let h = repo.squash(&c, &d)?;
30760×
    let new = repo.store().get_change_meta(&h)?;
30770×
    sp.done(&format!(
30780×
        "{} into {} {}  {}",
30790×
        ui::done("Squashed"),
30800×
        ui::id(new.change_id.short(8)),
30810×
        ui::hash(format!("#{}", h.short(12))),
30820×
        ui::subject(subject_of(&new.message))
30830×
    ));
30840×
    Ok(0)
30850×
}
3086
30870×
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
30880×
    let repo = open()?;
30890×
    let c = repo.resolve_change(change)?;
30900×
    let mut heads = Vec::new();
30910×
    for o in onto {
30920×
        heads.extend(repo.resolve_heads(o)?);
3093
    }
30940×
    let sp = ui::spinner("Rebasing…");
30950×
    let h = match repo.rebase(&c, &heads) {
30960×
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
30970×
            let r = repo.rebase_into_working_copy(&c, &heads)?;
30980×
            sp.done(&format!(
30990×
                "{} {} into {}: now {}",
31000×
                ui::done("Merged"),
31010×
                onto.join(" "),
31020×
                ui::bookmark(&repo.config.bookmark),
31030×
                plural(r.heads.len(), "head"),
31040×
            ));
31050×
            if r.checked_out {
31060×
                println!(
31070×
                    "  {} {}",
31080×
                    ui::caution(),
31090×
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
31100×
                );
31110×
            } else {
31120×
                println!(
31130×
                    "  {} {}",
31140×
                    ui::caution(),
31150×
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
31160×
                );
31170×
            }
31180×
            where_now(&repo);
31190×
            return Ok(0);
3120
        }
31210×
        other => other?,
3122
    };
31230×
    let new = repo.store().get_change_meta(&h)?;
31240×
    sp.done(&format!(
31250×
        "{} {} {}  {}",
31260×
        ui::done("Rebased"),
31270×
        ui::id(new.change_id.short(8)),
31280×
        ui::hash(format!("#{}", h.short(12))),
31290×
        ui::dim(format!(
31300×
            "now depends on {}",
31310×
            plural(new.deps.len(), "change")
31320×
        ))
31330×
    ));
31340×
    where_now(&repo);
31350×
    Ok(0)
31360×
}
3137
3138
#[cfg(test)]
3139
mod tests {
3140
    use super::*;
3141
3142
    #[test]
31431×
    fn id_prefixes_agree_with_the_whole_list() {
3144
        // Ids that share long prefixes, and some that differ only in a
3145
        // half byte, from a fixed sequence.
31461×
        let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
31477999×
        let mut next = || {
31487999×
            x ^= x << 13;
31497999×
            x ^= x >> 7;
31507999×
            x ^= x << 17;
31517999×
            x
31527999×
        };
31531×
        let mut ids: Vec<[u8; 16]> = Vec::new();
31541×
        for _ in 0..2000 {
31552000×
            let mut id = [0u8; 16];
31562000×
            id[..8].copy_from_slice(&next().to_le_bytes());
31572000×
            id[8..].copy_from_slice(&next().to_le_bytes());
31582000×
            let share = (next() % 4) as usize;
31592000×
            if let Some(prev) = ids.last() {
31601999×
                id[..share].copy_from_slice(&prev[..share]);
31611999×
                if next() % 2 == 0 {
3162973×
                    id[share] = (prev[share] & 0xf0) | (id[share] & 0x0f);
31631026×
                }
31641×
            }
31652000×
            ids.push(id);
3166
        }
31674000×
        let hex = |id: &[u8; 16]| oxy_core::ids::ChangeId(*id).to_hex();
31681×
        let whole = unique_prefixes(ids.iter().map(hex));
31691×
        let some = id_prefixes(ids.clone(), ids.iter().copied());
31702000×
        for id in &ids {
31712000×
            assert_eq!(some[id], whole[&hex(id)], "{}", hex(id));
3172
        }
31731×
    }
3174
}