OXYGENHUB

Coverage / src/cli/workspace.rs 40.3%

1014 of 2515 lines run, 98 of 355 functions · run #425 on main · run missed

1
//! Commands that act on the local repository and working copy.
2
3
use super::format::{
4
    author_name, awaits_seal, deps_line, deps_of, plural, short_id, signature_line,
5
    signature_mark_of, 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(
8303×
                &status,
8313×
                awaits_seal(&repo, &status, &c.author),
832
            ));
8331×
        }
8344×
        println!("{}{}", node_line(row, &bullet), head.join(" "));
8354×
        let subject = if e.is_working_copy && c.message.is_empty() {
8361×
            let edited = repo
8371×
                .store()
8381×
                .get_change(&e.hash)
8391×
                .is_ok_and(|w| !w.tree_ops.is_empty() || !w.edits.is_empty());
8401×
            ui::dim(if edited {
8410×
                "(working copy, uncommitted changes)"
842
            } else {
8431×
                "(working copy)"
844
            })
8453×
        } else if c.message.trim().is_empty() {
8460×
            ui::dim("(no description)")
847
        } else {
8483×
            subject_of(&c.message).to_string()
849
        };
8504×
        println!("{}{subject}", below_line(row));
8514×
        if verbose {
8520×
            let rail = continuation(row);
8530×
            if !e.is_working_copy {
8540×
                println!(
855
                    "{rail}{}",
8560×
                    ui::dim(format!(
857
                        "{} {}",
8580×
                        when(c.hlc.wall_ms),
8590×
                        signature_line(&repo, &e.hash)?
860
                    ))
861
                );
8620×
            }
8630×
            if !c.deps.is_empty() {
8640×
                println!(
8650×
                    "{rail}{} {}",
8660×
                    ui::dim(ui::glyph("↳", "->")),
8670×
                    ui::dim(deps_of(&c.deps))
8680×
                );
8690×
            }
8700×
            let body: Vec<&str> = c
8710×
                .message
8720×
                .lines()
8730×
                .skip(1)
8740×
                .skip_while(|l| l.trim().is_empty())
8750×
                .collect();
8760×
            for line in body {
8770×
                println!("{rail}  {line}");
8780×
            }
8794×
        }
880
    }
8811×
    if shown < total {
8820×
        if let Some(last) = rows.get(shown.saturating_sub(1)) {
8830×
            let cut: String = last
8840×
                .below
8850×
                .iter()
8860×
                .map(|c| match c {
8870×
                    Cell::Blank | Cell::Elided | Cell::JoinRight => "  ",
8880×
                    _ => "~ ",
8890×
                })
8900×
                .collect();
8910×
            if cut.trim().is_empty() {
8920×
                println!("{}", ui::dim("~"));
8930×
            } else {
8940×
                println!("{}", ui::dim(cut.trim_end()));
8950×
            }
8960×
        }
8970×
        println!(
898
            "{}",
8990×
            ui::dim(format!(
900
                "{} {} more; pass -n to see them",
9010×
                ui::glyph("…", "..."),
9020×
                total - shown
903
            ))
904
        );
9051×
    }
9061×
    Ok(0)
90710×
}
908
909
/// Rows a drawn edge may span in `oxy log`; a longer one is elided (`~`).
910
const MAX_EDGE: usize = 12;
911
912
use oxy_core::hash::ChangeHash;
913
use oxy_core::lanes::{Cell, GraphRow};
914
915
/// A graph cell, two columns wide.
9166×
fn cell(c: Cell) -> &'static str {
9176×
    match c {
9181×
        Cell::Blank => "  ",
9193×
        Cell::Line => ui::glyph("│ ", "| "),
9200×
        Cell::Elided => "~ ",
9211×
        Cell::JoinLeft => ui::glyph("├─", "|-"),
9220×
        Cell::JoinPass => ui::glyph("──", "--"),
9230×
        Cell::JoinCross => ui::glyph("┼─", "+-"),
9241×
        Cell::JoinRight => ui::glyph("╯ ", "' "),
925
    }
9266×
}
927
928
/// The graph part of a change's own line, its bullet in its column.
9294×
fn node_line(row: &GraphRow, bullet: &str) -> String {
9304×
    let width = row
9314×
        .passing
9324×
        .iter()
9334×
        .copied()
9344×
        .max()
9354×
        .unwrap_or(0)
9364×
        .max(row.column)
9374×
        + 1;
9384×
    let mut out = String::new();
9395×
    for c in 0..width {
9405×
        if c == row.column {
9414×
            out.push_str(bullet);
9424×
            out.push(' ');
9434×
        } else if row.passing.contains(&c) {
9441×
            out.push_str(&ui::dim(cell(Cell::Line)));
9451×
        } else {
9460×
            out.push_str("  ");
9470×
        }
948
    }
9494×
    out.push(' ');
9504×
    out
9514×
}
952
953
/// The graph part of the line under a change: lanes carrying on, a join,
954
/// or `~` for an elided edge.
9554×
fn below_line(row: &GraphRow) -> String {
9565×
    let g: String = row.below.iter().map(|c| cell(*c)).collect();
9574×
    format!("{} ", ui::dim(g))
9584×
}
959
960
/// The graph part of any further line of a change (`-v`).
9610×
fn continuation(row: &GraphRow) -> String {
9620×
    let g: String = row
9630×
        .below
9640×
        .iter()
9650×
        .map(|c| match c {
9660×
            Cell::Line | Cell::JoinLeft | Cell::JoinCross => cell(Cell::Line),
9670×
            _ => "  ",
9680×
        })
9690×
        .collect();
9700×
    format!("{} ", ui::dim(g))
9710×
}
972
973
/// For each hex ID, the length of its shortest prefix no other ID shares.
974
/// The shortest prefix, in hex digits, that names each of `wanted` among
975
/// `all`: worked out for the few shown rather than for the whole history.
9762×
fn id_prefixes(
9772×
    mut all: Vec<[u8; 16]>,
9782×
    wanted: impl Iterator<Item = [u8; 16]>,
9792×
) -> std::collections::HashMap<[u8; 16], usize> {
9802×
    all.sort_unstable();
9812×
    all.dedup();
982
    // Hex digits two ids share at the start.
9834004×
    let common = |a: &[u8; 16], b: &[u8; 16]| {
98410720×
        let bytes = a.iter().zip(b).take_while(|(x, y)| x == y).count();
9854004×
        match (a.get(bytes), b.get(bytes)) {
9864004×
            (Some(x), Some(y)) if x >> 4 == y >> 4 => 2 * bytes + 1,
9871856×
            _ => 2 * bytes,
988
        }
9894004×
    };
9902×
    let mut out = std::collections::HashMap::new();
9912004×
    for id in wanted {
9922004×
        let Ok(i) = all.binary_search(&id) else {
9930×
            continue;
994
        };
9952004×
        let before = i.checked_sub(1).map_or(0, |j| common(&all[j], &id));
9962004×
        let after = all.get(i + 1).map_or(0, |n| common(&id, n));
9972004×
        out.insert(id, before.max(after) + 1);
998
    }
9992×
    out
10002×
}
1001
10021×
fn unique_prefixes(ids: impl Iterator<Item = String>) -> std::collections::HashMap<String, usize> {
10031×
    let mut v: Vec<String> = ids.collect();
10041×
    v.sort();
10051×
    v.dedup();
100619576×
    let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
10071×
    let mut out = std::collections::HashMap::with_capacity(v.len());
10082000×
    for i in 0..v.len() {
10092000×
        let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 };
10102000×
        let after = if i + 1 < v.len() {
10111999×
            common(&v[i], &v[i + 1])
1012
        } else {
10131×
            0
1014
        };
10152000×
        out.insert(v[i].clone(), before.max(after) + 1);
1016
    }
10171×
    out
10181×
}
1019
1020
/// Bookmark, remote bookmark and tag names to show beside the changes they
1021
/// point at. A name is shown on each head of its state; one with more than
1022
/// three heads names too much of the log to help, so it is left out (oxy
1023
/// bookmark list shows it). A remote bookmark at the same state as the
1024
/// local one of that name is not repeated.
10251×
fn reference_labels(repo: &Repo) -> Result<std::collections::HashMap<ChangeHash, Vec<String>>> {
1026
    const MAX_HEADS: usize = 3;
10271×
    let view = repo.view()?;
10281×
    let mut out: std::collections::HashMap<ChangeHash, Vec<String>> = Default::default();
10291×
    let mut add = |heads: Vec<ChangeHash>, label: String| {
10301×
        if heads.len() <= MAX_HEADS {
10312×
            for h in heads {
10322×
                out.entry(h).or_default().push(label.clone());
10332×
            }
10340×
        }
10351×
    };
10361×
    for (name, st) in &view.bookmarks {
10371×
        add(repo.store().get_state(st)?.heads, ui::bookmark(name));
1038
    }
10391×
    for (remote, bookmarks) in &view.remotes {
10400×
        for (name, st) in bookmarks {
10410×
            if view.bookmarks.get(name) == Some(st) {
10420×
                continue;
10430×
            }
10440×
            add(
10450×
                repo.store().get_state(st)?.heads,
10460×
                ui::dim(format!("{remote}/{name}")),
1047
            );
1048
        }
1049
    }
10501×
    for t in repo.tags()? {
10510×
        add(t.heads.clone(), ui::warn(&t.name));
10520×
    }
10531×
    Ok(out)
10541×
}
1055
10561×
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
10571×
    let repo = open()?;
10581×
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
10591×
    if as_json {
10601×
        let files = repo.diff_files(hash.as_ref())?;
10613×
        let items = files.iter().map(|f| {
10623×
            json::obj([
10633×
                ("path", json::s(&f.path)),
10643×
                ("kind", json::s(&f.kind)),
10653×
                ("from", json::opt(f.from.as_deref(), json::s)),
1066
                (
10673×
                    "hunks",
10683×
                    json::arr(f.hunks.iter().map(|h| {
10693×
                        json::obj([
10703×
                            ("base_line", json::n(h.base_line)),
1071
                            (
10723×
                                "added",
10733×
                                json::arr(
10743×
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
1075
                                ),
1076
                            ),
1077
                            (
10783×
                                "removed",
10793×
                                json::arr(h.removed.iter().map(|(n, l)| {
10800×
                                    json::obj([
10810×
                                        ("line", json::n(*n)),
10820×
                                        ("text", json::s(&String::from_utf8_lossy(l))),
10830×
                                    ])
10840×
                                })),
1085
                            ),
1086
                        ])
10873×
                    })),
1088
                ),
1089
            ])
10903×
        });
10911×
        println!(
1092
            "{}",
10931×
            json::obj([
10941×
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
10951×
                ("files", json::arr(items))
1096
            ])
1097
        );
10981×
        return Ok(0);
10990×
    }
11000×
    match hash {
11010×
        Some(h) => {
11020×
            let c = repo.store().get_change(&h)?;
11030×
            let (base, snapshot) = repo.change_base(&c)?;
11040×
            print!("{}", render_change(&c, &base, &snapshot));
1105
        }
1106
        None => {
1107
            // Nothing changed: nothing to show, and no base to load.
11080×
            let Some((wc, base, snapshot)) = repo.working_copy_with_base_unless_unchanged()? else {
11090×
                return Ok(0);
1110
            };
11110×
            let text = {
11120×
                let _t = oxy_core::timing::phase("diff: render the change");
11130×
                render_change(&wc, &base, &snapshot)
1114
            };
11150×
            print!("{text}");
1116
            // The process ends here: freeing the base's tree and graphs
1117
            // one by one would only cost time (about 27 ms on Linux).
11180×
            std::mem::forget((wc, base, snapshot));
1119
        }
1120
    }
11210×
    Ok(0)
11221×
}
1123
11243×
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
11253×
    let repo = open()?;
11263×
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
11273×
    let bytes = match repo.file_at(path, heads.as_deref()) {
11283×
        Ok(b) => b,
1129
        // -r CHANGE reads that change's dependency closure, not the
1130
        // bookmark it is on: say so when the bookmark has the file
1131
        // (oxygen#76).
11320×
        Err(e) => match change {
11330×
            Some(c)
11340×
                if !repo.view()?.bookmarks.contains_key(c)
11350×
                    && repo.tag_heads(c)?.is_none()
11360×
                    && repo.file_at(path, None).is_ok() =>
1137
            {
11380×
                anyhow::bail!(
1139
                    "{path} is not in {c}'s dependency closure (the change and what it \
1140
                     depends on); it is on the bookmark: try -r {}, or --at-op OP for the \
1141
                     state at an operation",
1142
                    repo.config.bookmark
1143
                )
1144
            }
11450×
            _ => return Err(e.into()),
1146
        },
1147
    };
1148
    use std::io::Write as _;
11493×
    std::io::stdout().write_all(&bytes)?;
11503×
    Ok(0)
11513×
}
1152
11531×
pub fn root(as_json: bool) -> Result<i32> {
11541×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
11550×
        if as_json {
11560×
            println!("null");
11570×
        }
11580×
        return Ok(1);
1159
    };
11601×
    if as_json {
11611×
        println!(
11621×
            "{}",
11631×
            json::obj([
11641×
                ("root", json::s(&repo.root().to_string_lossy())),
11651×
                ("workspace", json::s(&repo.workspace().to_hex())),
11661×
                ("bookmark", json::s(&repo.config.bookmark))
11671×
            ])
11681×
        );
11691×
    } else {
11700×
        println!("{}", repo.root().display());
11710×
    }
11721×
    Ok(0)
11731×
}
1174
11751×
pub fn version(as_json: bool) -> Result<i32> {
11761×
    if as_json {
11771×
        println!(
11781×
            "{}",
11791×
            json::obj([
11801×
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
11811×
                // What was built: a release's or install's `oxy describe`,
11821×
                // a Flow build's heads, or "local build".
11831×
                ("build", json::s(env!("OXY_BUILD_ID"))),
11841×
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
11851×
                ("format", json::n(2))
11861×
            ])
11871×
        );
11881×
    } else {
11890×
        println!(
11900×
            "oxy {} (repository format 2, protocol {})",
11910×
            env!("OXY_VERSION_LONG"),
11920×
            oxy_core::protocol::PROTOCOL_VERSION
11930×
        );
11940×
    }
11951×
    Ok(0)
11961×
}
1197
11982×
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
11992×
    let repo = open()?;
12002×
    if paths.is_empty() && hunks.is_empty() {
12010×
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
12022×
    }
12032×
    let mut n = 0;
12042×
    if !hunks.is_empty() {
12051×
        n += repo.discard_hunks(hunks)?;
12061×
    }
12072×
    if !paths.is_empty() {
12081×
        n += repo.discard(paths)?;
12091×
    }
12102×
    println!(
1211
        "{} {} restored to the working copy's base",
12122×
        ui::done("Discarded"),
12132×
        plural(n, "path")
1214
    );
12152×
    Ok(0)
12162×
}
1217
12182×
pub fn hunks(as_json: bool) -> Result<i32> {
12192×
    let repo = open()?;
12202×
    let (_, hunks) = repo.hunks()?;
12212×
    if as_json {
12222×
        println!(
1223
            "{}",
12245×
            json::arr(hunks.iter().map(|h| json::obj([
12255×
                ("index", json::n(h.index)),
12265×
                ("path", json::s(&h.path)),
12275×
                ("text", json::s(&h.text))
12285×
            ])))
1229
        );
12302×
        return Ok(0);
12310×
    }
12320×
    if hunks.is_empty() {
12330×
        println!(
12340×
            "{}",
12350×
            ui::dim("No hunks: the working copy matches its base.")
12360×
        );
12370×
    }
12380×
    for h in &hunks {
12390×
        println!(
1240
            "{} {}",
12410×
            ui::section(format!("hunk {}", h.index)),
12420×
            ui::path(&h.path)
1243
        );
12440×
        for line in h.text.lines() {
12450×
            let styled = if line.starts_with('+') {
12460×
                ui::ok(line)
12470×
            } else if line.starts_with('-') {
12480×
                ui::err(line)
1249
            } else {
12500×
                ui::dim(line)
1251
            };
12520×
            println!("  {styled}");
1253
        }
1254
    }
12550×
    Ok(0)
12562×
}
1257
12583×
pub fn show(change: Option<&str>, revset: Option<&str>, stat: bool, as_json: bool) -> Result<i32> {
12593×
    let repo = open()?;
12603×
    repo.snapshot_status("oxy show")?;
12613×
    let Some(r) = revset else {
12623×
        let h = repo.resolve_change(change.unwrap_or("@"))?;
12633×
        return show_one(&repo, h, as_json, false, stat);
1264
    };
1265
    // Several changes: a JSON array, or the changes one after another.
12660×
    let hashes = repo.revset(r)?.hashes;
12670×
    if as_json {
12680×
        print!("[");
12690×
        for (i, h) in hashes.iter().enumerate() {
12700×
            if i > 0 {
12710×
                print!(",");
12720×
            }
12730×
            show_one(&repo, *h, true, true, stat)?;
1274
        }
12750×
        println!("]");
12760×
        return Ok(0);
12770×
    }
12780×
    if hashes.is_empty() {
12790×
        println!("{}", ui::dim(format!("No change matches {r:?}.")));
12800×
        return Ok(0);
12810×
    }
12820×
    for (i, h) in hashes.iter().enumerate() {
12830×
        if i > 0 {
12840×
            println!();
12850×
        }
12860×
        show_one(&repo, *h, false, false, stat)?;
1287
    }
12880×
    Ok(0)
12893×
}
1290
1291
/// Lines added and removed in one file's diff.
12922×
fn counts(f: &oxy_core::repo::FileDiff) -> (usize, usize) {
12932×
    f.hunks
12942×
        .iter()
12952×
        .fold((0, 0), |(a, r), h| (a + h.added.len(), r + h.removed.len()))
12962×
}
1297
1298
/// What `--stat` prints (oxygen#119): each file the change touched, its
1299
/// lines added and removed, then the total.
13001×
fn print_stat(files: &[oxy_core::repo::FileDiff]) {
13011×
    let width = files
13021×
        .iter()
13031×
        .map(|f| f.path.chars().count())
13041×
        .max()
13051×
        .unwrap_or(0)
13061×
        .min(60);
13071×
    let (mut added, mut removed) = (0, 0);
13081×
    for f in files {
13091×
        let (a, r) = counts(f);
13101×
        added += a;
13111×
        removed += r;
13121×
        let path = match &f.from {
13130×
            Some(from) => format!("{from} → {}", f.path),
13141×
            None => f.path.clone(),
1315
        };
13161×
        println!(
1317
            " {path:<width$}  {} {}  {}",
13181×
            ui::ok(format!("{:>6}", format!("+{a}"))),
13191×
            ui::err(format!("{:>6}", format!("-{r}"))),
13201×
            ui::dim(&f.kind)
1321
        );
1322
    }
13231×
    println!(
1324
        " {}",
13251×
        ui::dim(format!(
1326
            "{} changed, {added} added, {removed} removed",
13271×
            plural(files.len(), "file")
1328
        ))
1329
    );
13301×
}
1331
1332
/// One change, as `oxy show` prints it; `inline` JSON goes without its
1333
/// newline, for an array. `stat` lists the files instead of the diff.
13343×
fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool, stat: bool) -> Result<i32> {
13353×
    let c = repo.store().get_change(&h)?;
13363×
    if as_json {
13371×
        let files = repo.diff_files(Some(&h))?;
13381×
        let heads = repo.bookmark_heads()?;
13391×
        let entry = oxy_core::repo::LogEntry {
13401×
            hash: h,
13411×
            change: oxy_core::state::ChangeMeta::of(&c),
13421×
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
13431×
            is_head: heads.contains(&h),
13441×
        };
13451×
        let mut body = log_entry_json(repo, &entry)?;
13461×
        body.pop();
13471×
        body.push_str(&format!(
1348
            ",{}:{}}}",
13491×
            json::s("files"),
13501×
            json::arr(files.iter().map(|f| {
13511×
                let (a, r) = counts(f);
13521×
                json::obj([
13531×
                    ("path", json::s(&f.path)),
13541×
                    ("kind", json::s(&f.kind)),
13551×
                    ("from", json::opt(f.from.as_deref(), json::s)),
13561×
                    ("added", a.to_string()),
13571×
                    ("removed", r.to_string()),
13581×
                ])
13591×
            }))
1360
        ));
13611×
        if inline {
13620×
            print!("{body}");
13631×
        } else {
13641×
            println!("{body}");
13651×
        }
13661×
        return Ok(0);
13672×
    }
13682×
    println!(
1369
        "{} {} {}",
13702×
        ui::section("change"),
13712×
        ui::id(short_id(&c)),
13722×
        ui::hash(format!("#{h}"))
1373
    );
13742×
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1375
    // Fetched but not pulled (oxygen#56): say where it is.
13762×
    if let Some(at) = repo.remote_only_location(&h)? {
13770×
        println!(
13780×
            "{}",
13790×
            ui::kv(
13800×
                "only in",
13810×
                ui::warn(format!(
13820×
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
13830×
                ))
13840×
            )
13850×
        );
13862×
    }
13872×
    let meta = oxy_core::state::ChangeMeta::of(&c);
13882×
    let status = repo.authenticate_change_known(&h, Some(&meta))?;
13892×
    println!("{}", ui::kv("author", ui::author(author_name(repo, &meta))));
13902×
    if let Some(agent) = via(repo, &status, &meta.author) {
13910×
        println!("{}", ui::kv("via", agent.line()));
13922×
    }
13932×
    println!(
1394
        "{}",
13952×
        ui::kv(
13962×
            "date",
13972×
            format!(
1398
                "{} {}",
13992×
                when(c.hlc.wall_ms),
14002×
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1401
            )
1402
        )
1403
    );
14042×
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
14052×
    println!("{}", ui::kv("sig", signature_line(repo, &h)?));
14062×
    println!();
14075×
    for line in (if c.message.is_empty() {
14080×
        "(no description)"
1409
    } else {
14102×
        &c.message
1411
    })
14122×
    .lines()
14135×
    {
14145×
        println!("    {line}");
14155×
    }
14162×
    println!();
14172×
    if stat {
14181×
        print_stat(&repo.diff_files(Some(&h))?);
1419
    } else {
14201×
        print!("{}", repo.describe_change(&h)?);
1421
    }
14222×
    Ok(0)
14233×
}
1424
14250×
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
14260×
    let repo = open()?;
1427
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1428
    // BRANCH` is: checking its files out under another bookmark's name
1429
    // made the next commit move the wrong bookmark (oxygen#60).
14300×
    if let [name] = changes {
14310×
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
14320×
            drop(repo);
14330×
            return bookmark_switch(name, discard, carry);
14340×
        }
14350×
    }
14360×
    let heads = if changes.is_empty() {
14370×
        repo.bookmark_heads()?
1438
    } else {
14390×
        let mut heads = Vec::new();
14400×
        for c in changes {
14410×
            heads.extend(repo.resolve_heads(c)?);
1442
        }
14430×
        heads
1444
    };
14450×
    let spec = if changes.is_empty() {
14460×
        repo.config.bookmark.clone()
1447
    } else {
14480×
        changes.join(" ")
1449
    };
14500×
    let sp = ui::spinner(&format!("Checking out {spec}…"));
14510×
    let command = format!("oxy checkout {spec}");
14520×
    let (r, carried) = if carry {
14530×
        repo.checkout_carry(&heads, &spec, &command)?
1454
    } else {
14550×
        (repo.checkout(&heads, discard, &command)?, vec![])
1456
    };
14570×
    sp.done(&format!(
1458
        "{} on {}: {} written, {} removed{}",
14590×
        ui::done("Working copy"),
14600×
        ui::bookmark(&spec),
14610×
        plural(r.written, "file"),
1462
        r.removed,
14630×
        if carried.is_empty() {
14640×
            String::new()
1465
        } else {
14660×
            format!("; carried {}", plural(carried.len(), "changed path"))
1467
        }
1468
    ));
14690×
    print_removed(&r);
14700×
    for n in &r.notes {
14710×
        println!("  {} {n}", ui::note());
14720×
    }
14730×
    print_kept_both(&r);
14740×
    if r.conflicted {
14750×
        println!(
14760×
            "  {} {}",
14770×
            ui::caution(),
14780×
            ui::warn("this state has conflicts; see oxy status")
14790×
        );
14800×
    }
14810×
    where_now(&repo);
14820×
    Ok(0)
14830×
}
1484
1485
/// Union files (`merge=union`, oxygen#145) a checkout settled itself.
14863×
fn print_kept_both(r: &oxy_core::repo::CheckoutReport) {
14873×
    for k in &r.kept_both {
14880×
        let how = if k.identical.len() == k.settled.len() {
14890×
            "kept one of its identical sides"
14900×
        } else if k.identical.is_empty() {
14910×
            "kept both sides (merge=union)"
1492
        } else {
14930×
            "kept one of identical sides and both of others (merge=union)"
1494
        };
14950×
        println!(
1496
            "  {} settled {}: {how}; the next commit records it",
14970×
            ui::note(),
14980×
            ui::path(&k.path)
1499
        );
1500
    }
15013×
}
1502
15031×
pub fn resolve(paths: &[String], both: bool, reverse: bool, as_json: bool) -> Result<i32> {
15041×
    let repo = open()?;
15051×
    let mut snap = repo.snapshot("oxy resolve")?;
15061×
    let paths: Vec<String> = paths
15071×
        .iter()
15081×
        .map(|p| p.trim_start_matches("./").trim_end_matches('/').to_string())
15091×
        .collect();
15101×
    if both {
1511
        // Adjacent insertions (oxygen#121): every side kept, in order.
15120×
        let kept = repo.keep_both(&snap, &paths, reverse)?;
15130×
        if !as_json {
15140×
            for k in &kept {
15150×
                if !k.settled.is_empty() {
15160×
                    let n: Vec<String> = k.settled.iter().map(|n| n.to_string()).collect();
15170×
                    println!("kept both  {}: conflict {}", k.path, n.join(", "));
15180×
                }
15190×
                for (n, why) in &k.left {
15200×
                    println!("markers    {}: conflict {n}: {why}", k.path);
15210×
                }
1522
            }
15230×
        }
15240×
        snap = repo.snapshot("oxy resolve")?;
15251×
    } else if !paths.is_empty() {
1526
        // A replace conflict has no markers to edit out: the user says which
1527
        // content wins (oxygen#140, spec §9.3), and the snapshot builds it.
15280×
        repo.choose_resolutions(&snap.base_snapshot, &paths)?;
15290×
        snap = repo.snapshot("oxy resolve")?;
15301×
    }
15311×
    if as_json {
15321×
        println!("{}", repo.status_json(&snap)?);
15331×
        return Ok(if snap.base_snapshot.is_conflicted() {
15340×
            2
1535
        } else {
15361×
            0
1537
        });
15380×
    }
15390×
    if !snap.base_snapshot.is_conflicted() {
15400×
        println!("The working copy's base has no conflicts.");
15410×
        return Ok(0);
15420×
    }
15430×
    let mut remaining = 0;
15440×
    for (p, f) in &snap.base_snapshot.files {
15450×
        if !f.is_conflicted() {
15460×
            continue;
15470×
        }
15480×
        match snap
15490×
            .statuses
15500×
            .iter()
15510×
            .find(|s| s.path == *p)
15520×
            .map(|s| s.status)
1553
        {
15540×
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
15550×
            Some(ChangeStatus::ConflictEdited) => {
15560×
                remaining += 1;
15570×
                println!("markers    {p}");
15580×
            }
15590×
            _ => {
15600×
                remaining += 1;
15610×
                println!("unresolved {p}");
15620×
            }
1563
        }
1564
    }
15650×
    for c in &snap.base_snapshot.tree.conflicts {
15660×
        remaining += 1;
15670×
        println!("tree       {c:?}");
15680×
    }
15690×
    if remaining == 0 {
15700×
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
15710×
        Ok(0)
1572
    } else {
15730×
        Ok(2)
1574
    }
15751×
}
1576
15770×
pub fn undo() -> Result<i32> {
15780×
    let repo = open()?;
15790×
    let u = repo.undo()?;
15800×
    println!("{} {}", ui::done("Undone:"), u.command);
15810×
    for c in &u.changes {
15820×
        println!("  {} {}", ui::note(), change_words(&repo, c));
15830×
    }
15840×
    if u.others_kept > 0 {
15850×
        let s = if u.others_kept == 1 { "" } else { "s" };
15860×
        println!(
1587
            "  {} {}",
15880×
            ui::note(),
15890×
            ui::dim(format!(
1590
                "{} newer operation{s} from other workspaces left as they are",
1591
                u.others_kept
1592
            ))
1593
        );
15940×
    }
15950×
    for (bookmark, remote) in &u.pushed {
15960×
        println!(
15970×
            "  {} {}",
15980×
            ui::caution(),
15990×
            ui::warn(format!(
16000×
                "{remote}/{bookmark} already has what this undid: undone here only; the next push of {bookmark} needs --force to take it back there"
16010×
            ))
16020×
        );
16030×
    }
16040×
    where_now(&repo);
16050×
    Ok(0)
16060×
}
1607
16081×
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
16091×
    let repo = open()?;
16101×
    let ops = repo.op_log()?;
1611
    // What each operation changed, against the one before it.
161211×
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
161311×
        match ops.get(i + 1) {
161410×
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
16151×
            None => Ok(vec![]),
1616
        }
161711×
    };
16181×
    if as_json {
16191×
        let mut items = Vec::new();
162011×
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
162111×
            let summary: Vec<String> = changes_of(i)?
162211×
                .iter()
162311×
                .map(|c| change_words(&repo, c))
162411×
                .collect();
162511×
            items.push(json::obj([
162611×
                ("id", json::s(&r.to_hex())),
162711×
                ("when_ms", json::n(op.hlc.wall_ms)),
162811×
                ("command", json::s(&op.command)),
162911×
                ("snapshot", json::b(op.is_snapshot())),
163011×
                ("current", json::b(i == 0)),
163111×
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1632
            ]));
1633
        }
16341×
        println!("{}", json::arr(items));
16351×
        return Ok(0);
16360×
    }
16370×
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
16380×
    let id = |r: &oxy_core::hash::ObjectRef| {
16390×
        let hex = r.to_hex();
16400×
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
16410×
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
16420×
    };
16430×
    let rail = ui::dim(ui::glyph("│", "|"));
16440×
    let (mut i, mut shown) = (0, 0);
16450×
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
16460×
        let (r, op) = &ops[i];
16470×
        let bullet = if i == 0 {
16480×
            ui::ok(ui::glyph("@", "@"))
1649
        } else {
16500×
            ui::dim(ui::glyph("○", "o"))
1651
        };
1652
        // A run of snapshots folds into one entry.
16530×
        let mut run = 1;
16540×
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
16550×
            run += 1;
16560×
        }
16570×
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
16580×
        if op.is_snapshot() {
16590×
            let span = if run > 1 {
16600×
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1661
            } else {
16620×
                String::new()
1663
            };
16640×
            println!(
1665
                "{bullet}  {}{} {when}",
16660×
                id(r),
16670×
                if span.is_empty() {
16680×
                    String::new()
1669
                } else {
16700×
                    format!(" {span}")
1671
                }
1672
            );
16730×
            println!(
1674
                "{rail}  {}",
16750×
                ui::dim(if run == 1 {
16760×
                    "working-copy snapshot".to_string()
1677
                } else {
16780×
                    format!("{run} working-copy snapshots")
1679
                })
1680
            );
1681
        } else {
16820×
            println!("{bullet}  {} {when}", id(r));
16830×
            let words: Vec<String> = changes_of(i)?
16840×
                .iter()
16850×
                .map(|c| change_words(&repo, c))
16860×
                .collect();
16870×
            let summary = if words.is_empty() {
16880×
                if i + 1 == ops.len() {
16890×
                    "created the repository".to_string()
1690
                } else {
16910×
                    "no bookmark or working-copy change".to_string()
1692
                }
1693
            } else {
16940×
                words.join("; ")
1695
            };
16960×
            println!(
1697
                "{rail}  {}",
16980×
                if i == 0 {
16990×
                    ui::subject(&summary)
1700
                } else {
17010×
                    summary
1702
                }
1703
            );
17040×
            let cmd = op.command.lines().next().unwrap_or("");
17050×
            let cmd: String = cmd.chars().take(100).collect();
17060×
            println!("{rail}  {}", ui::dim(cmd));
1707
        }
17080×
        i += run;
17090×
        shown += 1;
1710
    }
17110×
    if i < ops.len() {
17120×
        println!(
17130×
            "{}",
17140×
            ui::dim(format!(
17150×
                "{} {} older; pass -n to see more",
17160×
                ui::glyph("…", "..."),
17170×
                plural(ops.len() - i, "operation")
17180×
            ))
17190×
        );
17200×
    }
17210×
    Ok(0)
17221×
}
1723
1724
/// One change an operation made, in words.
172511×
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1726
    use oxy_core::repo::ViewChange::*;
17272×
    match c {
17280×
        BookmarkCreated { name, heads } => {
17290×
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1730
        }
17310×
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
17322×
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
17331×
        BookmarkMoved { name, from, to } => format!(
1734
            "{name}: {from} {} {}",
17351×
            ui::glyph("→", "->"),
17361×
            plural(*to, "head")
1737
        ),
17381×
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
17390×
        TagCreated { name } => format!("tagged {name}"),
17400×
        TagDeleted { name } => format!("removed tag {name}"),
17410×
        Policy => "trust policy changed".to_string(),
17428×
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
17438×
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
17440×
            Err(_) => "working copy moved".to_string(),
1745
        },
1746
    }
174711×
}
1748
17490×
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
17500×
    let repo = open()?;
17510×
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
17520×
    let r = repo.op_restore(op, discard)?;
17530×
    sp.done(&format!(
17540×
        "{} to operation {} {}",
17550×
        ui::done("Restored"),
17560×
        ui::hash(r.op.short(12)),
17570×
        ui::dim(r.command.lines().next().unwrap_or(""))
17580×
    ));
17590×
    println!(
1760
        "  {} {}",
17610×
        ui::note(),
17620×
        ui::dim(format!(
1763
            "{} written, {} removed; oxy undo goes back again",
17640×
            plural(r.checkout.written, "file"),
1765
            r.checkout.removed
1766
        ))
1767
    );
17680×
    where_now(&repo);
17690×
    Ok(0)
17700×
}
1771
17720×
pub fn op_revert(op: &str) -> Result<i32> {
17730×
    let repo = open()?;
17740×
    let r = repo.op_revert(op)?;
17750×
    let view = repo.view()?;
17760×
    let names: Vec<String> = r
17770×
        .reverted
17780×
        .iter()
17790×
        .map(|n| {
17800×
            if view.bookmarks.contains_key(n) {
17810×
                ui::bookmark(n)
1782
            } else {
17830×
                format!("{} (removed)", ui::bookmark(n))
1784
            }
17850×
        })
17860×
        .collect();
17870×
    println!(
1788
        "{} operation {} {}",
17890×
        ui::done("Reverted"),
17900×
        ui::hash(r.op.short(12)),
17910×
        ui::dim(r.command.lines().next().unwrap_or(""))
1792
    );
17930×
    println!(
1794
        "  {} {}",
17950×
        ui::note(),
17960×
        ui::dim(format!("as before it: {}", names.join(", ")))
1797
    );
17980×
    if !r.kept.is_empty() {
17990×
        println!(
18000×
            "  {} {}",
18010×
            ui::caution(),
18020×
            ui::warn(format!(
18030×
                "left as they are, having moved again since: {}",
18040×
                r.kept.join(", ")
18050×
            ))
18060×
        );
18070×
    }
18080×
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
18090×
        println!(
18100×
            "  {} {}",
18110×
            ui::note(),
18120×
            ui::dim("the working copy has work of its own: oxy checkout to move it")
18130×
        );
18140×
    }
18150×
    where_now(&repo);
18160×
    Ok(0)
18170×
}
1818
1819
/// Where the working copy and bookmark are now, after a command moved
1820
/// them (as jj says "Working copy now at").
182136×
pub fn where_now(repo: &Repo) {
182236×
    let Ok((_, wc)) = repo.working_copy() else {
18230×
        return;
1824
    };
182536×
    let heads = repo.bookmark_heads().unwrap_or_default();
182636×
    let newest = heads
182736×
        .iter()
182849×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
182936×
        .max_by_key(|(m, _)| m.hlc);
183036×
    println!(
1831
        "  {} {}",
183236×
        ui::dim(format!("{:<13}", "Working copy")),
183336×
        ui::id(wc.change_id.short(8))
1834
    );
183536×
    let tail = match newest {
183636×
        Some((m, _)) => format!(
1837
            ", newest {} {}",
183836×
            ui::id(m.change_id.short(8)),
183936×
            subject_of(&m.message)
1840
        ),
18410×
        None => String::new(),
1842
    };
184336×
    println!(
1844
        "  {} {}: {}{tail}",
184536×
        ui::dim(format!("{:<13}", "Bookmark")),
184636×
        ui::bookmark(&repo.config.bookmark),
184736×
        plural(heads.len(), "head")
1848
    );
184936×
}
1850
18511×
pub fn gc(now: bool, expire_snapshots: bool) -> Result<i32> {
18521×
    let mut repo = open()?;
18531×
    if expire_snapshots {
18540×
        repo.config.snapshot_retention_days = 0;
18551×
    }
18561×
    let sp = ui::spinner("Packing and pruning…");
1857
    // Cylinder's artifacts are named from outside the history: keep them.
18581×
    let artifacts = cylinder::roots(&repo)?;
18595×
    let r = repo.gc_keeping(now, &artifacts, &mut |phase| sp.set(&format!("{phase}…")))?;
18601×
    sp.clear();
18611×
    if r.packed.objects > 0 {
18621×
        println!(
18631×
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
18641×
            plural(r.packed.objects, "object"),
18651×
            r.packed.raw_bytes,
18661×
            r.packed.packed_bytes,
18671×
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
18681×
        );
18691×
    }
18701×
    println!(
1871
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
18721×
        plural(r.reachable, "object"),
18731×
        plural(r.pruned.objects, "unreachable object"),
1874
        r.pruned.bytes,
18751×
        if r.pruned.deferred > 0 {
18760×
            format!(
1877
                "; {} deferred by the grace period (use --now)",
18780×
                plural(r.pruned.deferred, "object")
1879
            )
1880
        } else {
18811×
            String::new()
1882
        },
18831×
        if r.merged_packs > 0 {
18840×
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1885
        } else {
18861×
            String::new()
1887
        },
18881×
        plural(repo.store().pack_count(), "pack")
1889
    );
1890
    // What earlier repacks replaced stays an hour for readers still using
1891
    // it (oxygenhub#249); a collection after that deletes it.
18921×
    let kept = if r.retired.kept > 0 {
18930×
        format!(
1894
            "{} retired less than an hour ago kept for readers",
18950×
            plural(r.retired.kept, "file")
1896
        )
1897
    } else {
18981×
        String::new()
1899
    };
19001×
    if r.retired.packs + r.retired.loose > 0 {
19010×
        println!(
1902
            "Deleted {} and {} retired by earlier repacks{}.",
19030×
            plural(r.retired.packs, "pack"),
19040×
            plural(r.retired.loose, "loose object"),
19050×
            if kept.is_empty() {
19060×
                String::new()
1907
            } else {
19080×
                format!("; {kept}")
1909
            }
1910
        );
19111×
    } else if !kept.is_empty() {
19120×
        println!("{kept}.");
19131×
    }
19141×
    Ok(0)
19151×
}
1916
1917
/// `oxy gc --remote NAME`: fold a store remote's bundles into one.
19182×
pub fn gc_remote(name: &str, now: bool) -> Result<i32> {
19192×
    let repo = open()?;
19202×
    let sp = ui::spinner(&format!("Folding {name}'s bundles…"));
19212×
    let r = repo.gc_remote(name, now)?;
19221×
    sp.clear();
19231×
    if r.merged > 0 {
19241×
        println!(
19251×
            "{} {} into one of {} bytes ({})",
19261×
            ui::done("Folded"),
19271×
            plural(r.merged, "bundle"),
19281×
            r.bundle_bytes,
19291×
            plural(r.changes, "change")
19301×
        );
19311×
    } else {
19320×
        println!(
19330×
            "{} {}",
19340×
            ui::note(),
19350×
            ui::dim("nothing to fold: one bundle holds everything")
19360×
        );
19370×
    }
19381×
    println!(
1939
        "  {} {}",
19401×
        ui::note(),
19411×
        ui::dim(format!(
1942
            "removed {}{}",
19431×
            plural(r.deleted, "superseded bundle"),
19441×
            if r.deferred > 0 {
19450×
                format!(
1946
                    "; {} kept for readers that may still fetch them (use --now)",
19470×
                    plural(r.deferred, "bundle")
1948
                )
1949
            } else {
19501×
                String::new()
1951
            }
1952
        ))
1953
    );
19541×
    Ok(0)
19552×
}
1956
1957
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
19580×
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1959
    use oxy_core::repo::Health;
19600×
    let repo = open()?;
19610×
    let sp = ui::spinner(if offline {
19620×
        "Checking…"
1963
    } else {
19640×
        "Checking, and contacting remotes…"
1965
    });
19660×
    let r = repo.doctor(!offline);
19670×
    sp.clear();
19680×
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
19690×
    let word = |h: Health| match h {
19700×
        Health::Ok => "ok",
19710×
        Health::Warn => "warning",
19720×
        Health::Fail => "fail",
19730×
    };
19740×
    if as_json {
19750×
        let checks: Vec<String> = r
19760×
            .checks
19770×
            .iter()
19780×
            .map(|c| {
19790×
                json::obj([
19800×
                    ("area", json::s(&c.area)),
19810×
                    ("health", json::s(word(c.health))),
19820×
                    ("message", json::s(&c.message)),
19830×
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
19840×
                ])
19850×
            })
19860×
            .collect();
19870×
        println!(
1988
            "{}",
19890×
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1990
        );
19910×
        return Ok(code);
19920×
    }
19930×
    let mut last = "";
19940×
    for c in &r.checks {
19950×
        if c.area != last {
19960×
            println!("{}", ui::section(&c.area));
19970×
            last = &c.area;
19980×
        }
19990×
        let mark = match c.health {
20000×
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
20010×
            Health::Warn => ui::caution(),
20020×
            Health::Fail => ui::err(ui::glyph("✖", "x")),
2003
        };
20040×
        println!("  {mark} {}", c.message);
20050×
        if let Some(h) = &c.hint {
20060×
            println!("    {} {}", ui::dim("→"), ui::dim(h));
20070×
        }
2008
    }
20090×
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
20100×
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
20110×
    if fails + warns == 0 {
20120×
        println!("{}", ui::done("Everything looks right."));
20130×
    } else {
20140×
        println!(
2015
            "{} {}, {}.",
20160×
            if fails > 0 {
20170×
                ui::err(ui::glyph("✖", "x"))
2018
            } else {
20190×
                ui::caution()
2020
            },
20210×
            plural(fails, "problem"),
20220×
            plural(warns, "warning")
2023
        );
2024
    }
20250×
    Ok(code)
20260×
}
2027
2028
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
20290×
pub fn fsck(as_json: bool) -> Result<i32> {
2030
    use oxy_core::repo::Severity;
20310×
    let repo = open()?;
20320×
    let sp = ui::spinner("Checking every object…");
20330×
    let r = repo.fsck()?;
20340×
    sp.clear();
20350×
    let code = if r.errors() > 0 { 1 } else { 0 };
20360×
    if as_json {
20370×
        let problems: Vec<String> = r
20380×
            .problems
20390×
            .iter()
20400×
            .map(|p| {
20410×
                json::obj([
2042
                    (
2043
                        "severity",
20440×
                        json::s(match p.severity {
20450×
                            Severity::Error => "error",
20460×
                            Severity::Warning => "warning",
2047
                        }),
2048
                    ),
2049
                    (
20500×
                        "object",
20510×
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
2052
                    ),
20530×
                    ("what", json::s(&p.what)),
2054
                ])
20550×
            })
20560×
            .collect();
20570×
        println!(
2058
            "{}",
20590×
            json::obj([
20600×
                ("ok", json::b(code == 0)),
20610×
                ("objects", json::n(r.objects)),
20620×
                ("ops", json::n(r.ops)),
20630×
                ("changes", json::n(r.changes)),
20640×
                ("signed", json::n(r.signed)),
20650×
                ("unsigned", json::n(r.unsigned)),
20660×
                ("checkpoints", json::n(r.checkpoints)),
20670×
                ("attestations", json::n(r.attestations)),
20680×
                ("errors", json::n(r.errors())),
20690×
                ("warnings", json::n(r.warnings())),
20700×
                ("problems", json::arr(problems)),
20710×
            ])
2072
        );
20730×
        return Ok(code);
20740×
    }
20750×
    println!(
2076
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
20770×
        plural(r.objects, "object"),
20780×
        plural(r.ops, "operation"),
20790×
        plural(r.changes, "change"),
2080
        r.signed,
2081
        r.unsigned,
20820×
        plural(r.checkpoints, "checkpoint"),
20830×
        plural(r.attestations, "attestation"),
2084
    );
20850×
    for p in &r.problems {
20860×
        let obj = p
20870×
            .object
20880×
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
20890×
            .unwrap_or_default();
20900×
        match p.severity {
20910×
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
20920×
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
2093
        }
2094
    }
20950×
    if r.problems.is_empty() {
20960×
        println!("{}", ui::done("No problems found."));
20970×
    } else if code == 0 {
20980×
        println!(
20990×
            "{}",
21000×
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
21010×
        );
21020×
    } else {
21030×
        println!(
21040×
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
21050×
            ui::err(ui::glyph("✖", "x")),
21060×
            plural(r.errors(), "error"),
21070×
            plural(r.warnings(), "warning")
21080×
        );
21090×
    }
21100×
    Ok(code)
21110×
}
2112
2113
/// The head the working copy sits on, for commands that default to it. With
2114
/// several heads beneath the working copy, the most recently made one is
2115
/// chosen and announced.
21160×
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
21170×
    let snap = repo.snapshot_status("oxy")?;
21180×
    let base = snap.base.maximal(&snap.wc.deps);
21190×
    match base.as_slice() {
21200×
        [] => anyhow::bail!("the working copy sits on no change yet"),
21210×
        [h] => Ok(*h),
21220×
        many => {
21230×
            let latest = many
21240×
                .iter()
21250×
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
21260×
                .copied()
21270×
                .unwrap();
21280×
            let c = repo.store().get_change(&latest)?;
21290×
            println!(
2130
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
21310×
                short_id(&c),
21320×
                latest.short(12),
21330×
                many.len()
2134
            );
21350×
            Ok(latest)
2136
        }
2137
    }
21380×
}
2139
2140
/// `oxy describe` without -m: the working copy's name for a build.
21414×
pub fn describe_name(as_json: bool) -> Result<i32> {
21424×
    let repo = open()?;
21434×
    let d = repo.describe_working_copy()?;
21444×
    if as_json {
21453×
        println!(
2146
            "{}",
21473×
            json::obj([
21483×
                ("describe", json::s(&d.line())),
21493×
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
21503×
                ("distance", json::n(d.distance)),
21513×
                ("bookmark", json::s(&d.bookmark)),
21523×
                ("change", json::s(&d.change.to_hex())),
21533×
                ("hash", json::s(&d.hash.to_hex())),
21543×
                ("dirty", json::b(d.dirty)),
2155
            ])
2156
        );
21571×
    } else {
21581×
        println!("{}", d.line());
21591×
    }
21604×
    Ok(0)
21614×
}
2162
21630×
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
21640×
    let repo = open()?;
21650×
    let h = match change {
21660×
        Some(c) => repo.resolve_change(c)?,
21670×
        None => current_head(&repo)?,
2168
    };
21690×
    let new = repo.describe(&h, message)?;
21700×
    let c = repo.store().get_change_meta(&new)?;
21710×
    println!(
2172
        "{} {} {}  {}",
21730×
        ui::done("Described"),
21740×
        ui::id(c.change_id.short(8)),
21750×
        ui::hash(format!("#{}", new.short(12))),
21760×
        ui::subject(subject_of(message))
2177
    );
21780×
    Ok(0)
21790×
}
2180
21810×
pub fn amend(message: Option<&str>, into: Option<&str>, paths: &[String]) -> Result<i32> {
21820×
    let repo = open()?;
21830×
    let before = repo.view()?;
21840×
    let new = match into {
21850×
        Some(spec) => {
21860×
            let target = repo.resolve_change(spec)?;
21870×
            repo.amend_into(&target, message)?
2188
        }
21890×
        None if !paths.is_empty() => repo.amend_paths(message, paths)?,
21900×
        None => repo.amend(message)?,
2191
    };
21920×
    let c = repo.store().get_change_meta(&new)?;
21930×
    println!(
2194
        "{} {} {}  {}",
21950×
        ui::done("Amended"),
21960×
        ui::id(c.change_id.short(8)),
21970×
        ui::hash(format!("#{}", new.short(12))),
21980×
        ui::subject(subject_of(&c.message))
2199
    );
2200
    // Rewriting what a remote already has means the next push replaces it
2201
    // there (oxygen#99): say so now, not when the push is refused.
22020×
    let bookmark = repo.config.bookmark.clone();
22030×
    let (had, has) = (
22040×
        repo.heads_of(&before, &bookmark)?,
22050×
        repo.heads_of(&repo.view()?, &bookmark)?,
2206
    );
22070×
    for (remote, bookmarks) in &before.remotes {
22080×
        let Some(st) = bookmarks.get(&bookmark) else {
22090×
            continue;
2210
        };
22110×
        let theirs = repo.store().get_state(st)?.heads;
22120×
        if theirs.iter().any(|h| had.contains(h) && !has.contains(h)) {
22130×
            println!(
22140×
                "  {} {}",
22150×
                ui::caution(),
22160×
                ui::warn(format!(
22170×
                    "{remote}/{bookmark} has the change as it was: the next push of {bookmark} needs --force to replace it"
22180×
                ))
22190×
            );
22200×
        }
2221
    }
22220×
    where_now(&repo);
22230×
    Ok(0)
22240×
}
2225
22260×
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
22270×
    let repo = open()?;
22280×
    let Some(r) = revset else {
22290×
        let h = repo.resolve_change(change.unwrap_or_default())?;
22300×
        abandon_one(&repo, h)?;
22310×
        where_now(&repo);
22320×
        return Ok(0);
2233
    };
2234
    // A revset: say what it selects, refuse an empty set, ask above a few.
22350×
    let selected = repo.revset(r)?;
22360×
    let wc = repo.working_copy().ok().map(|(h, _)| h);
22370×
    let hashes: Vec<ChangeHash> = selected
22380×
        .hashes
22390×
        .iter()
22400×
        .copied()
22410×
        .filter(|h| Some(*h) != wc)
22420×
        .collect();
22430×
    if hashes.is_empty() {
22440×
        anyhow::bail!("{r:?} selects no change to abandon");
22450×
    }
22460×
    println!(
2247
        "{} {} selects {}:",
22480×
        ui::section("abandon"),
22490×
        ui::id(r),
22500×
        plural(hashes.len(), "change")
2251
    );
22520×
    for h in &hashes {
22530×
        if let Some(m) = selected.metas.get(h) {
22540×
            println!(
22550×
                "  {} {}  {}",
22560×
                ui::id(m.change_id.short(8)),
22570×
                ui::hash(format!("#{}", h.short(12))),
22580×
                subject_of(&m.message)
22590×
            );
22600×
        }
2261
    }
2262
    const ASK_ABOVE: usize = 5;
22630×
    if hashes.len() > ASK_ABOVE && !yes {
22640×
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
22650×
    }
2266
    // Newest first: abandoning a change rewrites what depends on it, so a
2267
    // later member is found again by its ChangeId.
22680×
    let mut done = 0;
22690×
    for h in &hashes {
22700×
        let Some(m) = selected.metas.get(h) else {
22710×
            continue;
2272
        };
22730×
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
22740×
            Ok(h) => h,
22750×
            Err(_) => continue,
2276
        };
22770×
        abandon_one(&repo, now)?;
22780×
        done += 1;
2279
    }
22800×
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
22810×
    where_now(&repo);
22820×
    Ok(0)
22830×
}
2284
22850×
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
22860×
    let c = repo.store().get_change_meta(&h)?;
22870×
    let notes = repo.abandon(&h)?;
22880×
    println!(
2289
        "{} {} {}  {}",
22900×
        ui::done("Abandoned"),
22910×
        ui::id(c.change_id.short(8)),
22920×
        ui::hash(format!("#{}", h.short(12))),
22930×
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
2294
    );
22950×
    for n in notes {
22960×
        println!("  {} {n}", ui::note());
22970×
    }
22980×
    Ok(())
22990×
}
2300
23010×
pub fn checkpoint() -> Result<i32> {
23020×
    let repo = open()?;
23030×
    let sp = ui::spinner("Writing checkpoint…");
23040×
    let (r, changes, bytes) = repo.checkpoint()?;
23050×
    sp.done(&format!(
23060×
        "{} {} of {} ({} bytes) for {}",
23070×
        ui::done("Checkpoint"),
23080×
        ui::hash(format!("#{}", r.short(12))),
23090×
        plural(changes, "change"),
23100×
        bytes,
23110×
        ui::id(&repo.config.bookmark)
23120×
    ));
23130×
    Ok(0)
23140×
}
2315
2316
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
23170×
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
23180×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
23190×
        return Ok(1);
2320
    };
23210×
    let info = repo.quick_status()?;
23220×
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
23230×
        oxy_core::repo::GLYPH_PROMPT_FORMAT
2324
    } else {
23250×
        format
2326
    };
23270×
    let line = match color {
23280×
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
23290×
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
23300×
        Some(_) => info.format_colored(fmt, ("", "")),
23310×
        None => info.format(fmt),
2332
    };
23330×
    println!("{line}");
23340×
    Ok(0)
23350×
}
2336
23370×
pub fn sparse(paths: &[String]) -> Result<i32> {
23380×
    let mut repo = open()?;
23390×
    if paths.is_empty() {
23400×
        if repo.config.sparse_paths.is_empty() {
23410×
            println!("No sparse filter: the whole tree is materialized.");
23420×
        } else {
23430×
            println!("{}", ui::heading("Sparse filter"));
23440×
            for p in &repo.config.sparse_paths {
23450×
                println!("  {}", ui::path(p));
23460×
            }
2347
        }
23480×
        return Ok(0);
23490×
    }
23500×
    let snap = repo.snapshot("oxy sparse")?;
23510×
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
23520×
        anyhow::bail!(
2353
            "the working copy has changes; commit them before changing the sparse filter"
2354
        );
23550×
    }
23560×
    repo.config.set("filter.paths", &paths.join(","))?;
23570×
    repo.save_config()?;
23580×
    let heads = repo.bookmark_heads()?;
23590×
    let sp = ui::spinner("Re-checking out with the new filter…");
23600×
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
23610×
    sp.done(&format!(
23620×
        "{} {}: {} written, {} removed",
23630×
        ui::done("Sparse filter set to"),
23640×
        ui::path(paths.join(",")),
23650×
        plural(r.written, "file"),
23660×
        r.removed
23670×
    ));
23680×
    Ok(0)
23690×
}
2370
23712×
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
23722×
    let repo = open()?;
23732×
    repo.snapshot_status("oxy tag")?;
23742×
    let heads = if changes.is_empty() {
23752×
        repo.bookmark_heads()?
2376
    } else {
23770×
        let mut heads = Vec::new();
23780×
        for c in changes {
23790×
            heads.extend(repo.resolve_heads(c)?);
2380
        }
23810×
        heads
2382
    };
23832×
    let t = repo.tag_create(name, &heads, message)?;
23842×
    println!(
2385
        "{} {} {} {} ({}){}",
23862×
        ui::done("Tagged"),
23872×
        ui::bookmark(&t.name),
23882×
        ui::dim(ui::glyph("→", "->")),
23892×
        ui::hash(format!("#{}", t.state.short(12))),
23902×
        plural(t.heads.len(), "head"),
23912×
        t.signer
23922×
            .map(|s| format!(", signed by {s}"))
23932×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2394
    );
23952×
    Ok(0)
23962×
}
2397
23980×
pub fn tag_delete(name: &str, reason: &str) -> Result<i32> {
23990×
    let repo = open()?;
24000×
    let t = repo.tag_delete(name, reason)?;
24010×
    println!(
2402
        "{} {} {} {}{}",
24030×
        ui::done("Withdrew"),
24040×
        ui::bookmark(&t.name),
24050×
        ui::dim(ui::glyph("→", "->")),
24060×
        ui::hash(format!("#{}", t.state.short(12))),
24070×
        t.signer
24080×
            .map(|s| format!(", signed by {s}"))
24090×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2410
    );
24110×
    println!(
2412
        "  {} {}",
24130×
        ui::note(),
24140×
        ui::dim("`oxy push` sends the withdrawal to a remote that has the tag; the name is not used again")
2415
    );
24160×
    Ok(0)
24170×
}
2418
24191×
pub fn tag_list(as_json: bool) -> Result<i32> {
24201×
    let repo = open()?;
24211×
    let tags = repo.tags()?;
24221×
    if as_json {
24231×
        println!(
2424
            "{}",
24251×
            json::arr(tags.iter().map(|t| {
24261×
                json::obj([
24271×
                    ("name", json::s(&t.name)),
24281×
                    ("state", json::s(&t.state.to_hex())),
24291×
                    ("heads", json::hashes(&t.heads)),
24301×
                    ("message", json::s(&t.message)),
2431
                    (
24321×
                        "signer",
24331×
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2434
                    ),
2435
                ])
24361×
            }))
2437
        );
24381×
        return Ok(0);
24390×
    }
24400×
    if tags.is_empty() {
24410×
        println!("{}", ui::dim("No tags."));
24420×
    }
24430×
    for t in tags {
24440×
        println!(
2445
            "{} {} {}{}{}{}",
24460×
            ui::ok(ui::glyph("⚑", "#")),
24470×
            ui::bookmark(&t.name),
2448
            // The heads, as `oxy log` shows changes, not the state hash.
24490×
            ui::hash(
24500×
                t.heads
24510×
                    .iter()
24520×
                    .map(|h| format!("#{}", h.short(12)))
24530×
                    .collect::<Vec<_>>()
24540×
                    .join(" ")
2455
            ),
24560×
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
24570×
            if t.message.is_empty() {
24580×
                String::new()
2459
            } else {
24600×
                format!("  {}", ui::subject(subject_of(&t.message)))
2461
            },
24620×
            t.signer
24630×
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
24640×
                .unwrap_or_default()
2465
        );
2466
    }
24670×
    Ok(0)
24681×
}
2469
2470
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2471
/// and workspace add take as "be on this bookmark" (oxygen#60).
24720×
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
24730×
    Ok(repo.view()?.bookmarks.contains_key(name)
24740×
        || repo
24750×
            .remote_only_bookmarks()?
24760×
            .iter()
24770×
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
24780×
}
2479
24800×
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
24810×
    let repo = open()?;
2482
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2483
    // this workspace's bookmark with that one's files.
24840×
    if let [name] = changes {
24850×
        if names_bookmark(&repo, name)? {
24860×
            let (local, _) = repo.local_bookmark_for(name)?;
24870×
            let heads = repo.resolve_heads(&local)?;
24880×
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
24890×
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
24900×
            sp.done(&format!(
24910×
                "{} {} (workspace {}) on {}",
24920×
                ui::done("Workspace created at"),
24930×
                ui::path(ws.root().display()),
24940×
                ui::id(ws.workspace().short(8)),
24950×
                ui::bookmark(&local)
24960×
            ));
24970×
            return Ok(0);
24980×
        }
24990×
    }
25000×
    let heads = if changes.is_empty() {
25010×
        None
2502
    } else {
25030×
        let mut heads = Vec::new();
25040×
        for c in changes {
25050×
            heads.extend(repo.resolve_heads(c)?);
2506
        }
25070×
        Some(heads)
2508
    };
25090×
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
25100×
    let ws = repo.workspace_add(path, heads.as_deref())?;
25110×
    sp.done(&format!(
25120×
        "{} {} (workspace {})",
25130×
        ui::done("Workspace created at"),
25140×
        ui::path(ws.root().display()),
25150×
        ui::id(ws.workspace().short(8))
25160×
    ));
25170×
    Ok(0)
25180×
}
2519
25201×
pub fn workspace_list(as_json: bool) -> Result<i32> {
25211×
    let repo = open()?;
25221×
    if as_json {
25231×
        println!(
2524
            "{}",
25251×
            json::arr(repo.workspaces()?.iter().map(|w| {
25261×
                json::obj([
25271×
                    ("id", json::s(&w.id.to_hex())),
25281×
                    ("path", json::s(&w.path.to_string_lossy())),
25291×
                    ("current", json::b(w.current)),
2530
                    (
25311×
                        "working_copy",
25321×
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2533
                    ),
2534
                ])
25351×
            }))
2536
        );
25371×
        return Ok(0);
25380×
    }
25390×
    for w in repo.workspaces()? {
25400×
        println!(
2541
            "{} {} {}{}",
25420×
            if w.current {
25430×
                ui::ok(ui::glyph("●", "*"))
2544
            } else {
25450×
                ui::dim(ui::glyph("○", "o"))
2546
            },
25470×
            ui::id(w.id.short(8)),
25480×
            ui::path(w.path.display()),
25490×
            w.working_copy
25500×
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
25510×
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2552
        );
2553
    }
25540×
    Ok(0)
25551×
}
2556
25570×
pub fn workspace_forget(spec: &str) -> Result<i32> {
25580×
    let repo = open()?;
25590×
    let all = repo.workspaces()?;
25600×
    let target = std::fs::canonicalize(spec).ok();
25610×
    let matches: Vec<_> = all
25620×
        .iter()
25630×
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
25640×
        .collect();
25650×
    let w = match matches.as_slice() {
25660×
        [w] => *w,
25670×
        [] => anyhow::bail!("no workspace matches {spec:?}"),
25680×
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2569
    };
25700×
    repo.workspace_forget(&w.id)?;
25710×
    println!(
2572
        "{} workspace {} at {}; its files were left in place.",
25730×
        ui::done("Forgot"),
25740×
        ui::id(w.id.short(8)),
25750×
        ui::path(w.path.display())
2576
    );
25770×
    Ok(0)
25780×
}
2579
25800×
pub fn lock(path: &str) -> Result<i32> {
25810×
    let repo = open()?;
25820×
    repo.lock_path(path)?;
25830×
    println!(
2584
        "{} {} {}",
25850×
        ui::done("Locked"),
25860×
        ui::path(path),
25870×
        ui::dim("(advisory, local)")
2588
    );
25890×
    Ok(0)
25900×
}
2591
25920×
pub fn unlock(path: &str) -> Result<i32> {
25930×
    let repo = open()?;
25940×
    repo.unlock_path(path)?;
25950×
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
25960×
    Ok(0)
25970×
}
2598
25990×
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
26000×
    let repo = open()?;
26010×
    let h = repo.resolve_change(change)?;
26020×
    let (h1, h2) = repo.split(&h, paths)?;
26030×
    let c1 = repo.store().get_change_meta(&h1)?;
26040×
    let c2 = repo.store().get_change_meta(&h2)?;
26050×
    println!(
2606
        "{} into {} {} and {} {}",
26070×
        ui::done("Split"),
26080×
        ui::id(c1.change_id.short(8)),
26090×
        ui::hash(format!("#{}", h1.short(12))),
26100×
        ui::id(c2.change_id.short(8)),
26110×
        ui::hash(format!("#{}", h2.short(12)))
2612
    );
26130×
    Ok(0)
26140×
}
2615
26166×
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
26176×
    let mut heads = Vec::new();
26186×
    for c in changes {
26196×
        heads.extend(repo.resolve_heads(c)?);
2620
    }
26216×
    Ok(heads)
26226×
}
2623
26246×
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
26256×
    let repo = open()?;
26266×
    repo.snapshot_status("oxy bookmark create")?;
26276×
    let heads = if changes.is_empty() {
26283×
        None
2629
    } else {
26303×
        let named = heads_from(&repo, changes)?;
26313×
        let (_, wc) = repo.working_copy()?;
26323×
        let gap = repo.state_gap(&wc.deps, &named)?;
26333×
        if upto {
26341×
            Some(gap.upto)
26352×
        } else if only || gap.earlier.is_empty() {
26361×
            Some(named)
2637
        } else {
26381×
            anyhow::bail!(
2639
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2640
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2641
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2642
                 or --only for just {0} and what it depends on.",
26431×
                changes.join(" "),
26441×
                plural(gap.earlier.len(), "change"),
26451×
                listed_changes(&repo, &gap.earlier)
2646
            );
2647
        }
2648
    };
26495×
    let heads = repo.bookmark_create(name, heads.as_deref())?;
26505×
    println!(
2651
        "{} bookmark {} {} {}",
26525×
        ui::done("Created"),
26535×
        ui::bookmark(name),
26545×
        ui::dim(ui::glyph("→", "->")),
26555×
        ui::dim(plural(heads.len(), "head"))
2656
    );
26575×
    println!(
2658
        "  {} {}",
26595×
        ui::note(),
26605×
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2661
    );
26625×
    Ok(0)
26636×
}
2664
2665
/// Up to five changes, newest last, as `  #hash subject` lines.
26662×
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
26672×
    let shown = changes.len().min(5);
26682×
    let mut lines: Vec<String> = changes[changes.len() - shown..]
26692×
        .iter()
26702×
        .map(|h| {
26712×
            let subject = repo
26722×
                .store()
26732×
                .get_change(h)
26742×
                .map(|c| subject_of(&c.message).to_string())
26752×
                .unwrap_or_default();
26762×
            format!("  #{} {subject}", h.short(12))
26772×
        })
26782×
        .collect();
26792×
    if changes.len() > shown {
26800×
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
26812×
    }
26822×
    lines.join("\n")
26832×
}
2684
26853×
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
26863×
    let repo = open()?;
26873×
    repo.snapshot_status("oxy bookmark set")?;
26883×
    let named = heads_from(&repo, changes)?;
2689
    // What the bookmark holds now and the new heads would leave out.
26903×
    let current = repo
26913×
        .bookmarks()?
26923×
        .into_iter()
26936×
        .find(|b| b.name == name)
26943×
        .map(|b| b.heads)
26953×
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
26963×
    let gap = repo.state_gap(&current, &named)?;
2697
    // A fast-forward: the new heads hold the bookmark's newest head, so
2698
    // what they leave out is older work nothing since has built on, such
2699
    // as an early change no later one depends on (oxygen#78). Keep it, as
2700
    // --upto does, and say so.
27013×
    let newest = current
27023×
        .iter()
27038×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m.hlc, *h)))
27043×
        .max()
27053×
        .map(|(_, h)| h);
2706
    // Ahead, too: a head the bookmark holds already (it would only drop
2707
    // the others) is not a move forward.
27083×
    let ahead = repo
27093×
        .load_state_history(&current)
27103×
        .is_ok_and(|st| named.iter().any(|h| !st.contains(h)));
27113×
    let forward = !only
27123×
        && ahead
27131×
        && !gap.earlier.is_empty()
27141×
        && newest.is_some_and(|n| {
27151×
            repo.load_state_history(&named)
27161×
                .is_ok_and(|st| st.contains(&n))
27171×
        });
27183×
    let heads = if upto {
27191×
        gap.upto
27202×
    } else if forward {
27211×
        println!(
2722
            "  {} {}",
27231×
            ui::note(),
27241×
            ui::dim(format!(
2725
                "{} builds on {name}'s newest head; keeping {} it holds that {0} does not depend on",
27261×
                changes.join(" "),
27271×
                plural(gap.earlier.len(), "change")
2728
            ))
2729
        );
27301×
        gap.upto
27311×
    } else if only || gap.earlier.is_empty() {
27320×
        named
2733
    } else {
27341×
        anyhow::bail!(
2735
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2736
             A state is its heads and what they depend on, not everything recorded before them.\n\
2737
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2738
             or --only for just {0} and what it depends on.",
27391×
            changes.join(" "),
27401×
            plural(gap.earlier.len(), "change"),
27411×
            listed_changes(&repo, &gap.earlier)
2742
        );
2743
    };
27442×
    let heads = repo.bookmark_set(name, &heads)?;
27452×
    println!(
2746
        "{} bookmark {} {} {}",
27472×
        ui::done("Moved"),
27482×
        ui::bookmark(name),
27492×
        ui::dim(ui::glyph("→", "->")),
27502×
        ui::dim(plural(heads.len(), "head"))
2751
    );
27522×
    Ok(0)
27533×
}
2754
27550×
pub fn bookmark_delete(name: &str) -> Result<i32> {
27560×
    let repo = open()?;
27570×
    repo.bookmark_delete(name)?;
27580×
    println!(
2759
        "{} bookmark {} {}",
27600×
        ui::done("Deleted"),
27610×
        ui::bookmark(name),
27620×
        ui::dim("(its changes stay until unreachable)")
2763
    );
27640×
    Ok(0)
27650×
}
2766
2767
/// Heads with their metadata, newest first.
27680×
fn heads_newest_first(
27690×
    repo: &Repo,
27700×
    heads: &[oxy_core::hash::ChangeHash],
27710×
) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> {
27720×
    let mut out: Vec<_> = heads
27730×
        .iter()
27740×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m)))
27750×
        .collect();
27760×
    out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc));
27770×
    out
27780×
}
2779
2780
/// One head as a line: id, hash, author, when, subject.
27810×
fn print_head(
27820×
    repo: &Repo,
27830×
    indent: &str,
27840×
    h: &oxy_core::hash::ChangeHash,
27850×
    m: &oxy_core::state::ChangeMeta,
27860×
) {
27870×
    println!(
2788
        "{indent}{} {} {}{}{}{}{}",
27890×
        ui::id(m.change_id.short(8)),
27900×
        ui::dim(format!("#{}", &h.to_hex()[..8])),
27910×
        author_name(repo, m),
27920×
        ui::sep(),
27930×
        ui::dim(ui::ago(m.hlc.wall_ms)),
27940×
        ui::sep(),
27950×
        ui::subject(subject_of(&m.message))
2796
    );
27970×
}
2798
27990×
pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result<i32> {
28000×
    let repo = open()?;
28010×
    let name = name.unwrap_or(&repo.config.bookmark).to_string();
28020×
    let view = repo.view()?;
28030×
    let st = match view.bookmarks.get(&name) {
28040×
        Some(st) => *st,
28050×
        None => match oxy_core::repo::remote_bookmark(&view, &name) {
28060×
            Some((_, _, st)) => st,
28070×
            None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"),
2808
        },
2809
    };
28100×
    let heads = repo.store().get_state(&st)?.heads;
28110×
    let shown = heads_newest_first(&repo, &heads);
28120×
    if as_json {
28130×
        println!(
2814
            "{}",
28150×
            json::obj([
28160×
                ("name", json::s(&name)),
28170×
                ("current", json::b(name == repo.config.bookmark)),
2818
                (
28190×
                    "heads",
28200×
                    json::arr(shown.iter().map(|(h, m)| {
28210×
                        json::obj([
28220×
                            ("hash", json::s(&h.to_hex())),
28230×
                            ("id", json::s(&m.change_id.to_string())),
28240×
                            ("author", json::s(&author_name(&repo, m))),
28250×
                            ("time_ms", json::n(m.hlc.wall_ms)),
28260×
                            ("subject", json::s(subject_of(&m.message))),
28270×
                        ])
28280×
                    }))
2829
                ),
2830
            ])
2831
        );
28320×
        return Ok(0);
28330×
    }
28340×
    println!(
2835
        "{} {}{}{}",
28360×
        ui::ok(ui::glyph("●", "*")),
28370×
        ui::bookmark(&name),
28380×
        ui::sep(),
28390×
        ui::dim(plural(heads.len(), "head"))
2840
    );
28410×
    for (h, m) in &shown {
28420×
        print_head(&repo, "  ", h, m);
28430×
    }
28440×
    if heads.len() > 1 {
28450×
        println!(
28460×
            "  {}",
28470×
            ui::dim("None depends on another: the bookmark is all of them and their dependencies.")
28480×
        );
28490×
    }
28500×
    Ok(0)
28510×
}
2852
28535×
pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result<i32> {
28545×
    let repo = open()?;
28555×
    let remote_only = repo.remote_only_bookmarks()?;
28565×
    if as_json {
28575×
        let mut items: Vec<String> = repo
28585×
            .bookmarks()?
28595×
            .into_iter()
286013×
            .map(|b| {
286113×
                json::obj([
286213×
                    ("name", json::s(&b.name)),
286313×
                    ("heads", json::hashes(&b.heads)),
286413×
                    ("current", json::b(b.current)),
286513×
                    ("ahead", json::opt(b.ahead, json::n)),
286613×
                    ("behind", json::opt(b.behind, json::n)),
286713×
                    ("remote", json::opt(b.remote.as_deref(), json::s)),
286813×
                ])
286913×
            })
28705×
            .collect();
28715×
        if all {
28720×
            items.extend(remote_only.iter().map(|b| {
28730×
                json::obj([
28740×
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
28750×
                    ("heads", json::hashes(&b.heads)),
28760×
                    ("current", json::b(false)),
28770×
                    ("ahead", "null".into()),
28780×
                    ("behind", "null".into()),
28790×
                    ("remote", json::s(&b.remote)),
28800×
                ])
28810×
            }));
28825×
        }
28835×
        println!("{}", json::arr(items));
28845×
        return Ok(0);
28850×
    }
28860×
    for b in repo.bookmarks()? {
28870×
        let mark = if b.current {
28880×
            ui::ok(ui::glyph("●", "*"))
2889
        } else {
28900×
            ui::dim(ui::glyph("○", "o"))
2891
        };
28920×
        let mut tail = String::new();
28930×
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
28940×
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
28950×
        }
28960×
        if let Some(n) = b.behind.filter(|n| *n > 0) {
28970×
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
28980×
        }
2899
        // Which remote, when there is a choice (oxygen#83).
29000×
        if !tail.is_empty() && repo.config.remotes.len() > 1 {
29010×
            if let Some(r) = &b.remote {
29020×
                tail += &ui::dim(format!(" {r}"));
29030×
            }
29040×
        }
29050×
        let shown = heads_newest_first(&repo, &b.heads);
2906
        // The newest head's subject, so a busy bookmark shows its latest work.
29070×
        let head = match shown.first() {
29080×
            Some(_) if verbose => String::new(),
29090×
            Some((_, m)) if b.heads.len() > 1 => format!(
2910
                "{} {}",
29110×
                ui::dim("newest"),
29120×
                ui::subject(subject_of(&m.message))
2913
            ),
29140×
            Some((_, m)) => ui::subject(subject_of(&m.message)),
29150×
            None => ui::dim("(empty)"),
2916
        };
29170×
        let head = if head.is_empty() {
29180×
            head
2919
        } else {
29200×
            format!("  {head}")
2921
        };
29220×
        println!(
2923
            "{mark} {}{}{}{tail}{head}",
29240×
            ui::bookmark(&b.name),
29250×
            ui::sep(),
29260×
            ui::dim(plural(b.heads.len(), "head"))
2927
        );
29280×
        if verbose {
29290×
            for (h, m) in &shown {
29300×
                print_head(&repo, "    ", h, m);
29310×
            }
29320×
        }
2933
    }
29340×
    if remote_only.is_empty() {
29350×
        return Ok(0);
29360×
    }
29370×
    if !all {
29380×
        println!(
2939
            "{}",
29400×
            ui::dim(format!(
2941
                "  and {} only on a remote: oxy bookmark list --all",
29420×
                plural(remote_only.len(), "bookmark")
2943
            ))
2944
        );
29450×
        return Ok(0);
29460×
    }
29470×
    for b in &remote_only {
29480×
        println!(
29490×
            "{} {}{}{}",
29500×
            ui::dim(ui::glyph("◌", ".")),
29510×
            ui::dim(format!("{}/{}", b.remote, b.name)),
29520×
            ui::sep(),
29530×
            ui::dim(plural(b.heads.len(), "head"))
29540×
        );
29550×
    }
29560×
    println!(
2957
        "  {} {}",
29580×
        ui::note(),
29590×
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2960
    );
29610×
    Ok(0)
29625×
}
2963
29643×
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
29653×
    let mut repo = open()?;
29663×
    let from = repo.config.bookmark.clone();
29673×
    let (local, created_from) = repo.local_bookmark_for(name)?;
29683×
    if let Some(remote) = created_from {
29690×
        println!(
29700×
            "{} {} from {}",
29710×
            ui::done("Created"),
29720×
            ui::bookmark(&local),
29730×
            ui::dim(format!("{remote}/{local}"))
29740×
        );
29753×
    }
29763×
    let name = local.as_str();
2977
    // Only behind its remote: take the remote's state, so the switch does
2978
    // not check out a stale one (oxygen#74).
29793×
    if let Some(n) = repo.catch_up_bookmark(name)? {
29800×
        println!(
29810×
            "{} {} with {}: {} it lacked",
29820×
            ui::done("Caught up"),
29830×
            ui::bookmark(name),
29840×
            ui::dim(format!("{}/{name}", repo.default_remote())),
29850×
            plural(n, "change")
29860×
        );
29873×
    }
29883×
    let sp = ui::spinner(&format!("Switching to {name}…"));
29893×
    let (r, carried) = if carry {
29900×
        repo.bookmark_switch_carry(name)?
2991
    } else {
29923×
        (repo.bookmark_switch(name, discard)?, vec![])
2993
    };
29943×
    sp.done(&format!(
2995
        "{} to {}: {} written, {} removed{}",
29963×
        ui::done("Switched"),
29973×
        ui::bookmark(name),
29983×
        plural(r.written, "file"),
2999
        r.removed,
30003×
        if carried.is_empty() {
30013×
            String::new()
3002
        } else {
30030×
            format!("; carried {}", plural(carried.len(), "changed path"))
3004
        }
3005
    ));
30063×
    print_removed(&r);
30073×
    print_carried(&carried);
30083×
    print_kept_both(&r);
30093×
    if r.conflicted {
30100×
        println!(
30110×
            "  {} {}",
30120×
            ui::caution(),
30130×
            ui::warn("this state has conflicts; see oxy status")
30140×
        );
30153×
    }
3016
    // Say when the new state leaves out work the old one had: a state is
3017
    // its heads and what they depend on, which can be far less than a Git
3018
    // user expects.
30193×
    if r.lacks > 0 {
30201×
        println!(
30211×
            "  {} {}",
30221×
            ui::note(),
30231×
            ui::dim(format!(
30241×
                "{name} lacks {} that {from} has",
30251×
                plural(r.lacks, "change")
30261×
            ))
30271×
        );
30282×
    }
30293×
    super::sync::subrepos_behind(&repo);
30303×
    where_now(&repo);
30313×
    Ok(0)
30323×
}
3033
30340×
pub fn merge(bookmark: &str) -> Result<i32> {
30350×
    let repo = open()?;
30360×
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
30370×
    let r = repo.merge(bookmark)?;
30380×
    if !r.changed {
30390×
        sp.done(&format!(
30400×
            "{} {}",
30410×
            ui::ok(ui::glyph("✔", "*")),
30420×
            ui::dim(format!(
30430×
                "{} already contains {bookmark}",
30440×
                repo.config.bookmark
30450×
            ))
30460×
        ));
30470×
        return Ok(0);
30480×
    }
30490×
    sp.done(&format!(
3050
        "{} {} into {}: now {}{}",
30510×
        ui::done("Merged"),
30520×
        ui::bookmark(bookmark),
30530×
        ui::bookmark(&repo.config.bookmark),
30540×
        plural(r.heads.len(), "head"),
30550×
        ui::dim(if r.checked_out {
30560×
            "; working copy updated"
3057
        } else {
30580×
            "; run oxy checkout to update the working copy"
3059
        })
3060
    ));
30610×
    let snap = repo.snapshot("oxy merge")?;
30620×
    if snap.base_snapshot.is_conflicted() {
30630×
        println!(
30640×
            "  {} {}",
30650×
            ui::caution(),
30660×
            ui::warn("the result has conflicts; see oxy status")
30670×
        );
30680×
    }
30690×
    where_now(&repo);
30700×
    Ok(0)
30710×
}
3072
30730×
pub fn squash(change: &str, into: &str) -> Result<i32> {
30740×
    let repo = open()?;
30750×
    let c = repo.resolve_change(change)?;
30760×
    let d = repo.resolve_change(into)?;
30770×
    let sp = ui::spinner("Squashing…");
30780×
    let h = repo.squash(&c, &d)?;
30790×
    let new = repo.store().get_change_meta(&h)?;
30800×
    sp.done(&format!(
30810×
        "{} into {} {}  {}",
30820×
        ui::done("Squashed"),
30830×
        ui::id(new.change_id.short(8)),
30840×
        ui::hash(format!("#{}", h.short(12))),
30850×
        ui::subject(subject_of(&new.message))
30860×
    ));
30870×
    Ok(0)
30880×
}
3089
30900×
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
30910×
    let repo = open()?;
30920×
    let c = repo.resolve_change(change)?;
30930×
    let mut heads = Vec::new();
30940×
    for o in onto {
30950×
        heads.extend(repo.resolve_heads(o)?);
3096
    }
30970×
    let sp = ui::spinner("Rebasing…");
30980×
    let h = match repo.rebase(&c, &heads) {
30990×
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
31000×
            let r = repo.rebase_into_working_copy(&c, &heads)?;
31010×
            sp.done(&format!(
31020×
                "{} {} into {}: now {}",
31030×
                ui::done("Merged"),
31040×
                onto.join(" "),
31050×
                ui::bookmark(&repo.config.bookmark),
31060×
                plural(r.heads.len(), "head"),
31070×
            ));
31080×
            if r.checked_out {
31090×
                println!(
31100×
                    "  {} {}",
31110×
                    ui::caution(),
31120×
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
31130×
                );
31140×
            } else {
31150×
                println!(
31160×
                    "  {} {}",
31170×
                    ui::caution(),
31180×
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
31190×
                );
31200×
            }
31210×
            where_now(&repo);
31220×
            return Ok(0);
3123
        }
31240×
        other => other?,
3125
    };
31260×
    let new = repo.store().get_change_meta(&h)?;
31270×
    sp.done(&format!(
31280×
        "{} {} {}  {}",
31290×
        ui::done("Rebased"),
31300×
        ui::id(new.change_id.short(8)),
31310×
        ui::hash(format!("#{}", h.short(12))),
31320×
        ui::dim(format!(
31330×
            "now depends on {}",
31340×
            plural(new.deps.len(), "change")
31350×
        ))
31360×
    ));
31370×
    where_now(&repo);
31380×
    Ok(0)
31390×
}
3140
3141
#[cfg(test)]
3142
mod tests {
3143
    use super::*;
3144
3145
    #[test]
31461×
    fn id_prefixes_agree_with_the_whole_list() {
3147
        // Ids that share long prefixes, and some that differ only in a
3148
        // half byte, from a fixed sequence.
31491×
        let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
31507999×
        let mut next = || {
31517999×
            x ^= x << 13;
31527999×
            x ^= x >> 7;
31537999×
            x ^= x << 17;
31547999×
            x
31557999×
        };
31561×
        let mut ids: Vec<[u8; 16]> = Vec::new();
31571×
        for _ in 0..2000 {
31582000×
            let mut id = [0u8; 16];
31592000×
            id[..8].copy_from_slice(&next().to_le_bytes());
31602000×
            id[8..].copy_from_slice(&next().to_le_bytes());
31612000×
            let share = (next() % 4) as usize;
31622000×
            if let Some(prev) = ids.last() {
31631999×
                id[..share].copy_from_slice(&prev[..share]);
31641999×
                if next() % 2 == 0 {
3165973×
                    id[share] = (prev[share] & 0xf0) | (id[share] & 0x0f);
31661026×
                }
31671×
            }
31682000×
            ids.push(id);
3169
        }
31704000×
        let hex = |id: &[u8; 16]| oxy_core::ids::ChangeId(*id).to_hex();
31711×
        let whole = unique_prefixes(ids.iter().map(hex));
31721×
        let some = id_prefixes(ids.clone(), ids.iter().copied());
31732000×
        for id in &ids {
31742000×
            assert_eq!(some[id], whole[&hex(id)], "{}", hex(id));
3175
        }
31761×
    }
3177
}