OXYGENHUB

Coverage / src/cli/workspace.rs 39.7%

963 of 2428 lines run, 94 of 339 functions · run #332 on show-stat · run missed

1
//! Commands that act on the local repository and working copy.
2
3
use super::format::{
4
    author_name, deps_line, deps_of, plural, short_id, signature_line, signature_mark_of,
5
    subject_of, via, when,
6
};
7
use super::json;
8
use super::open;
9
use super::ui;
10
use anyhow::Result;
11
use oxy_core::objects::ChangeKind;
12
use oxy_core::repo::SignatureStatus;
13
use oxy_core::repo::{render_change, ChangeStatus, Repo};
14
use std::io::Write;
15
use std::path::PathBuf;
16
1712×
pub fn init(path: Option<PathBuf>, bare: bool, store: Option<&str>) -> Result<i32> {
1812×
    let path = path.unwrap_or(std::env::current_dir()?);
1912×
    let repo = Repo::init_new(&path, bare, store)?;
2012×
    println!(
21
        "{} {}oxy repository in {}",
2212×
        ui::done("Initialized"),
2312×
        if bare { "bare " } else { "" },
2412×
        ui::path(repo.root().display())
25
    );
2612×
    println!(
27
        "{}",
2812×
        ui::kv("bookmark", ui::bookmark(&repo.config.bookmark))
29
    );
3012×
    if let Some(url) = &repo.config.storage_url {
310×
        println!(
320×
            "{}",
330×
            ui::kv(
340×
                "store",
350×
                format!(
360×
                    "{url} (cache in {}, up to {} MiB)",
370×
                    ui::path(repo.root().join(".oxy/cache").display()),
380×
                    repo.config.storage_cache >> 20
390×
                )
400×
            )
410×
        );
4212×
    }
4312×
    println!(
44
        "{}",
4512×
        ui::kv(
4612×
            "author",
4712×
            format!(
48
                "{} <{}>",
4912×
                ui::author(&repo.config.author_name),
50
                repo.config.author_email
51
            )
52
        )
53
    );
5412×
    Ok(0)
5512×
}
56
572×
fn status_tag(s: ChangeStatus) -> &'static str {
582×
    match s {
591×
        ChangeStatus::Added => "A",
600×
        ChangeStatus::Modified => "M",
610×
        ChangeStatus::Removed => "D",
620×
        ChangeStatus::Renamed => "R",
631×
        ChangeStatus::ModeChanged => "X",
640×
        ChangeStatus::ConflictEdited => "C!",
650×
        ChangeStatus::Resolved => "V",
66
    }
672×
}
68
69
/// New untracked files left out of the snapshot for their size (oxygen#98):
70
/// named, with how to keep them out quietly or take them in.
7131×
fn print_skipped_large(repo: &Repo) {
7231×
    let skipped = repo.skipped_large();
7331×
    if skipped.is_empty() {
7431×
        return;
750×
    }
760×
    let size = |n: u64| {
770×
        if n >= 1 << 30 {
780×
            format!("{:.1} GiB", n as f64 / (1u64 << 30) as f64)
79
        } else {
800×
            format!("{:.0} MiB", n as f64 / (1u64 << 20) as f64)
81
        }
820×
    };
830×
    println!();
840×
    println!(
85
        "{} {}",
860×
        ui::section(ui::warn("Not tracked")),
870×
        ui::dim(format!("new files over {}", size(repo.config.max_new_file)))
88
    );
890×
    for (p, n) in &skipped {
900×
        println!("  {} {}  {}", ui::caution(), ui::path(p), ui::dim(size(*n)));
910×
    }
920×
    println!(
93
        "  {} {}",
940×
        ui::note(),
950×
        ui::dim(
96
            "to leave them out quietly, list them in .oxyignore; to track one, \
97
             raise snapshot.max-new-file-size (oxy config snapshot.max-new-file-size 2G)"
98
        )
99
    );
10031×
}
101
102
/// Name what a checkout removed from the working copy (oxygen#102): a
103
/// switch to a bookmark lacking files takes them off disk, which an
104
/// editor open on the tree notices before a person reading a count does.
1053×
fn print_removed(r: &oxy_core::repo::CheckoutReport) {
1063×
    if r.removed == 0 {
1072×
        return;
1081×
    }
1091×
    let more = r.removed.saturating_sub(r.removed_paths.len());
1101×
    let names = r.removed_paths.join(", ");
1111×
    let tail = if more > 0 {
1120×
        format!(" and {more} more")
113
    } else {
1141×
        String::new()
115
    };
1161×
    let lead = if r.removed >= 20 {
1170×
        ui::caution()
118
    } else {
1191×
        ui::note()
120
    };
1211×
    println!(
122
        "  {} {}",
123
        lead,
1241×
        ui::dim(format!(
125
            "removed from disk (the bookmark does not have them): {names}{tail}"
126
        ))
127
    );
1283×
}
129
130
/// Folders holding a repository of their own, which oxy leaves out (oxygen#43):
131
/// named, with how to track them.
13231×
fn print_untracked_nested(repo: &Repo, nested: &[String]) {
13331×
    if nested.is_empty() {
13429×
        return;
1352×
    }
1362×
    println!();
1372×
    println!(
138
        "{} {}",
1392×
        ui::section(ui::warn("Not tracked")),
1402×
        ui::dim("folders holding a repository of their own")
141
    );
1422×
    for p in nested {
1432×
        let kind = if repo.root().join(p).join(".git").exists() {
1442×
            "Git"
145
        } else {
1460×
            "Oxygen"
147
        };
1482×
        println!(
149
            "  {} {}  {}",
1502×
            ui::caution(),
1512×
            ui::path(format!("{p}/")),
1522×
            ui::dim(format!("a nested {kind} repository"))
153
        );
154
    }
1552×
    println!(
156
        "  {} {}",
1572×
        ui::note(),
1582×
        ui::dim(
159
            "to track one's files, remove its .git (or .oxy); to keep it a repository of its own, \
160
             oxy submodule add URL PATH; to leave it out quietly, list it in .oxyignore"
161
        )
162
    );
16331×
}
164
165
/// The working copy's changed paths, or that it is clean.
1665×
fn print_statuses(statuses: &[oxy_core::repo::PathStatus]) {
1675×
    if statuses.is_empty() {
1683×
        println!(
169
            "  {} {}",
1703×
            ui::ok(ui::glyph("✔", "*")),
1713×
            ui::dim("nothing to commit, working copy clean")
172
        );
1733×
        return;
1742×
    }
1752×
    println!();
1762×
    for s in statuses {
1772×
        println!(
1782×
            "  {} {}",
1792×
            ui::status_mark(status_tag(s.status)),
1802×
            ui::path(&s.path)
1812×
        );
1822×
    }
1835×
}
184
185
/// Say when the working copy has fallen behind its own bookmark: a
186
/// "clean" status there hid a pull that left it on old code (oxygen#89).
1875×
fn print_behind(repo: &Repo) {
1885×
    if let Ok(Some(n)) = repo.working_copy_behind() {
1890×
        println!(
1900×
            "  {} {}",
1910×
            ui::caution(),
1920×
            ui::warn(format!(
1930×
                "the working copy is behind {}: it lacks {} the bookmark has; oxy checkout brings it up",
1940×
                repo.config.bookmark,
1950×
                plural(n, "change")
1960×
            ))
1970×
        );
1985×
    }
1995×
}
200
2018×
pub fn status(json: bool) -> Result<i32> {
2028×
    let repo = open()?;
203
    // Answered by the manifest alone, with no history to load (oxygen#35,
204
    // #41): a clean working copy, or one as the last snapshot left it.
2058×
    let known = if json {
2063×
        None
207
    } else {
2085×
        repo.status_by_manifest()?
209
    };
2108×
    if let Some(statuses) = known {
2113×
        let (_, wc) = repo.working_copy()?;
2123×
        let heads = repo.bookmark_heads()?;
2133×
        println!(
214
            "{} {}{}working copy {}{}{}",
2153×
            ui::dim("On"),
2163×
            ui::bookmark(&repo.config.bookmark),
2173×
            ui::sep(),
2183×
            ui::id(wc.change_id.short(8)),
2193×
            ui::sep(),
2203×
            ui::dim(plural(heads.len(), "head"))
221
        );
2223×
        print_behind(&repo);
2233×
        print_statuses(&statuses);
2243×
        print_untracked_nested(&repo, &repo.untracked_nested());
2253×
        print_skipped_large(&repo);
2263×
        return Ok(0);
2275×
    }
2285×
    let sp = ui::spinner("Snapshotting the working copy…");
2295×
    let snap = repo.snapshot_status("oxy status")?;
2305×
    let heads = {
2315×
        let _t = oxy_core::timing::phase("status: heads");
2325×
        repo.bookmark_heads()?
233
    };
2345×
    let _drop = oxy_core::timing::phase("status: print and drop");
2355×
    sp.clear();
2365×
    if json {
2373×
        println!("{}", repo.status_json(&snap)?);
2383×
        return Ok(if snap.base_snapshot.is_conflicted() {
2390×
            2
240
        } else {
2413×
            0
242
        });
2432×
    }
2442×
    println!(
245
        "{} {}{}working copy {}{}{}",
2462×
        ui::dim("On"),
2472×
        ui::bookmark(&repo.config.bookmark),
2482×
        ui::sep(),
2492×
        ui::id(snap.wc.change_id.short(8)),
2502×
        ui::sep(),
2512×
        ui::dim(plural(heads.len(), "head"))
252
    );
2532×
    print_behind(&repo);
2542×
    print_statuses(&snap.statuses);
2552×
    print_untracked_nested(&repo, &snap.untracked_nested);
2562×
    print_skipped_large(&repo);
2572×
    if !snap.base_snapshot.is_conflicted() {
2582×
        return Ok(0);
2590×
    }
2600×
    println!();
2610×
    println!(
262
        "{} {}",
2630×
        ui::section(ui::err("Conflicts")),
2640×
        ui::dim("edit the marked files, or the .oxy-conflict-N candidates, then commit")
265
    );
2660×
    for c in &snap.base_snapshot.tree.conflicts {
2670×
        println!("  {} tree: {c:?}", ui::err(ui::glyph("✱", "!")));
2680×
    }
2690×
    for (p, f) in &snap.base_snapshot.files {
2700×
        if f.is_conflicted() {
2710×
            let state = match snap
2720×
                .statuses
2730×
                .iter()
2740×
                .find(|s| s.path == *p)
2750×
                .map(|s| s.status)
276
            {
277
                Some(ChangeStatus::Resolved) => {
2780×
                    ui::ok(format!("{} resolved in working copy", ui::glyph("✔", "*")))
279
                }
280
                Some(ChangeStatus::ConflictEdited) => {
2810×
                    ui::warn(format!("{} markers remain", ui::glyph("‼", "!")))
282
                }
2830×
                _ => ui::err(format!("{} unresolved", ui::glyph("✱", "!"))),
284
            };
2850×
            println!("  {}  {state}", ui::path(p));
2860×
        }
287
    }
2880×
    Ok(2)
2898×
}
290
29126×
pub fn commit(
29226×
    message: &str,
29326×
    depends_on: &[String],
29426×
    paths: &[String],
29526×
    interactive: bool,
29626×
    hunks: &[usize],
29726×
) -> Result<i32> {
29826×
    let repo = open()?;
29926×
    let mut deps = Vec::new();
30026×
    for d in depends_on {
3010×
        deps.push(repo.resolve_change(d)?);
302
    }
30326×
    let selection = if !hunks.is_empty() {
3041×
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
30525×
    } else if interactive {
3060×
        let (_, hunks) = repo.hunks()?;
3070×
        if hunks.is_empty() {
3080×
            anyhow::bail!("nothing to commit: the working copy matches its base");
3090×
        }
3100×
        let hunks: Vec<_> = hunks
3110×
            .into_iter()
3120×
            .filter(|h| {
3130×
                paths.is_empty()
3140×
                    || paths.iter().any(|p| {
3150×
                        h.path == *p || h.path.starts_with(&format!("{}/", p.trim_end_matches('/')))
3160×
                    })
3170×
            })
3180×
            .collect();
3190×
        let mut chosen = Vec::new();
3200×
        let stdin = std::io::stdin();
3210×
        let mut take_rest = false;
3220×
        for (n, h) in hunks.iter().enumerate() {
3230×
            if take_rest {
3240×
                chosen.push(h.index);
3250×
                continue;
3260×
            }
3270×
            println!(
328
                "{} {} {}",
3290×
                ui::section(format!("hunk {} of {}", n + 1, hunks.len())),
3300×
                ui::path(&h.path),
3310×
                ui::dim(format!("(#{})", h.index))
332
            );
3330×
            for line in h.text.lines() {
3340×
                let styled = if line.starts_with('+') {
3350×
                    ui::ok(line)
3360×
                } else if line.starts_with('-') {
3370×
                    ui::err(line)
338
                } else {
3390×
                    ui::dim(line)
340
                };
3410×
                println!("  {styled}");
342
            }
343
            loop {
3440×
                print!(
345
                    "{} ",
3460×
                    ui::warn("Commit this hunk? [y]es [n]o [a]ll remaining [q]uit:")
347
                );
348
                use std::io::Write as _;
3490×
                std::io::stdout().flush()?;
3500×
                let mut answer = String::new();
3510×
                if stdin.read_line(&mut answer)? == 0 {
3520×
                    anyhow::bail!("aborted");
3530×
                }
3540×
                match answer.trim() {
3550×
                    "y" | "Y" => {
3560×
                        chosen.push(h.index);
3570×
                        break;
358
                    }
3590×
                    "n" | "N" | "" => break,
3600×
                    "a" | "A" => {
3610×
                        chosen.push(h.index);
3620×
                        take_rest = true;
3630×
                        break;
364
                    }
3650×
                    "q" | "Q" => anyhow::bail!("aborted; nothing committed"),
3660×
                    _ => continue,
367
                }
368
            }
369
        }
3700×
        if chosen.is_empty() {
3710×
            anyhow::bail!("no hunks chosen; nothing committed");
3720×
        }
3730×
        oxy_core::repo::Selection::Hunks(chosen)
37425×
    } else if paths.is_empty() {
37523×
        oxy_core::repo::Selection::All
376
    } else {
3772×
        oxy_core::repo::Selection::Paths(paths.to_vec())
378
    };
37926×
    let sp = ui::spinner("Committing…");
38026×
    let (h, partial) = repo.commit_selection_partial(message, &deps, &selection)?;
381
    // The metadata only: a first commit's change holds the whole tree.
38226×
    let meta = repo.store().get_change_meta(&h)?;
38326×
    sp.done(&format!(
38426×
        "{} {} {}  {}",
38526×
        ui::done("Committed"),
38626×
        ui::id(meta.change_id.short(8)),
38726×
        ui::hash(format!("#{}", h.short(12))),
38826×
        ui::subject(subject_of(message))
38926×
    ));
39026×
    print_untracked_nested(&repo, &repo.untracked_nested());
39126×
    print_skipped_large(&repo);
392
    // Only a commit that took part of the working copy leaves anything.
39326×
    if partial {
3942×
        let rest = repo.snapshot_status("oxy commit")?;
3952×
        if !rest.statuses.is_empty() {
3962×
            println!(
3972×
                "  {} {}",
3982×
                ui::note(),
3992×
                ui::dim(format!(
4002×
                    "{} left uncommitted",
4012×
                    plural(rest.statuses.len(), "path")
4022×
                ))
4032×
            );
4042×
        }
40524×
    }
40626×
    where_now(&repo);
40726×
    Ok(0)
40826×
}
409
4100×
pub fn blame(path: &str, json: bool) -> Result<i32> {
4110×
    let repo = open()?;
4120×
    let lines = repo.blame(path)?;
4130×
    if json {
4140×
        let items = lines.iter().map(|l| {
4150×
            format!(
416
                "{{\"line\":{},\"change_id\":{},\"hash\":{},\"index\":{},\"author\":{},\"when_ms\":{}}}",
417
                l.line,
4180×
                oxy_core::repo::json_str(&l.change_id.to_hex()),
4190×
                oxy_core::repo::json_str(&l.hash.to_hex()),
420
                l.index,
4210×
                oxy_core::repo::json_str(&l.author),
422
                l.when_ms
423
            )
4240×
        });
4250×
        println!("{}", oxy_core::repo::json_array(items));
4260×
        return Ok(0);
4270×
    }
4280×
    let width = lines
4290×
        .iter()
4300×
        .map(|l| l.author.chars().count())
4310×
        .max()
4320×
        .unwrap_or(0)
4330×
        .min(20);
4340×
    let digits = lines.len().to_string().len();
4350×
    let _t = oxy_core::timing::phase("blame: print");
436
    // Most lines share their change with many others: each change's id,
437
    // author and age are formatted once, and the lines go out through one
438
    // buffered lock on stdout.
4390×
    let mut prefix: std::collections::HashMap<oxy_core::hash::ChangeHash, String> =
4400×
        std::collections::HashMap::new();
4410×
    let bar = ui::dim(ui::glyph("│", "|"));
4420×
    let mut out = std::io::BufWriter::with_capacity(1 << 16, std::io::stdout().lock());
4430×
    for l in &lines {
4440×
        let p = prefix.entry(l.hash).or_insert_with(|| {
4450×
            let author: String = l.author.chars().take(20).collect();
4460×
            format!(
447
                "{} {} {}",
4480×
                ui::id(l.change_id.short(8)),
4490×
                ui::author(format!("{author:<width$}")),
4500×
                ui::dim(ui::ago(l.when_ms))
451
            )
4520×
        });
4530×
        let text = String::from_utf8_lossy(&l.text);
4540×
        if writeln!(
4550×
            out,
456
            "{p} {:>digits$}{bar} {}",
457
            l.line,
4580×
            text.trim_end_matches('\n')
459
        )
4600×
        .is_err()
461
        {
462
            // A closed pipe (blame | head): stop quietly.
4630×
            return Ok(0);
4640×
        }
465
    }
4660×
    let _ = out.flush();
4670×
    Ok(0)
4680×
}
469
4700×
fn bisect_report(repo: &Repo, step: &oxy_core::repo::BisectStep) -> Result<i32> {
471
    use oxy_core::repo::BisectStep::*;
4720×
    match step {
4730×
        NeedMarks { good, bad } => {
4740×
            println!(
475
                "{} {} {}",
4760×
                ui::note(),
4770×
                ui::dim(format!("{good} good, {bad} bad;")),
4780×
                ui::dim(if *good == 0 {
4790×
                    "mark a known-good change or bookmark: oxy bisect good CHANGE"
480
                } else {
4810×
                    "mark a known-bad change or bookmark: oxy bisect bad CHANGE"
482
                })
483
            );
4840×
            Ok(0)
485
        }
486
        Testing {
4870×
            heads,
4880×
            remaining,
4890×
            steps_left,
490
        } => {
4910×
            println!(
492
                "{} {} {}",
4930×
                ui::done("Testing"),
4940×
                ui::dim(format!(
495
                    "{} in the state under test;",
4960×
                    plural(heads.len(), "head")
497
                )),
4980×
                ui::dim(format!(
499
                    "{remaining} candidates left, about {steps_left} more steps"
500
                ))
501
            );
5020×
            println!(
503
                "  {} {}",
5040×
                ui::note(),
5050×
                ui::dim("run your test, then oxy bisect good | bad | skip")
506
            );
5070×
            Ok(0)
508
        }
5090×
        Found { culprit } => {
5100×
            let c = repo.store().get_change(culprit)?;
5110×
            println!(
512
                "{} {} {}  {}",
5130×
                ui::done("Found"),
5140×
                ui::id(short_id(&c)),
5150×
                ui::hash(format!("#{}", culprit.short(12))),
5160×
                ui::subject(subject_of(&c.message))
517
            );
5180×
            println!("  {} {}", ui::note(), ui::dim("the first change whose inclusion makes the state bad; oxy bisect reset to return"));
5190×
            Ok(0)
520
        }
5210×
        Inconclusive { candidates } => {
5220×
            println!(
523
                "{} {}",
5240×
                ui::caution(),
5250×
                ui::warn(format!(
526
                    "every remaining candidate was skipped ({}); oxy bisect reset to return",
5270×
                    plural(candidates.len(), "change")
528
                ))
529
            );
5300×
            Ok(1)
531
        }
532
    }
5330×
}
534
5350×
pub fn bisect_start() -> Result<i32> {
5360×
    let repo = open()?;
5370×
    repo.bisect_start()?;
5380×
    println!(
539
        "{} bisect; {}",
5400×
        ui::done("Started"),
5410×
        ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE")
542
    );
5430×
    Ok(0)
5440×
}
545
5460×
pub fn bisect_mark(good: Option<bool>, changes: &[String]) -> Result<i32> {
5470×
    let repo = open()?;
5480×
    let mut heads = Vec::new();
5490×
    for c in changes {
5500×
        heads.extend(repo.resolve_heads(c)?);
551
    }
5520×
    let step = repo.bisect_mark(good, &heads)?;
5530×
    bisect_report(&repo, &step)
5540×
}
555
5560×
pub fn bisect_run(command: &[String]) -> Result<i32> {
5570×
    let repo = open()?;
5580×
    let step = repo.bisect_run(command)?;
5590×
    bisect_report(&repo, &step)
5600×
}
561
5621×
pub fn bisect_status(as_json: bool) -> Result<i32> {
5631×
    let repo = open()?;
5641×
    if as_json {
565
        use oxy_core::repo::BisectStep::*;
5661×
        let v = match repo.bisect_status()? {
5671×
            None => "null".to_string(),
5680×
            Some(NeedMarks { good, bad }) => json::obj([
5690×
                ("state", json::s("need-marks")),
5700×
                ("good", json::n(good)),
5710×
                ("bad", json::n(bad)),
5720×
            ]),
573
            Some(Testing {
5740×
                heads,
5750×
                remaining,
5760×
                steps_left,
5770×
            }) => json::obj([
5780×
                ("state", json::s("testing")),
5790×
                ("heads", json::hashes(&heads)),
5800×
                ("remaining", json::n(remaining)),
5810×
                ("steps_left", json::n(steps_left)),
5820×
            ]),
5830×
            Some(Found { culprit }) => json::obj([
5840×
                ("state", json::s("found")),
5850×
                ("culprit", json::s(&culprit.to_hex())),
5860×
            ]),
5870×
            Some(Inconclusive { candidates }) => json::obj([
5880×
                ("state", json::s("inconclusive")),
5890×
                ("candidates", json::hashes(&candidates)),
5900×
            ]),
591
        };
5921×
        println!("{v}");
5931×
        return Ok(0);
5940×
    }
5950×
    match repo.bisect_status()? {
596
        None => {
5970×
            println!("{}", ui::dim("No bisect in progress."));
5980×
            Ok(0)
599
        }
6000×
        Some(step) => bisect_report(&repo, &step),
601
    }
6021×
}
603
6040×
pub fn bisect_reset() -> Result<i32> {
6050×
    let repo = open()?;
6060×
    repo.bisect_reset()?;
6070×
    println!("{} bisect; working copy restored", ui::done("Reset"));
6080×
    Ok(0)
6090×
}
610
611
/// The log: one entry per change, newest first, joined by a rail. The
612
/// default view is the subject and a metadata line; `verbose` adds the full
613
/// message, dependencies, and the authenticating key.
61414×
fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
61514×
    Ok(match repo.authenticate_change(h)? {
6169×
        SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]),
617
        SignatureStatus::Valid {
6185×
            key,
6195×
            name,
6205×
            email,
6215×
            sealed,
6225×
            revoked,
6235×
        } => json::obj([
6245×
            ("status", json::s(if sealed { "sealed" } else { "signed" })),
6255×
            ("key", json::s(&key.to_hex())),
6265×
            ("name", json::s(&name)),
6275×
            ("email", json::s(&email)),
6285×
            ("revoked", json::b(revoked)),
629
        ]),
6300×
        SignatureStatus::Invalid(why) => {
6310×
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
632
        }
633
    })
63414×
}
635
63618×
fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result<String> {
63718×
    let c = &e.change;
63818×
    Ok(json::obj([
63918×
        ("hash", json::s(&e.hash.to_hex())),
64018×
        ("change_id", json::s(&c.change_id.to_hex())),
64118×
        ("author", json::s(&author_name(repo, c))),
64218×
        ("author_key", json::s(&c.author.to_hex())),
643
        (
64418×
            "via",
64518×
            match via(
64618×
                repo,
64718×
                &repo.authenticate_change_known(&e.hash, Some(c))?,
64818×
                &c.author,
649
            ) {
6500×
                Some(v) => json::obj([
6510×
                    ("name", json::s(&v.name)),
6520×
                    ("email", json::s(&v.email)),
6530×
                    ("key", json::s(&v.key.to_hex())),
6540×
                    ("scope", json::opt(v.scope.as_deref(), json::s)),
6550×
                    ("expires_ms", json::opt(v.expires, json::n)),
6560×
                    ("revoked", json::b(v.revoked)),
6570×
                ]),
65818×
                None => "null".to_string(),
659
            },
660
        ),
66118×
        ("when_ms", json::n(c.hlc.wall_ms)),
66218×
        ("message", json::s(&c.message)),
66318×
        ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())),
66418×
        ("deps", json::hashes(&c.deps)),
66518×
        ("head", json::b(e.is_head)),
66618×
        ("working_copy", json::b(e.is_working_copy)),
667
        (
66818×
            "signature",
66918×
            if e.is_working_copy {
6704×
                "null".into()
671
            } else {
67214×
                signature_json(repo, &e.hash)?
673
            },
674
        ),
675
    ]))
67618×
}
677
678
/// `START,END:PATH` for `oxy log -L`.
6792×
fn parse_line_range(spec: &str) -> Result<(usize, usize, &str)> {
6802×
    let bad = || anyhow::anyhow!("-L {spec}: expected START,END:PATH, as 10,24:src/lib.rs");
6812×
    let (range, path) = spec.split_once(':').ok_or_else(bad)?;
6822×
    let (a, b) = range.split_once(',').ok_or_else(bad)?;
683
    Ok((
6841×
        a.trim().parse().map_err(|_| bad())?,
6851×
        b.trim().parse().map_err(|_| bad())?,
6861×
        path,
687
    ))
6882×
}
689
6908×
pub fn log(
6918×
    revset: Option<&str>,
6928×
    limit: Option<usize>,
6938×
    verbose: bool,
6948×
    path: Option<&str>,
6958×
    lines: Option<&str>,
6968×
    as_json: bool,
6978×
) -> Result<i32> {
6988×
    let repo = open()?;
699
    // Whether the working copy is clean and conflicted: from the manifest
700
    // when it proves the working copy clean, else from a snapshot.
701
    // The working copy as last recorded, without looking at the files (as
702
    // Git's log does not): whether its change holds edits, and whether its
703
    // base was conflicted. `oxy status` is what checks the disk.
7048×
    let conflicted = !repo.is_at_op() && repo.recorded_conflicted()?;
7058×
    let listing = oxy_core::timing::phase("log: entries");
7068×
    let entries = match (path, lines) {
7078×
        _ if revset.is_some() => repo.log_revset(revset.unwrap_or_default())?,
7082×
        (_, Some(spec)) => {
7092×
            let (first, last, p) = parse_line_range(spec)?;
7101×
            let (_, wc) = repo.working_copy()?;
7111×
            let base = repo.load_state_history(&wc.deps)?.maximal(&wc.deps);
7121×
            repo.line_history(&base, p, first, last)?
713
        }
7141×
        (Some(p), None) => repo.log_for_path(p)?,
7155×
        (None, None) => repo.log()?,
716
    };
7177×
    drop(listing);
7187×
    let _print = oxy_core::timing::phase("log: print");
7197×
    if as_json {
7206×
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
7216×
        let mut items = Vec::new();
72217×
        for e in entries.iter().take(shown) {
72317×
            items.push(log_entry_json(&repo, e)?);
724
        }
7256×
        println!(
726
            "{}",
7276×
            json::obj([
7286×
                ("bookmark", json::s(&repo.config.bookmark)),
7296×
                ("total", json::n(entries.len())),
7306×
                ("changes", json::arr(items))
7316×
            ])
732
        );
7336×
        return Ok(0);
7341×
    }
7351×
    let total = entries.len();
7361×
    let shown = limit.unwrap_or(total).min(total);
737
    // Lay out a little past what is shown, so edges into the cut are drawn.
7381×
    let window: Vec<(ChangeHash, Vec<ChangeHash>)> = entries
7391×
        .iter()
7401×
        .take((shown + MAX_EDGE).min(total))
7414×
        .map(|e| (e.hash, e.change.deps.clone()))
7421×
        .collect();
7431×
    let rows = oxy_core::lanes::graph(&window, MAX_EDGE);
744
    // Highlight the shortest prefix that names each change: against the
745
    // whole log, which is what `resolve_change` searches.
746
    let everything;
7471×
    let all = if path.is_some() || lines.is_some() || revset.is_some() {
7480×
        everything = repo.log()?;
7490×
        &everything
750
    } else {
7511×
        &entries
752
    };
7531×
    let prefixes = oxy_core::timing::phase("log: id prefixes");
7541×
    let id_prefix = id_prefixes(
7551×
        all.iter().map(|e| e.change.change_id.0).collect(),
7561×
        entries.iter().take(shown).map(|e| e.change.change_id.0),
757
    );
7581×
    drop(prefixes);
7591×
    let labels = reference_labels(&repo)?;
7604×
    for (e, row) in entries.iter().take(shown).zip(&rows) {
7614×
        let c = &e.change;
7624×
        let bullet = ui::log_bullet(
7634×
            e.is_working_copy,
7644×
            e.is_head,
7654×
            e.is_working_copy && conflicted,
766
        );
7674×
        let id = c.change_id.to_hex();
7684×
        let n = id_prefix.get(&c.change_id.0).copied().unwrap_or(8).min(8);
7694×
        let mut head = vec![format!("{}{}", ui::id(&id[..n]), ui::dim(&id[n..8]))];
7704×
        head.push(ui::author(author_name(&repo, c)));
7714×
        head.push(ui::dim(ui::ago(c.hlc.wall_ms)));
7724×
        if let Some(names) = labels.get(&e.hash) {
7732×
            head.push(names.join(" "));
7742×
        }
7754×
        if c.kind == ChangeKind::Resolution {
7760×
            head.push(ui::warn("resolution"));
7774×
        }
7784×
        if !e.is_working_copy {
7793×
            head.push(ui::hash(format!("#{}", e.hash.short(8))));
7803×
            let status = repo.authenticate_change_known(&e.hash, Some(c))?;
7813×
            if let Some(agent) = via(&repo, &status, &c.author) {
7820×
                head.push(ui::dim(format!("via {}", agent.name)));
7833×
            }
7843×
            head.push(signature_mark_of(&status));
7851×
        }
7864×
        println!("{}{}", node_line(row, &bullet), head.join(" "));
7874×
        let subject = if e.is_working_copy && c.message.is_empty() {
7881×
            let edited = repo
7891×
                .store()
7901×
                .get_change(&e.hash)
7911×
                .is_ok_and(|w| !w.tree_ops.is_empty() || !w.edits.is_empty());
7921×
            ui::dim(if edited {
7930×
                "(working copy, uncommitted changes)"
794
            } else {
7951×
                "(working copy)"
796
            })
7973×
        } else if c.message.trim().is_empty() {
7980×
            ui::dim("(no description)")
799
        } else {
8003×
            subject_of(&c.message).to_string()
801
        };
8024×
        println!("{}{subject}", below_line(row));
8034×
        if verbose {
8040×
            let rail = continuation(row);
8050×
            if !e.is_working_copy {
8060×
                println!(
807
                    "{rail}{}",
8080×
                    ui::dim(format!(
809
                        "{} {}",
8100×
                        when(c.hlc.wall_ms),
8110×
                        signature_line(&repo, &e.hash)?
812
                    ))
813
                );
8140×
            }
8150×
            if !c.deps.is_empty() {
8160×
                println!(
8170×
                    "{rail}{} {}",
8180×
                    ui::dim(ui::glyph("↳", "->")),
8190×
                    ui::dim(deps_of(&c.deps))
8200×
                );
8210×
            }
8220×
            let body: Vec<&str> = c
8230×
                .message
8240×
                .lines()
8250×
                .skip(1)
8260×
                .skip_while(|l| l.trim().is_empty())
8270×
                .collect();
8280×
            for line in body {
8290×
                println!("{rail}  {line}");
8300×
            }
8314×
        }
832
    }
8331×
    if shown < total {
8340×
        if let Some(last) = rows.get(shown.saturating_sub(1)) {
8350×
            let cut: String = last
8360×
                .below
8370×
                .iter()
8380×
                .map(|c| match c {
8390×
                    Cell::Blank | Cell::Elided | Cell::JoinRight => "  ",
8400×
                    _ => "~ ",
8410×
                })
8420×
                .collect();
8430×
            if cut.trim().is_empty() {
8440×
                println!("{}", ui::dim("~"));
8450×
            } else {
8460×
                println!("{}", ui::dim(cut.trim_end()));
8470×
            }
8480×
        }
8490×
        println!(
850
            "{}",
8510×
            ui::dim(format!(
852
                "{} {} more; pass -n to see them",
8530×
                ui::glyph("…", "..."),
8540×
                total - shown
855
            ))
856
        );
8571×
    }
8581×
    Ok(0)
8598×
}
860
861
/// Rows a drawn edge may span in `oxy log`; a longer one is elided (`~`).
862
const MAX_EDGE: usize = 12;
863
864
use oxy_core::hash::ChangeHash;
865
use oxy_core::lanes::{Cell, GraphRow};
866
867
/// A graph cell, two columns wide.
8686×
fn cell(c: Cell) -> &'static str {
8696×
    match c {
8701×
        Cell::Blank => "  ",
8713×
        Cell::Line => ui::glyph("│ ", "| "),
8720×
        Cell::Elided => "~ ",
8731×
        Cell::JoinLeft => ui::glyph("├─", "|-"),
8740×
        Cell::JoinPass => ui::glyph("──", "--"),
8750×
        Cell::JoinCross => ui::glyph("┼─", "+-"),
8761×
        Cell::JoinRight => ui::glyph("╯ ", "' "),
877
    }
8786×
}
879
880
/// The graph part of a change's own line, its bullet in its column.
8814×
fn node_line(row: &GraphRow, bullet: &str) -> String {
8824×
    let width = row
8834×
        .passing
8844×
        .iter()
8854×
        .copied()
8864×
        .max()
8874×
        .unwrap_or(0)
8884×
        .max(row.column)
8894×
        + 1;
8904×
    let mut out = String::new();
8915×
    for c in 0..width {
8925×
        if c == row.column {
8934×
            out.push_str(bullet);
8944×
            out.push(' ');
8954×
        } else if row.passing.contains(&c) {
8961×
            out.push_str(&ui::dim(cell(Cell::Line)));
8971×
        } else {
8980×
            out.push_str("  ");
8990×
        }
900
    }
9014×
    out.push(' ');
9024×
    out
9034×
}
904
905
/// The graph part of the line under a change: lanes carrying on, a join,
906
/// or `~` for an elided edge.
9074×
fn below_line(row: &GraphRow) -> String {
9085×
    let g: String = row.below.iter().map(|c| cell(*c)).collect();
9094×
    format!("{} ", ui::dim(g))
9104×
}
911
912
/// The graph part of any further line of a change (`-v`).
9130×
fn continuation(row: &GraphRow) -> String {
9140×
    let g: String = row
9150×
        .below
9160×
        .iter()
9170×
        .map(|c| match c {
9180×
            Cell::Line | Cell::JoinLeft | Cell::JoinCross => cell(Cell::Line),
9190×
            _ => "  ",
9200×
        })
9210×
        .collect();
9220×
    format!("{} ", ui::dim(g))
9230×
}
924
925
/// For each hex ID, the length of its shortest prefix no other ID shares.
926
/// The shortest prefix, in hex digits, that names each of `wanted` among
927
/// `all`: worked out for the few shown rather than for the whole history.
9282×
fn id_prefixes(
9292×
    mut all: Vec<[u8; 16]>,
9302×
    wanted: impl Iterator<Item = [u8; 16]>,
9312×
) -> std::collections::HashMap<[u8; 16], usize> {
9322×
    all.sort_unstable();
9332×
    all.dedup();
934
    // Hex digits two ids share at the start.
9354004×
    let common = |a: &[u8; 16], b: &[u8; 16]| {
93610720×
        let bytes = a.iter().zip(b).take_while(|(x, y)| x == y).count();
9374004×
        match (a.get(bytes), b.get(bytes)) {
9384004×
            (Some(x), Some(y)) if x >> 4 == y >> 4 => 2 * bytes + 1,
9391856×
            _ => 2 * bytes,
940
        }
9414004×
    };
9422×
    let mut out = std::collections::HashMap::new();
9432004×
    for id in wanted {
9442004×
        let Ok(i) = all.binary_search(&id) else {
9450×
            continue;
946
        };
9472004×
        let before = i.checked_sub(1).map_or(0, |j| common(&all[j], &id));
9482004×
        let after = all.get(i + 1).map_or(0, |n| common(&id, n));
9492004×
        out.insert(id, before.max(after) + 1);
950
    }
9512×
    out
9522×
}
953
9541×
fn unique_prefixes(ids: impl Iterator<Item = String>) -> std::collections::HashMap<String, usize> {
9551×
    let mut v: Vec<String> = ids.collect();
9561×
    v.sort();
9571×
    v.dedup();
95819576×
    let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
9591×
    let mut out = std::collections::HashMap::with_capacity(v.len());
9602000×
    for i in 0..v.len() {
9612000×
        let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 };
9622000×
        let after = if i + 1 < v.len() {
9631999×
            common(&v[i], &v[i + 1])
964
        } else {
9651×
            0
966
        };
9672000×
        out.insert(v[i].clone(), before.max(after) + 1);
968
    }
9691×
    out
9701×
}
971
972
/// Bookmark, remote bookmark and tag names to show beside the changes they
973
/// point at. A name is shown on each head of its state; one with more than
974
/// three heads names too much of the log to help, so it is left out (oxy
975
/// bookmark list shows it). A remote bookmark at the same state as the
976
/// local one of that name is not repeated.
9771×
fn reference_labels(repo: &Repo) -> Result<std::collections::HashMap<ChangeHash, Vec<String>>> {
978
    const MAX_HEADS: usize = 3;
9791×
    let view = repo.view()?;
9801×
    let mut out: std::collections::HashMap<ChangeHash, Vec<String>> = Default::default();
9811×
    let mut add = |heads: Vec<ChangeHash>, label: String| {
9821×
        if heads.len() <= MAX_HEADS {
9832×
            for h in heads {
9842×
                out.entry(h).or_default().push(label.clone());
9852×
            }
9860×
        }
9871×
    };
9881×
    for (name, st) in &view.bookmarks {
9891×
        add(repo.store().get_state(st)?.heads, ui::bookmark(name));
990
    }
9911×
    for (remote, bookmarks) in &view.remotes {
9920×
        for (name, st) in bookmarks {
9930×
            if view.bookmarks.get(name) == Some(st) {
9940×
                continue;
9950×
            }
9960×
            add(
9970×
                repo.store().get_state(st)?.heads,
9980×
                ui::dim(format!("{remote}/{name}")),
999
            );
1000
        }
1001
    }
10021×
    for t in repo.tags()? {
10030×
        add(t.heads.clone(), ui::warn(&t.name));
10040×
    }
10051×
    Ok(out)
10061×
}
1007
10081×
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
10091×
    let repo = open()?;
10101×
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
10111×
    if as_json {
10121×
        let files = repo.diff_files(hash.as_ref())?;
10133×
        let items = files.iter().map(|f| {
10143×
            json::obj([
10153×
                ("path", json::s(&f.path)),
10163×
                ("kind", json::s(&f.kind)),
10173×
                ("from", json::opt(f.from.as_deref(), json::s)),
1018
                (
10193×
                    "hunks",
10203×
                    json::arr(f.hunks.iter().map(|h| {
10213×
                        json::obj([
10223×
                            ("base_line", json::n(h.base_line)),
1023
                            (
10243×
                                "added",
10253×
                                json::arr(
10263×
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
1027
                                ),
1028
                            ),
1029
                            (
10303×
                                "removed",
10313×
                                json::arr(h.removed.iter().map(|(n, l)| {
10320×
                                    json::obj([
10330×
                                        ("line", json::n(*n)),
10340×
                                        ("text", json::s(&String::from_utf8_lossy(l))),
10350×
                                    ])
10360×
                                })),
1037
                            ),
1038
                        ])
10393×
                    })),
1040
                ),
1041
            ])
10423×
        });
10431×
        println!(
1044
            "{}",
10451×
            json::obj([
10461×
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
10471×
                ("files", json::arr(items))
1048
            ])
1049
        );
10501×
        return Ok(0);
10510×
    }
10520×
    match hash {
10530×
        Some(h) => {
10540×
            let c = repo.store().get_change(&h)?;
10550×
            let (base, snapshot) = repo.change_base(&c)?;
10560×
            print!("{}", render_change(&c, &base, &snapshot));
1057
        }
1058
        None => {
1059
            // Nothing changed: nothing to show, and no base to load.
10600×
            let Some((wc, base, snapshot)) = repo.working_copy_with_base_unless_unchanged()? else {
10610×
                return Ok(0);
1062
            };
10630×
            let text = {
10640×
                let _t = oxy_core::timing::phase("diff: render the change");
10650×
                render_change(&wc, &base, &snapshot)
1066
            };
10670×
            print!("{text}");
1068
            // The process ends here: freeing the base's tree and graphs
1069
            // one by one would only cost time (about 27 ms on Linux).
10700×
            std::mem::forget((wc, base, snapshot));
1071
        }
1072
    }
10730×
    Ok(0)
10741×
}
1075
10762×
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
10772×
    let repo = open()?;
10782×
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
10792×
    let bytes = match repo.file_at(path, heads.as_deref()) {
10802×
        Ok(b) => b,
1081
        // -r CHANGE reads that change's dependency closure, not the
1082
        // bookmark it is on: say so when the bookmark has the file
1083
        // (oxygen#76).
10840×
        Err(e) => match change {
10850×
            Some(c)
10860×
                if !repo.view()?.bookmarks.contains_key(c)
10870×
                    && repo.tag_heads(c)?.is_none()
10880×
                    && repo.file_at(path, None).is_ok() =>
1089
            {
10900×
                anyhow::bail!(
1091
                    "{path} is not in {c}'s dependency closure (the change and what it \
1092
                     depends on); it is on the bookmark: try -r {}, or --at-op OP for the \
1093
                     state at an operation",
1094
                    repo.config.bookmark
1095
                )
1096
            }
10970×
            _ => return Err(e.into()),
1098
        },
1099
    };
1100
    use std::io::Write as _;
11012×
    std::io::stdout().write_all(&bytes)?;
11022×
    Ok(0)
11032×
}
1104
11051×
pub fn root(as_json: bool) -> Result<i32> {
11061×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
11070×
        if as_json {
11080×
            println!("null");
11090×
        }
11100×
        return Ok(1);
1111
    };
11121×
    if as_json {
11131×
        println!(
11141×
            "{}",
11151×
            json::obj([
11161×
                ("root", json::s(&repo.root().to_string_lossy())),
11171×
                ("workspace", json::s(&repo.workspace().to_hex())),
11181×
                ("bookmark", json::s(&repo.config.bookmark))
11191×
            ])
11201×
        );
11211×
    } else {
11220×
        println!("{}", repo.root().display());
11230×
    }
11241×
    Ok(0)
11251×
}
1126
11271×
pub fn version(as_json: bool) -> Result<i32> {
11281×
    if as_json {
11291×
        println!(
11301×
            "{}",
11311×
            json::obj([
11321×
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
11331×
                // What was built: a release's or install's `oxy describe`,
11341×
                // a Flow build's heads, or "local build".
11351×
                ("build", json::s(env!("OXY_BUILD_ID"))),
11361×
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
11371×
                ("format", json::n(2))
11381×
            ])
11391×
        );
11401×
    } else {
11410×
        println!(
11420×
            "oxy {} (repository format 2, protocol {})",
11430×
            env!("OXY_VERSION_LONG"),
11440×
            oxy_core::protocol::PROTOCOL_VERSION
11450×
        );
11460×
    }
11471×
    Ok(0)
11481×
}
1149
11502×
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
11512×
    let repo = open()?;
11522×
    if paths.is_empty() && hunks.is_empty() {
11530×
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
11542×
    }
11552×
    let mut n = 0;
11562×
    if !hunks.is_empty() {
11571×
        n += repo.discard_hunks(hunks)?;
11581×
    }
11592×
    if !paths.is_empty() {
11601×
        n += repo.discard(paths)?;
11611×
    }
11622×
    println!(
1163
        "{} {} restored to the working copy's base",
11642×
        ui::done("Discarded"),
11652×
        plural(n, "path")
1166
    );
11672×
    Ok(0)
11682×
}
1169
11702×
pub fn hunks(as_json: bool) -> Result<i32> {
11712×
    let repo = open()?;
11722×
    let (_, hunks) = repo.hunks()?;
11732×
    if as_json {
11742×
        println!(
1175
            "{}",
11765×
            json::arr(hunks.iter().map(|h| json::obj([
11775×
                ("index", json::n(h.index)),
11785×
                ("path", json::s(&h.path)),
11795×
                ("text", json::s(&h.text))
11805×
            ])))
1181
        );
11822×
        return Ok(0);
11830×
    }
11840×
    if hunks.is_empty() {
11850×
        println!(
11860×
            "{}",
11870×
            ui::dim("No hunks: the working copy matches its base.")
11880×
        );
11890×
    }
11900×
    for h in &hunks {
11910×
        println!(
1192
            "{} {}",
11930×
            ui::section(format!("hunk {}", h.index)),
11940×
            ui::path(&h.path)
1195
        );
11960×
        for line in h.text.lines() {
11970×
            let styled = if line.starts_with('+') {
11980×
                ui::ok(line)
11990×
            } else if line.starts_with('-') {
12000×
                ui::err(line)
1201
            } else {
12020×
                ui::dim(line)
1203
            };
12040×
            println!("  {styled}");
1205
        }
1206
    }
12070×
    Ok(0)
12082×
}
1209
12103×
pub fn show(change: Option<&str>, revset: Option<&str>, stat: bool, as_json: bool) -> Result<i32> {
12113×
    let repo = open()?;
12123×
    repo.snapshot_status("oxy show")?;
12133×
    let Some(r) = revset else {
12143×
        let h = repo.resolve_change(change.unwrap_or("@"))?;
12153×
        return show_one(&repo, h, as_json, false, stat);
1216
    };
1217
    // Several changes: a JSON array, or the changes one after another.
12180×
    let hashes = repo.revset(r)?.hashes;
12190×
    if as_json {
12200×
        print!("[");
12210×
        for (i, h) in hashes.iter().enumerate() {
12220×
            if i > 0 {
12230×
                print!(",");
12240×
            }
12250×
            show_one(&repo, *h, true, true, stat)?;
1226
        }
12270×
        println!("]");
12280×
        return Ok(0);
12290×
    }
12300×
    if hashes.is_empty() {
12310×
        println!("{}", ui::dim(format!("No change matches {r:?}.")));
12320×
        return Ok(0);
12330×
    }
12340×
    for (i, h) in hashes.iter().enumerate() {
12350×
        if i > 0 {
12360×
            println!();
12370×
        }
12380×
        show_one(&repo, *h, false, false, stat)?;
1239
    }
12400×
    Ok(0)
12413×
}
1242
1243
/// Lines added and removed in one file's diff.
12442×
fn counts(f: &oxy_core::repo::FileDiff) -> (usize, usize) {
12452×
    f.hunks
12462×
        .iter()
12472×
        .fold((0, 0), |(a, r), h| (a + h.added.len(), r + h.removed.len()))
12482×
}
1249
1250
/// What `--stat` prints (oxygen#119): each file the change touched, its
1251
/// lines added and removed, then the total.
12521×
fn print_stat(files: &[oxy_core::repo::FileDiff]) {
12531×
    let width = files
12541×
        .iter()
12551×
        .map(|f| f.path.chars().count())
12561×
        .max()
12571×
        .unwrap_or(0)
12581×
        .min(60);
12591×
    let (mut added, mut removed) = (0, 0);
12601×
    for f in files {
12611×
        let (a, r) = counts(f);
12621×
        added += a;
12631×
        removed += r;
12641×
        let path = match &f.from {
12650×
            Some(from) => format!("{from} → {}", f.path),
12661×
            None => f.path.clone(),
1267
        };
12681×
        println!(
1269
            " {path:<width$}  {} {}  {}",
12701×
            ui::ok(format!("{:>6}", format!("+{a}"))),
12711×
            ui::err(format!("{:>6}", format!("-{r}"))),
12721×
            ui::dim(&f.kind)
1273
        );
1274
    }
12751×
    println!(
1276
        " {}",
12771×
        ui::dim(format!(
1278
            "{} changed, {added} added, {removed} removed",
12791×
            plural(files.len(), "file")
1280
        ))
1281
    );
12821×
}
1283
1284
/// One change, as `oxy show` prints it; `inline` JSON goes without its
1285
/// newline, for an array. `stat` lists the files instead of the diff.
12863×
fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool, stat: bool) -> Result<i32> {
12873×
    let c = repo.store().get_change(&h)?;
12883×
    if as_json {
12891×
        let files = repo.diff_files(Some(&h))?;
12901×
        let heads = repo.bookmark_heads()?;
12911×
        let entry = oxy_core::repo::LogEntry {
12921×
            hash: h,
12931×
            change: oxy_core::state::ChangeMeta::of(&c),
12941×
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
12951×
            is_head: heads.contains(&h),
12961×
        };
12971×
        let mut body = log_entry_json(repo, &entry)?;
12981×
        body.pop();
12991×
        body.push_str(&format!(
1300
            ",{}:{}}}",
13011×
            json::s("files"),
13021×
            json::arr(files.iter().map(|f| {
13031×
                let (a, r) = counts(f);
13041×
                json::obj([
13051×
                    ("path", json::s(&f.path)),
13061×
                    ("kind", json::s(&f.kind)),
13071×
                    ("from", json::opt(f.from.as_deref(), json::s)),
13081×
                    ("added", a.to_string()),
13091×
                    ("removed", r.to_string()),
13101×
                ])
13111×
            }))
1312
        ));
13131×
        if inline {
13140×
            print!("{body}");
13151×
        } else {
13161×
            println!("{body}");
13171×
        }
13181×
        return Ok(0);
13192×
    }
13202×
    println!(
1321
        "{} {} {}",
13222×
        ui::section("change"),
13232×
        ui::id(short_id(&c)),
13242×
        ui::hash(format!("#{h}"))
1325
    );
13262×
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1327
    // Fetched but not pulled (oxygen#56): say where it is.
13282×
    if let Some(at) = repo.remote_only_location(&h)? {
13290×
        println!(
13300×
            "{}",
13310×
            ui::kv(
13320×
                "only in",
13330×
                ui::warn(format!(
13340×
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
13350×
                ))
13360×
            )
13370×
        );
13382×
    }
13392×
    let meta = oxy_core::state::ChangeMeta::of(&c);
13402×
    let status = repo.authenticate_change_known(&h, Some(&meta))?;
13412×
    println!("{}", ui::kv("author", ui::author(author_name(repo, &meta))));
13422×
    if let Some(agent) = via(repo, &status, &meta.author) {
13430×
        println!("{}", ui::kv("via", agent.line()));
13442×
    }
13452×
    println!(
1346
        "{}",
13472×
        ui::kv(
13482×
            "date",
13492×
            format!(
1350
                "{} {}",
13512×
                when(c.hlc.wall_ms),
13522×
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1353
            )
1354
        )
1355
    );
13562×
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
13572×
    println!("{}", ui::kv("sig", signature_line(repo, &h)?));
13582×
    println!();
13595×
    for line in (if c.message.is_empty() {
13600×
        "(no description)"
1361
    } else {
13622×
        &c.message
1363
    })
13642×
    .lines()
13655×
    {
13665×
        println!("    {line}");
13675×
    }
13682×
    println!();
13692×
    if stat {
13701×
        print_stat(&repo.diff_files(Some(&h))?);
1371
    } else {
13721×
        print!("{}", repo.describe_change(&h)?);
1373
    }
13742×
    Ok(0)
13753×
}
1376
13770×
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
13780×
    let repo = open()?;
1379
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1380
    // BRANCH` is: checking its files out under another bookmark's name
1381
    // made the next commit move the wrong bookmark (oxygen#60).
13820×
    if let [name] = changes {
13830×
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
13840×
            drop(repo);
13850×
            return bookmark_switch(name, discard, carry);
13860×
        }
13870×
    }
13880×
    let heads = if changes.is_empty() {
13890×
        repo.bookmark_heads()?
1390
    } else {
13910×
        let mut heads = Vec::new();
13920×
        for c in changes {
13930×
            heads.extend(repo.resolve_heads(c)?);
1394
        }
13950×
        heads
1396
    };
13970×
    let spec = if changes.is_empty() {
13980×
        repo.config.bookmark.clone()
1399
    } else {
14000×
        changes.join(" ")
1401
    };
14020×
    let sp = ui::spinner(&format!("Checking out {spec}…"));
14030×
    let command = format!("oxy checkout {spec}");
14040×
    let (r, carried) = if carry {
14050×
        repo.checkout_carry(&heads, &spec, &command)?
1406
    } else {
14070×
        (repo.checkout(&heads, discard, &command)?, vec![])
1408
    };
14090×
    sp.done(&format!(
1410
        "{} on {}: {} written, {} removed{}",
14110×
        ui::done("Working copy"),
14120×
        ui::bookmark(&spec),
14130×
        plural(r.written, "file"),
1414
        r.removed,
14150×
        if carried.is_empty() {
14160×
            String::new()
1417
        } else {
14180×
            format!("; carried {}", plural(carried.len(), "changed path"))
1419
        }
1420
    ));
14210×
    print_removed(&r);
14220×
    for n in &r.notes {
14230×
        println!("  {} {n}", ui::note());
14240×
    }
14250×
    if r.conflicted {
14260×
        println!(
14270×
            "  {} {}",
14280×
            ui::caution(),
14290×
            ui::warn("this state has conflicts; see oxy status")
14300×
        );
14310×
    }
14320×
    where_now(&repo);
14330×
    Ok(0)
14340×
}
1435
14361×
pub fn resolve(as_json: bool) -> Result<i32> {
14371×
    let repo = open()?;
14381×
    let snap = repo.snapshot("oxy resolve")?;
14391×
    if as_json {
14401×
        println!("{}", repo.status_json(&snap)?);
14411×
        return Ok(if snap.base_snapshot.is_conflicted() {
14420×
            2
1443
        } else {
14441×
            0
1445
        });
14460×
    }
14470×
    if !snap.base_snapshot.is_conflicted() {
14480×
        println!("The working copy's base has no conflicts.");
14490×
        return Ok(0);
14500×
    }
14510×
    let mut remaining = 0;
14520×
    for (p, f) in &snap.base_snapshot.files {
14530×
        if !f.is_conflicted() {
14540×
            continue;
14550×
        }
14560×
        match snap
14570×
            .statuses
14580×
            .iter()
14590×
            .find(|s| s.path == *p)
14600×
            .map(|s| s.status)
1461
        {
14620×
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
14630×
            Some(ChangeStatus::ConflictEdited) => {
14640×
                remaining += 1;
14650×
                println!("markers    {p}");
14660×
            }
14670×
            _ => {
14680×
                remaining += 1;
14690×
                println!("unresolved {p}");
14700×
            }
1471
        }
1472
    }
14730×
    for c in &snap.base_snapshot.tree.conflicts {
14740×
        remaining += 1;
14750×
        println!("tree       {c:?}");
14760×
    }
14770×
    if remaining == 0 {
14780×
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
14790×
        Ok(0)
1480
    } else {
14810×
        Ok(2)
1482
    }
14831×
}
1484
14850×
pub fn undo() -> Result<i32> {
14860×
    let repo = open()?;
14870×
    let u = repo.undo()?;
14880×
    println!("{} {}", ui::done("Undone:"), u.command);
14890×
    for c in &u.changes {
14900×
        println!("  {} {}", ui::note(), change_words(&repo, c));
14910×
    }
14920×
    if u.others_kept > 0 {
14930×
        let s = if u.others_kept == 1 { "" } else { "s" };
14940×
        println!(
1495
            "  {} {}",
14960×
            ui::note(),
14970×
            ui::dim(format!(
1498
                "{} newer operation{s} from other workspaces left as they are",
1499
                u.others_kept
1500
            ))
1501
        );
15020×
    }
15030×
    for (bookmark, remote) in &u.pushed {
15040×
        println!(
15050×
            "  {} {}",
15060×
            ui::caution(),
15070×
            ui::warn(format!(
15080×
                "{remote}/{bookmark} already has what this undid: undone here only; the next push of {bookmark} needs --force to take it back there"
15090×
            ))
15100×
        );
15110×
    }
15120×
    where_now(&repo);
15130×
    Ok(0)
15140×
}
1515
15161×
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
15171×
    let repo = open()?;
15181×
    let ops = repo.op_log()?;
1519
    // What each operation changed, against the one before it.
152011×
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
152111×
        match ops.get(i + 1) {
152210×
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
15231×
            None => Ok(vec![]),
1524
        }
152511×
    };
15261×
    if as_json {
15271×
        let mut items = Vec::new();
152811×
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
152911×
            let summary: Vec<String> = changes_of(i)?
153011×
                .iter()
153111×
                .map(|c| change_words(&repo, c))
153211×
                .collect();
153311×
            items.push(json::obj([
153411×
                ("id", json::s(&r.to_hex())),
153511×
                ("when_ms", json::n(op.hlc.wall_ms)),
153611×
                ("command", json::s(&op.command)),
153711×
                ("snapshot", json::b(op.is_snapshot())),
153811×
                ("current", json::b(i == 0)),
153911×
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1540
            ]));
1541
        }
15421×
        println!("{}", json::arr(items));
15431×
        return Ok(0);
15440×
    }
15450×
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
15460×
    let id = |r: &oxy_core::hash::ObjectRef| {
15470×
        let hex = r.to_hex();
15480×
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
15490×
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
15500×
    };
15510×
    let rail = ui::dim(ui::glyph("│", "|"));
15520×
    let (mut i, mut shown) = (0, 0);
15530×
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
15540×
        let (r, op) = &ops[i];
15550×
        let bullet = if i == 0 {
15560×
            ui::ok(ui::glyph("@", "@"))
1557
        } else {
15580×
            ui::dim(ui::glyph("○", "o"))
1559
        };
1560
        // A run of snapshots folds into one entry.
15610×
        let mut run = 1;
15620×
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
15630×
            run += 1;
15640×
        }
15650×
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
15660×
        if op.is_snapshot() {
15670×
            let span = if run > 1 {
15680×
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1569
            } else {
15700×
                String::new()
1571
            };
15720×
            println!(
1573
                "{bullet}  {}{} {when}",
15740×
                id(r),
15750×
                if span.is_empty() {
15760×
                    String::new()
1577
                } else {
15780×
                    format!(" {span}")
1579
                }
1580
            );
15810×
            println!(
1582
                "{rail}  {}",
15830×
                ui::dim(if run == 1 {
15840×
                    "working-copy snapshot".to_string()
1585
                } else {
15860×
                    format!("{run} working-copy snapshots")
1587
                })
1588
            );
1589
        } else {
15900×
            println!("{bullet}  {} {when}", id(r));
15910×
            let words: Vec<String> = changes_of(i)?
15920×
                .iter()
15930×
                .map(|c| change_words(&repo, c))
15940×
                .collect();
15950×
            let summary = if words.is_empty() {
15960×
                if i + 1 == ops.len() {
15970×
                    "created the repository".to_string()
1598
                } else {
15990×
                    "no bookmark or working-copy change".to_string()
1600
                }
1601
            } else {
16020×
                words.join("; ")
1603
            };
16040×
            println!(
1605
                "{rail}  {}",
16060×
                if i == 0 {
16070×
                    ui::subject(&summary)
1608
                } else {
16090×
                    summary
1610
                }
1611
            );
16120×
            let cmd = op.command.lines().next().unwrap_or("");
16130×
            let cmd: String = cmd.chars().take(100).collect();
16140×
            println!("{rail}  {}", ui::dim(cmd));
1615
        }
16160×
        i += run;
16170×
        shown += 1;
1618
    }
16190×
    if i < ops.len() {
16200×
        println!(
16210×
            "{}",
16220×
            ui::dim(format!(
16230×
                "{} {} older; pass -n to see more",
16240×
                ui::glyph("…", "..."),
16250×
                plural(ops.len() - i, "operation")
16260×
            ))
16270×
        );
16280×
    }
16290×
    Ok(0)
16301×
}
1631
1632
/// One change an operation made, in words.
163311×
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1634
    use oxy_core::repo::ViewChange::*;
16352×
    match c {
16360×
        BookmarkCreated { name, heads } => {
16370×
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1638
        }
16390×
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
16402×
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
16411×
        BookmarkMoved { name, from, to } => format!(
1642
            "{name}: {from} {} {}",
16431×
            ui::glyph("→", "->"),
16441×
            plural(*to, "head")
1645
        ),
16461×
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
16470×
        TagCreated { name } => format!("tagged {name}"),
16480×
        TagDeleted { name } => format!("removed tag {name}"),
16490×
        Policy => "trust policy changed".to_string(),
16508×
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
16518×
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
16520×
            Err(_) => "working copy moved".to_string(),
1653
        },
1654
    }
165511×
}
1656
16570×
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
16580×
    let repo = open()?;
16590×
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
16600×
    let r = repo.op_restore(op, discard)?;
16610×
    sp.done(&format!(
16620×
        "{} to operation {} {}",
16630×
        ui::done("Restored"),
16640×
        ui::hash(r.op.short(12)),
16650×
        ui::dim(r.command.lines().next().unwrap_or(""))
16660×
    ));
16670×
    println!(
1668
        "  {} {}",
16690×
        ui::note(),
16700×
        ui::dim(format!(
1671
            "{} written, {} removed; oxy undo goes back again",
16720×
            plural(r.checkout.written, "file"),
1673
            r.checkout.removed
1674
        ))
1675
    );
16760×
    where_now(&repo);
16770×
    Ok(0)
16780×
}
1679
16800×
pub fn op_revert(op: &str) -> Result<i32> {
16810×
    let repo = open()?;
16820×
    let r = repo.op_revert(op)?;
16830×
    let view = repo.view()?;
16840×
    let names: Vec<String> = r
16850×
        .reverted
16860×
        .iter()
16870×
        .map(|n| {
16880×
            if view.bookmarks.contains_key(n) {
16890×
                ui::bookmark(n)
1690
            } else {
16910×
                format!("{} (removed)", ui::bookmark(n))
1692
            }
16930×
        })
16940×
        .collect();
16950×
    println!(
1696
        "{} operation {} {}",
16970×
        ui::done("Reverted"),
16980×
        ui::hash(r.op.short(12)),
16990×
        ui::dim(r.command.lines().next().unwrap_or(""))
1700
    );
17010×
    println!(
1702
        "  {} {}",
17030×
        ui::note(),
17040×
        ui::dim(format!("as before it: {}", names.join(", ")))
1705
    );
17060×
    if !r.kept.is_empty() {
17070×
        println!(
17080×
            "  {} {}",
17090×
            ui::caution(),
17100×
            ui::warn(format!(
17110×
                "left as they are, having moved again since: {}",
17120×
                r.kept.join(", ")
17130×
            ))
17140×
        );
17150×
    }
17160×
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
17170×
        println!(
17180×
            "  {} {}",
17190×
            ui::note(),
17200×
            ui::dim("the working copy has work of its own: oxy checkout to move it")
17210×
        );
17220×
    }
17230×
    where_now(&repo);
17240×
    Ok(0)
17250×
}
1726
1727
/// Where the working copy and bookmark are now, after a command moved
1728
/// them (as jj says "Working copy now at").
172931×
pub fn where_now(repo: &Repo) {
173031×
    let Ok((_, wc)) = repo.working_copy() else {
17310×
        return;
1732
    };
173331×
    let heads = repo.bookmark_heads().unwrap_or_default();
173431×
    let newest = heads
173531×
        .iter()
173643×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
173731×
        .max_by_key(|(m, _)| m.hlc);
173831×
    println!(
1739
        "  {} {}",
174031×
        ui::dim(format!("{:<13}", "Working copy")),
174131×
        ui::id(wc.change_id.short(8))
1742
    );
174331×
    let tail = match newest {
174431×
        Some((m, _)) => format!(
1745
            ", newest {} {}",
174631×
            ui::id(m.change_id.short(8)),
174731×
            subject_of(&m.message)
1748
        ),
17490×
        None => String::new(),
1750
    };
175131×
    println!(
1752
        "  {} {}: {}{tail}",
175331×
        ui::dim(format!("{:<13}", "Bookmark")),
175431×
        ui::bookmark(&repo.config.bookmark),
175531×
        plural(heads.len(), "head")
1756
    );
175731×
}
1758
17590×
pub fn gc(now: bool, expire_snapshots: bool) -> Result<i32> {
17600×
    let mut repo = open()?;
17610×
    if expire_snapshots {
17620×
        repo.config.snapshot_retention_days = 0;
17630×
    }
17640×
    let sp = ui::spinner("Packing and pruning…");
17650×
    let r = repo.gc_with(now, &mut |phase| sp.set(&format!("{phase}…")))?;
17660×
    sp.clear();
17670×
    if r.packed.objects > 0 {
17680×
        println!(
17690×
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
17700×
            plural(r.packed.objects, "object"),
17710×
            r.packed.raw_bytes,
17720×
            r.packed.packed_bytes,
17730×
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
17740×
        );
17750×
    }
17760×
    println!(
1777
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
17780×
        plural(r.reachable, "object"),
17790×
        plural(r.pruned.objects, "unreachable object"),
1780
        r.pruned.bytes,
17810×
        if r.pruned.deferred > 0 {
17820×
            format!(
1783
                "; {} deferred by the grace period (use --now)",
17840×
                plural(r.pruned.deferred, "object")
1785
            )
1786
        } else {
17870×
            String::new()
1788
        },
17890×
        if r.merged_packs > 0 {
17900×
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1791
        } else {
17920×
            String::new()
1793
        },
17940×
        plural(repo.store().pack_count(), "pack")
1795
    );
1796
    // What earlier repacks replaced stays an hour for readers still using
1797
    // it (oxygenhub#249); a collection after that deletes it.
17980×
    let kept = if r.retired.kept > 0 {
17990×
        format!(
1800
            "{} retired less than an hour ago kept for readers",
18010×
            plural(r.retired.kept, "file")
1802
        )
1803
    } else {
18040×
        String::new()
1805
    };
18060×
    if r.retired.packs + r.retired.loose > 0 {
18070×
        println!(
1808
            "Deleted {} and {} retired by earlier repacks{}.",
18090×
            plural(r.retired.packs, "pack"),
18100×
            plural(r.retired.loose, "loose object"),
18110×
            if kept.is_empty() {
18120×
                String::new()
1813
            } else {
18140×
                format!("; {kept}")
1815
            }
1816
        );
18170×
    } else if !kept.is_empty() {
18180×
        println!("{kept}.");
18190×
    }
18200×
    Ok(0)
18210×
}
1822
1823
/// `oxy gc --remote NAME`: fold a store remote's bundles into one.
18242×
pub fn gc_remote(name: &str, now: bool) -> Result<i32> {
18252×
    let repo = open()?;
18262×
    let sp = ui::spinner(&format!("Folding {name}'s bundles…"));
18272×
    let r = repo.gc_remote(name, now)?;
18281×
    sp.clear();
18291×
    if r.merged > 0 {
18301×
        println!(
18311×
            "{} {} into one of {} bytes ({})",
18321×
            ui::done("Folded"),
18331×
            plural(r.merged, "bundle"),
18341×
            r.bundle_bytes,
18351×
            plural(r.changes, "change")
18361×
        );
18371×
    } else {
18380×
        println!(
18390×
            "{} {}",
18400×
            ui::note(),
18410×
            ui::dim("nothing to fold: one bundle holds everything")
18420×
        );
18430×
    }
18441×
    println!(
1845
        "  {} {}",
18461×
        ui::note(),
18471×
        ui::dim(format!(
1848
            "removed {}{}",
18491×
            plural(r.deleted, "superseded bundle"),
18501×
            if r.deferred > 0 {
18510×
                format!(
1852
                    "; {} kept for readers that may still fetch them (use --now)",
18530×
                    plural(r.deferred, "bundle")
1854
                )
1855
            } else {
18561×
                String::new()
1857
            }
1858
        ))
1859
    );
18601×
    Ok(0)
18612×
}
1862
1863
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
18640×
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1865
    use oxy_core::repo::Health;
18660×
    let repo = open()?;
18670×
    let sp = ui::spinner(if offline {
18680×
        "Checking…"
1869
    } else {
18700×
        "Checking, and contacting remotes…"
1871
    });
18720×
    let r = repo.doctor(!offline);
18730×
    sp.clear();
18740×
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
18750×
    let word = |h: Health| match h {
18760×
        Health::Ok => "ok",
18770×
        Health::Warn => "warning",
18780×
        Health::Fail => "fail",
18790×
    };
18800×
    if as_json {
18810×
        let checks: Vec<String> = r
18820×
            .checks
18830×
            .iter()
18840×
            .map(|c| {
18850×
                json::obj([
18860×
                    ("area", json::s(&c.area)),
18870×
                    ("health", json::s(word(c.health))),
18880×
                    ("message", json::s(&c.message)),
18890×
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
18900×
                ])
18910×
            })
18920×
            .collect();
18930×
        println!(
1894
            "{}",
18950×
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1896
        );
18970×
        return Ok(code);
18980×
    }
18990×
    let mut last = "";
19000×
    for c in &r.checks {
19010×
        if c.area != last {
19020×
            println!("{}", ui::section(&c.area));
19030×
            last = &c.area;
19040×
        }
19050×
        let mark = match c.health {
19060×
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
19070×
            Health::Warn => ui::caution(),
19080×
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1909
        };
19100×
        println!("  {mark} {}", c.message);
19110×
        if let Some(h) = &c.hint {
19120×
            println!("    {} {}", ui::dim("→"), ui::dim(h));
19130×
        }
1914
    }
19150×
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
19160×
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
19170×
    if fails + warns == 0 {
19180×
        println!("{}", ui::done("Everything looks right."));
19190×
    } else {
19200×
        println!(
1921
            "{} {}, {}.",
19220×
            if fails > 0 {
19230×
                ui::err(ui::glyph("✖", "x"))
1924
            } else {
19250×
                ui::caution()
1926
            },
19270×
            plural(fails, "problem"),
19280×
            plural(warns, "warning")
1929
        );
1930
    }
19310×
    Ok(code)
19320×
}
1933
1934
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
19350×
pub fn fsck(as_json: bool) -> Result<i32> {
1936
    use oxy_core::repo::Severity;
19370×
    let repo = open()?;
19380×
    let sp = ui::spinner("Checking every object…");
19390×
    let r = repo.fsck()?;
19400×
    sp.clear();
19410×
    let code = if r.errors() > 0 { 1 } else { 0 };
19420×
    if as_json {
19430×
        let problems: Vec<String> = r
19440×
            .problems
19450×
            .iter()
19460×
            .map(|p| {
19470×
                json::obj([
1948
                    (
1949
                        "severity",
19500×
                        json::s(match p.severity {
19510×
                            Severity::Error => "error",
19520×
                            Severity::Warning => "warning",
1953
                        }),
1954
                    ),
1955
                    (
19560×
                        "object",
19570×
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1958
                    ),
19590×
                    ("what", json::s(&p.what)),
1960
                ])
19610×
            })
19620×
            .collect();
19630×
        println!(
1964
            "{}",
19650×
            json::obj([
19660×
                ("ok", json::b(code == 0)),
19670×
                ("objects", json::n(r.objects)),
19680×
                ("ops", json::n(r.ops)),
19690×
                ("changes", json::n(r.changes)),
19700×
                ("signed", json::n(r.signed)),
19710×
                ("unsigned", json::n(r.unsigned)),
19720×
                ("checkpoints", json::n(r.checkpoints)),
19730×
                ("attestations", json::n(r.attestations)),
19740×
                ("errors", json::n(r.errors())),
19750×
                ("warnings", json::n(r.warnings())),
19760×
                ("problems", json::arr(problems)),
19770×
            ])
1978
        );
19790×
        return Ok(code);
19800×
    }
19810×
    println!(
1982
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
19830×
        plural(r.objects, "object"),
19840×
        plural(r.ops, "operation"),
19850×
        plural(r.changes, "change"),
1986
        r.signed,
1987
        r.unsigned,
19880×
        plural(r.checkpoints, "checkpoint"),
19890×
        plural(r.attestations, "attestation"),
1990
    );
19910×
    for p in &r.problems {
19920×
        let obj = p
19930×
            .object
19940×
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
19950×
            .unwrap_or_default();
19960×
        match p.severity {
19970×
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
19980×
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1999
        }
2000
    }
20010×
    if r.problems.is_empty() {
20020×
        println!("{}", ui::done("No problems found."));
20030×
    } else if code == 0 {
20040×
        println!(
20050×
            "{}",
20060×
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
20070×
        );
20080×
    } else {
20090×
        println!(
20100×
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
20110×
            ui::err(ui::glyph("✖", "x")),
20120×
            plural(r.errors(), "error"),
20130×
            plural(r.warnings(), "warning")
20140×
        );
20150×
    }
20160×
    Ok(code)
20170×
}
2018
2019
/// The head the working copy sits on, for commands that default to it. With
2020
/// several heads beneath the working copy, the most recently made one is
2021
/// chosen and announced.
20220×
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
20230×
    let snap = repo.snapshot_status("oxy")?;
20240×
    let base = snap.base.maximal(&snap.wc.deps);
20250×
    match base.as_slice() {
20260×
        [] => anyhow::bail!("the working copy sits on no change yet"),
20270×
        [h] => Ok(*h),
20280×
        many => {
20290×
            let latest = many
20300×
                .iter()
20310×
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
20320×
                .copied()
20330×
                .unwrap();
20340×
            let c = repo.store().get_change(&latest)?;
20350×
            println!(
2036
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
20370×
                short_id(&c),
20380×
                latest.short(12),
20390×
                many.len()
2040
            );
20410×
            Ok(latest)
2042
        }
2043
    }
20440×
}
2045
2046
/// `oxy describe` without -m: the working copy's name for a build.
20474×
pub fn describe_name(as_json: bool) -> Result<i32> {
20484×
    let repo = open()?;
20494×
    let d = repo.describe_working_copy()?;
20504×
    if as_json {
20513×
        println!(
2052
            "{}",
20533×
            json::obj([
20543×
                ("describe", json::s(&d.line())),
20553×
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
20563×
                ("distance", json::n(d.distance)),
20573×
                ("bookmark", json::s(&d.bookmark)),
20583×
                ("change", json::s(&d.change.to_hex())),
20593×
                ("hash", json::s(&d.hash.to_hex())),
20603×
                ("dirty", json::b(d.dirty)),
2061
            ])
2062
        );
20631×
    } else {
20641×
        println!("{}", d.line());
20651×
    }
20664×
    Ok(0)
20674×
}
2068
20690×
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
20700×
    let repo = open()?;
20710×
    let h = match change {
20720×
        Some(c) => repo.resolve_change(c)?,
20730×
        None => current_head(&repo)?,
2074
    };
20750×
    let new = repo.describe(&h, message)?;
20760×
    let c = repo.store().get_change_meta(&new)?;
20770×
    println!(
2078
        "{} {} {}  {}",
20790×
        ui::done("Described"),
20800×
        ui::id(c.change_id.short(8)),
20810×
        ui::hash(format!("#{}", new.short(12))),
20820×
        ui::subject(subject_of(message))
2083
    );
20840×
    Ok(0)
20850×
}
2086
20870×
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
20880×
    let repo = open()?;
20890×
    let before = repo.view()?;
20900×
    let new = match into {
20910×
        Some(spec) => {
20920×
            let target = repo.resolve_change(spec)?;
20930×
            repo.amend_into(&target, message)?
2094
        }
20950×
        None => repo.amend(message)?,
2096
    };
20970×
    let c = repo.store().get_change_meta(&new)?;
20980×
    println!(
2099
        "{} {} {}  {}",
21000×
        ui::done("Amended"),
21010×
        ui::id(c.change_id.short(8)),
21020×
        ui::hash(format!("#{}", new.short(12))),
21030×
        ui::subject(subject_of(&c.message))
2104
    );
2105
    // Rewriting what a remote already has means the next push replaces it
2106
    // there (oxygen#99): say so now, not when the push is refused.
21070×
    let bookmark = repo.config.bookmark.clone();
21080×
    let (had, has) = (
21090×
        repo.heads_of(&before, &bookmark)?,
21100×
        repo.heads_of(&repo.view()?, &bookmark)?,
2111
    );
21120×
    for (remote, bookmarks) in &before.remotes {
21130×
        let Some(st) = bookmarks.get(&bookmark) else {
21140×
            continue;
2115
        };
21160×
        let theirs = repo.store().get_state(st)?.heads;
21170×
        if theirs.iter().any(|h| had.contains(h) && !has.contains(h)) {
21180×
            println!(
21190×
                "  {} {}",
21200×
                ui::caution(),
21210×
                ui::warn(format!(
21220×
                    "{remote}/{bookmark} has the change as it was: the next push of {bookmark} needs --force to replace it"
21230×
                ))
21240×
            );
21250×
        }
2126
    }
21270×
    where_now(&repo);
21280×
    Ok(0)
21290×
}
2130
21310×
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
21320×
    let repo = open()?;
21330×
    let Some(r) = revset else {
21340×
        let h = repo.resolve_change(change.unwrap_or_default())?;
21350×
        abandon_one(&repo, h)?;
21360×
        where_now(&repo);
21370×
        return Ok(0);
2138
    };
2139
    // A revset: say what it selects, refuse an empty set, ask above a few.
21400×
    let selected = repo.revset(r)?;
21410×
    let wc = repo.working_copy().ok().map(|(h, _)| h);
21420×
    let hashes: Vec<ChangeHash> = selected
21430×
        .hashes
21440×
        .iter()
21450×
        .copied()
21460×
        .filter(|h| Some(*h) != wc)
21470×
        .collect();
21480×
    if hashes.is_empty() {
21490×
        anyhow::bail!("{r:?} selects no change to abandon");
21500×
    }
21510×
    println!(
2152
        "{} {} selects {}:",
21530×
        ui::section("abandon"),
21540×
        ui::id(r),
21550×
        plural(hashes.len(), "change")
2156
    );
21570×
    for h in &hashes {
21580×
        if let Some(m) = selected.metas.get(h) {
21590×
            println!(
21600×
                "  {} {}  {}",
21610×
                ui::id(m.change_id.short(8)),
21620×
                ui::hash(format!("#{}", h.short(12))),
21630×
                subject_of(&m.message)
21640×
            );
21650×
        }
2166
    }
2167
    const ASK_ABOVE: usize = 5;
21680×
    if hashes.len() > ASK_ABOVE && !yes {
21690×
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
21700×
    }
2171
    // Newest first: abandoning a change rewrites what depends on it, so a
2172
    // later member is found again by its ChangeId.
21730×
    let mut done = 0;
21740×
    for h in &hashes {
21750×
        let Some(m) = selected.metas.get(h) else {
21760×
            continue;
2177
        };
21780×
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
21790×
            Ok(h) => h,
21800×
            Err(_) => continue,
2181
        };
21820×
        abandon_one(&repo, now)?;
21830×
        done += 1;
2184
    }
21850×
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
21860×
    where_now(&repo);
21870×
    Ok(0)
21880×
}
2189
21900×
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
21910×
    let c = repo.store().get_change_meta(&h)?;
21920×
    let notes = repo.abandon(&h)?;
21930×
    println!(
2194
        "{} {} {}  {}",
21950×
        ui::done("Abandoned"),
21960×
        ui::id(c.change_id.short(8)),
21970×
        ui::hash(format!("#{}", h.short(12))),
21980×
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
2199
    );
22000×
    for n in notes {
22010×
        println!("  {} {n}", ui::note());
22020×
    }
22030×
    Ok(())
22040×
}
2205
22060×
pub fn checkpoint() -> Result<i32> {
22070×
    let repo = open()?;
22080×
    let sp = ui::spinner("Writing checkpoint…");
22090×
    let (r, changes, bytes) = repo.checkpoint()?;
22100×
    sp.done(&format!(
22110×
        "{} {} of {} ({} bytes) for {}",
22120×
        ui::done("Checkpoint"),
22130×
        ui::hash(format!("#{}", r.short(12))),
22140×
        plural(changes, "change"),
22150×
        bytes,
22160×
        ui::id(&repo.config.bookmark)
22170×
    ));
22180×
    Ok(0)
22190×
}
2220
2221
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
22220×
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
22230×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
22240×
        return Ok(1);
2225
    };
22260×
    let info = repo.quick_status()?;
22270×
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
22280×
        oxy_core::repo::GLYPH_PROMPT_FORMAT
2229
    } else {
22300×
        format
2231
    };
22320×
    let line = match color {
22330×
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
22340×
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
22350×
        Some(_) => info.format_colored(fmt, ("", "")),
22360×
        None => info.format(fmt),
2237
    };
22380×
    println!("{line}");
22390×
    Ok(0)
22400×
}
2241
22420×
pub fn sparse(paths: &[String]) -> Result<i32> {
22430×
    let mut repo = open()?;
22440×
    if paths.is_empty() {
22450×
        if repo.config.sparse_paths.is_empty() {
22460×
            println!("No sparse filter: the whole tree is materialized.");
22470×
        } else {
22480×
            println!("{}", ui::heading("Sparse filter"));
22490×
            for p in &repo.config.sparse_paths {
22500×
                println!("  {}", ui::path(p));
22510×
            }
2252
        }
22530×
        return Ok(0);
22540×
    }
22550×
    let snap = repo.snapshot("oxy sparse")?;
22560×
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
22570×
        anyhow::bail!(
2258
            "the working copy has changes; commit them before changing the sparse filter"
2259
        );
22600×
    }
22610×
    repo.config.set("filter.paths", &paths.join(","))?;
22620×
    repo.save_config()?;
22630×
    let heads = repo.bookmark_heads()?;
22640×
    let sp = ui::spinner("Re-checking out with the new filter…");
22650×
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
22660×
    sp.done(&format!(
22670×
        "{} {}: {} written, {} removed",
22680×
        ui::done("Sparse filter set to"),
22690×
        ui::path(paths.join(",")),
22700×
        plural(r.written, "file"),
22710×
        r.removed
22720×
    ));
22730×
    Ok(0)
22740×
}
2275
22762×
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
22772×
    let repo = open()?;
22782×
    repo.snapshot_status("oxy tag")?;
22792×
    let heads = if changes.is_empty() {
22802×
        repo.bookmark_heads()?
2281
    } else {
22820×
        let mut heads = Vec::new();
22830×
        for c in changes {
22840×
            heads.extend(repo.resolve_heads(c)?);
2285
        }
22860×
        heads
2287
    };
22882×
    let t = repo.tag_create(name, &heads, message)?;
22892×
    println!(
2290
        "{} {} {} {} ({}){}",
22912×
        ui::done("Tagged"),
22922×
        ui::bookmark(&t.name),
22932×
        ui::dim(ui::glyph("→", "->")),
22942×
        ui::hash(format!("#{}", t.state.short(12))),
22952×
        plural(t.heads.len(), "head"),
22962×
        t.signer
22972×
            .map(|s| format!(", signed by {s}"))
22982×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2299
    );
23002×
    Ok(0)
23012×
}
2302
23031×
pub fn tag_list(as_json: bool) -> Result<i32> {
23041×
    let repo = open()?;
23051×
    let tags = repo.tags()?;
23061×
    if as_json {
23071×
        println!(
2308
            "{}",
23091×
            json::arr(tags.iter().map(|t| {
23101×
                json::obj([
23111×
                    ("name", json::s(&t.name)),
23121×
                    ("state", json::s(&t.state.to_hex())),
23131×
                    ("heads", json::hashes(&t.heads)),
23141×
                    ("message", json::s(&t.message)),
2315
                    (
23161×
                        "signer",
23171×
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2318
                    ),
2319
                ])
23201×
            }))
2321
        );
23221×
        return Ok(0);
23230×
    }
23240×
    if tags.is_empty() {
23250×
        println!("{}", ui::dim("No tags."));
23260×
    }
23270×
    for t in tags {
23280×
        println!(
2329
            "{} {} {}{}{}{}",
23300×
            ui::ok(ui::glyph("⚑", "#")),
23310×
            ui::bookmark(&t.name),
2332
            // The heads, as `oxy log` shows changes, not the state hash.
23330×
            ui::hash(
23340×
                t.heads
23350×
                    .iter()
23360×
                    .map(|h| format!("#{}", h.short(12)))
23370×
                    .collect::<Vec<_>>()
23380×
                    .join(" ")
2339
            ),
23400×
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
23410×
            if t.message.is_empty() {
23420×
                String::new()
2343
            } else {
23440×
                format!("  {}", ui::subject(subject_of(&t.message)))
2345
            },
23460×
            t.signer
23470×
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
23480×
                .unwrap_or_default()
2349
        );
2350
    }
23510×
    Ok(0)
23521×
}
2353
2354
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2355
/// and workspace add take as "be on this bookmark" (oxygen#60).
23560×
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
23570×
    Ok(repo.view()?.bookmarks.contains_key(name)
23580×
        || repo
23590×
            .remote_only_bookmarks()?
23600×
            .iter()
23610×
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
23620×
}
2363
23640×
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
23650×
    let repo = open()?;
2366
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2367
    // this workspace's bookmark with that one's files.
23680×
    if let [name] = changes {
23690×
        if names_bookmark(&repo, name)? {
23700×
            let (local, _) = repo.local_bookmark_for(name)?;
23710×
            let heads = repo.resolve_heads(&local)?;
23720×
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
23730×
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
23740×
            sp.done(&format!(
23750×
                "{} {} (workspace {}) on {}",
23760×
                ui::done("Workspace created at"),
23770×
                ui::path(ws.root().display()),
23780×
                ui::id(ws.workspace().short(8)),
23790×
                ui::bookmark(&local)
23800×
            ));
23810×
            return Ok(0);
23820×
        }
23830×
    }
23840×
    let heads = if changes.is_empty() {
23850×
        None
2386
    } else {
23870×
        let mut heads = Vec::new();
23880×
        for c in changes {
23890×
            heads.extend(repo.resolve_heads(c)?);
2390
        }
23910×
        Some(heads)
2392
    };
23930×
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
23940×
    let ws = repo.workspace_add(path, heads.as_deref())?;
23950×
    sp.done(&format!(
23960×
        "{} {} (workspace {})",
23970×
        ui::done("Workspace created at"),
23980×
        ui::path(ws.root().display()),
23990×
        ui::id(ws.workspace().short(8))
24000×
    ));
24010×
    Ok(0)
24020×
}
2403
24041×
pub fn workspace_list(as_json: bool) -> Result<i32> {
24051×
    let repo = open()?;
24061×
    if as_json {
24071×
        println!(
2408
            "{}",
24091×
            json::arr(repo.workspaces()?.iter().map(|w| {
24101×
                json::obj([
24111×
                    ("id", json::s(&w.id.to_hex())),
24121×
                    ("path", json::s(&w.path.to_string_lossy())),
24131×
                    ("current", json::b(w.current)),
2414
                    (
24151×
                        "working_copy",
24161×
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2417
                    ),
2418
                ])
24191×
            }))
2420
        );
24211×
        return Ok(0);
24220×
    }
24230×
    for w in repo.workspaces()? {
24240×
        println!(
2425
            "{} {} {}{}",
24260×
            if w.current {
24270×
                ui::ok(ui::glyph("●", "*"))
2428
            } else {
24290×
                ui::dim(ui::glyph("○", "o"))
2430
            },
24310×
            ui::id(w.id.short(8)),
24320×
            ui::path(w.path.display()),
24330×
            w.working_copy
24340×
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
24350×
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2436
        );
2437
    }
24380×
    Ok(0)
24391×
}
2440
24410×
pub fn workspace_forget(spec: &str) -> Result<i32> {
24420×
    let repo = open()?;
24430×
    let all = repo.workspaces()?;
24440×
    let target = std::fs::canonicalize(spec).ok();
24450×
    let matches: Vec<_> = all
24460×
        .iter()
24470×
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
24480×
        .collect();
24490×
    let w = match matches.as_slice() {
24500×
        [w] => *w,
24510×
        [] => anyhow::bail!("no workspace matches {spec:?}"),
24520×
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2453
    };
24540×
    repo.workspace_forget(&w.id)?;
24550×
    println!(
2456
        "{} workspace {} at {}; its files were left in place.",
24570×
        ui::done("Forgot"),
24580×
        ui::id(w.id.short(8)),
24590×
        ui::path(w.path.display())
2460
    );
24610×
    Ok(0)
24620×
}
2463
24640×
pub fn lock(path: &str) -> Result<i32> {
24650×
    let repo = open()?;
24660×
    repo.lock_path(path)?;
24670×
    println!(
2468
        "{} {} {}",
24690×
        ui::done("Locked"),
24700×
        ui::path(path),
24710×
        ui::dim("(advisory, local)")
2472
    );
24730×
    Ok(0)
24740×
}
2475
24760×
pub fn unlock(path: &str) -> Result<i32> {
24770×
    let repo = open()?;
24780×
    repo.unlock_path(path)?;
24790×
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
24800×
    Ok(0)
24810×
}
2482
24830×
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
24840×
    let repo = open()?;
24850×
    let h = repo.resolve_change(change)?;
24860×
    let (h1, h2) = repo.split(&h, paths)?;
24870×
    let c1 = repo.store().get_change_meta(&h1)?;
24880×
    let c2 = repo.store().get_change_meta(&h2)?;
24890×
    println!(
2490
        "{} into {} {} and {} {}",
24910×
        ui::done("Split"),
24920×
        ui::id(c1.change_id.short(8)),
24930×
        ui::hash(format!("#{}", h1.short(12))),
24940×
        ui::id(c2.change_id.short(8)),
24950×
        ui::hash(format!("#{}", h2.short(12)))
2496
    );
24970×
    Ok(0)
24980×
}
2499
25006×
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
25016×
    let mut heads = Vec::new();
25026×
    for c in changes {
25036×
        heads.extend(repo.resolve_heads(c)?);
2504
    }
25056×
    Ok(heads)
25066×
}
2507
25086×
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
25096×
    let repo = open()?;
25106×
    repo.snapshot_status("oxy bookmark create")?;
25116×
    let heads = if changes.is_empty() {
25123×
        None
2513
    } else {
25143×
        let named = heads_from(&repo, changes)?;
25153×
        let (_, wc) = repo.working_copy()?;
25163×
        let gap = repo.state_gap(&wc.deps, &named)?;
25173×
        if upto {
25181×
            Some(gap.upto)
25192×
        } else if only || gap.earlier.is_empty() {
25201×
            Some(named)
2521
        } else {
25221×
            anyhow::bail!(
2523
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2524
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2525
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2526
                 or --only for just {0} and what it depends on.",
25271×
                changes.join(" "),
25281×
                plural(gap.earlier.len(), "change"),
25291×
                listed_changes(&repo, &gap.earlier)
2530
            );
2531
        }
2532
    };
25335×
    let heads = repo.bookmark_create(name, heads.as_deref())?;
25345×
    println!(
2535
        "{} bookmark {} {} {}",
25365×
        ui::done("Created"),
25375×
        ui::bookmark(name),
25385×
        ui::dim(ui::glyph("→", "->")),
25395×
        ui::dim(plural(heads.len(), "head"))
2540
    );
25415×
    println!(
2542
        "  {} {}",
25435×
        ui::note(),
25445×
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2545
    );
25465×
    Ok(0)
25476×
}
2548
2549
/// Up to five changes, newest last, as `  #hash subject` lines.
25502×
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
25512×
    let shown = changes.len().min(5);
25522×
    let mut lines: Vec<String> = changes[changes.len() - shown..]
25532×
        .iter()
25542×
        .map(|h| {
25552×
            let subject = repo
25562×
                .store()
25572×
                .get_change(h)
25582×
                .map(|c| subject_of(&c.message).to_string())
25592×
                .unwrap_or_default();
25602×
            format!("  #{} {subject}", h.short(12))
25612×
        })
25622×
        .collect();
25632×
    if changes.len() > shown {
25640×
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
25652×
    }
25662×
    lines.join("\n")
25672×
}
2568
25693×
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
25703×
    let repo = open()?;
25713×
    repo.snapshot_status("oxy bookmark set")?;
25723×
    let named = heads_from(&repo, changes)?;
2573
    // What the bookmark holds now and the new heads would leave out.
25743×
    let current = repo
25753×
        .bookmarks()?
25763×
        .into_iter()
25776×
        .find(|b| b.name == name)
25783×
        .map(|b| b.heads)
25793×
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
25803×
    let gap = repo.state_gap(&current, &named)?;
2581
    // A fast-forward: the new heads hold the bookmark's newest head, so
2582
    // what they leave out is older work nothing since has built on, such
2583
    // as an early change no later one depends on (oxygen#78). Keep it, as
2584
    // --upto does, and say so.
25853×
    let newest = current
25863×
        .iter()
25878×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m.hlc, *h)))
25883×
        .max()
25893×
        .map(|(_, h)| h);
2590
    // Ahead, too: a head the bookmark holds already (it would only drop
2591
    // the others) is not a move forward.
25923×
    let ahead = repo
25933×
        .load_state_history(&current)
25943×
        .is_ok_and(|st| named.iter().any(|h| !st.contains(h)));
25953×
    let forward = !only
25963×
        && ahead
25971×
        && !gap.earlier.is_empty()
25981×
        && newest.is_some_and(|n| {
25991×
            repo.load_state_history(&named)
26001×
                .is_ok_and(|st| st.contains(&n))
26011×
        });
26023×
    let heads = if upto {
26031×
        gap.upto
26042×
    } else if forward {
26051×
        println!(
2606
            "  {} {}",
26071×
            ui::note(),
26081×
            ui::dim(format!(
2609
                "{} builds on {name}'s newest head; keeping {} it holds that {0} does not depend on",
26101×
                changes.join(" "),
26111×
                plural(gap.earlier.len(), "change")
2612
            ))
2613
        );
26141×
        gap.upto
26151×
    } else if only || gap.earlier.is_empty() {
26160×
        named
2617
    } else {
26181×
        anyhow::bail!(
2619
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2620
             A state is its heads and what they depend on, not everything recorded before them.\n\
2621
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2622
             or --only for just {0} and what it depends on.",
26231×
            changes.join(" "),
26241×
            plural(gap.earlier.len(), "change"),
26251×
            listed_changes(&repo, &gap.earlier)
2626
        );
2627
    };
26282×
    let heads = repo.bookmark_set(name, &heads)?;
26292×
    println!(
2630
        "{} bookmark {} {} {}",
26312×
        ui::done("Moved"),
26322×
        ui::bookmark(name),
26332×
        ui::dim(ui::glyph("→", "->")),
26342×
        ui::dim(plural(heads.len(), "head"))
2635
    );
26362×
    Ok(0)
26373×
}
2638
26390×
pub fn bookmark_delete(name: &str) -> Result<i32> {
26400×
    let repo = open()?;
26410×
    repo.bookmark_delete(name)?;
26420×
    println!(
2643
        "{} bookmark {} {}",
26440×
        ui::done("Deleted"),
26450×
        ui::bookmark(name),
26460×
        ui::dim("(its changes stay until unreachable)")
2647
    );
26480×
    Ok(0)
26490×
}
2650
2651
/// Heads with their metadata, newest first.
26520×
fn heads_newest_first(
26530×
    repo: &Repo,
26540×
    heads: &[oxy_core::hash::ChangeHash],
26550×
) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> {
26560×
    let mut out: Vec<_> = heads
26570×
        .iter()
26580×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m)))
26590×
        .collect();
26600×
    out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc));
26610×
    out
26620×
}
2663
2664
/// One head as a line: id, hash, author, when, subject.
26650×
fn print_head(
26660×
    repo: &Repo,
26670×
    indent: &str,
26680×
    h: &oxy_core::hash::ChangeHash,
26690×
    m: &oxy_core::state::ChangeMeta,
26700×
) {
26710×
    println!(
2672
        "{indent}{} {} {}{}{}{}{}",
26730×
        ui::id(m.change_id.short(8)),
26740×
        ui::dim(format!("#{}", &h.to_hex()[..8])),
26750×
        author_name(repo, m),
26760×
        ui::sep(),
26770×
        ui::dim(ui::ago(m.hlc.wall_ms)),
26780×
        ui::sep(),
26790×
        ui::subject(subject_of(&m.message))
2680
    );
26810×
}
2682
26830×
pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result<i32> {
26840×
    let repo = open()?;
26850×
    let name = name.unwrap_or(&repo.config.bookmark).to_string();
26860×
    let view = repo.view()?;
26870×
    let st = match view.bookmarks.get(&name) {
26880×
        Some(st) => *st,
26890×
        None => match oxy_core::repo::remote_bookmark(&view, &name) {
26900×
            Some((_, _, st)) => st,
26910×
            None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"),
2692
        },
2693
    };
26940×
    let heads = repo.store().get_state(&st)?.heads;
26950×
    let shown = heads_newest_first(&repo, &heads);
26960×
    if as_json {
26970×
        println!(
2698
            "{}",
26990×
            json::obj([
27000×
                ("name", json::s(&name)),
27010×
                ("current", json::b(name == repo.config.bookmark)),
2702
                (
27030×
                    "heads",
27040×
                    json::arr(shown.iter().map(|(h, m)| {
27050×
                        json::obj([
27060×
                            ("hash", json::s(&h.to_hex())),
27070×
                            ("id", json::s(&m.change_id.to_string())),
27080×
                            ("author", json::s(&author_name(&repo, m))),
27090×
                            ("time_ms", json::n(m.hlc.wall_ms)),
27100×
                            ("subject", json::s(subject_of(&m.message))),
27110×
                        ])
27120×
                    }))
2713
                ),
2714
            ])
2715
        );
27160×
        return Ok(0);
27170×
    }
27180×
    println!(
2719
        "{} {}{}{}",
27200×
        ui::ok(ui::glyph("●", "*")),
27210×
        ui::bookmark(&name),
27220×
        ui::sep(),
27230×
        ui::dim(plural(heads.len(), "head"))
2724
    );
27250×
    for (h, m) in &shown {
27260×
        print_head(&repo, "  ", h, m);
27270×
    }
27280×
    if heads.len() > 1 {
27290×
        println!(
27300×
            "  {}",
27310×
            ui::dim("None depends on another: the bookmark is all of them and their dependencies.")
27320×
        );
27330×
    }
27340×
    Ok(0)
27350×
}
2736
27375×
pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result<i32> {
27385×
    let repo = open()?;
27395×
    let remote_only = repo.remote_only_bookmarks()?;
27405×
    if as_json {
27415×
        let mut items: Vec<String> = repo
27425×
            .bookmarks()?
27435×
            .into_iter()
274413×
            .map(|b| {
274513×
                json::obj([
274613×
                    ("name", json::s(&b.name)),
274713×
                    ("heads", json::hashes(&b.heads)),
274813×
                    ("current", json::b(b.current)),
274913×
                    ("ahead", json::opt(b.ahead, json::n)),
275013×
                    ("behind", json::opt(b.behind, json::n)),
275113×
                    ("remote", json::opt(b.remote.as_deref(), json::s)),
275213×
                ])
275313×
            })
27545×
            .collect();
27555×
        if all {
27560×
            items.extend(remote_only.iter().map(|b| {
27570×
                json::obj([
27580×
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
27590×
                    ("heads", json::hashes(&b.heads)),
27600×
                    ("current", json::b(false)),
27610×
                    ("ahead", "null".into()),
27620×
                    ("behind", "null".into()),
27630×
                    ("remote", json::s(&b.remote)),
27640×
                ])
27650×
            }));
27665×
        }
27675×
        println!("{}", json::arr(items));
27685×
        return Ok(0);
27690×
    }
27700×
    for b in repo.bookmarks()? {
27710×
        let mark = if b.current {
27720×
            ui::ok(ui::glyph("●", "*"))
2773
        } else {
27740×
            ui::dim(ui::glyph("○", "o"))
2775
        };
27760×
        let mut tail = String::new();
27770×
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
27780×
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
27790×
        }
27800×
        if let Some(n) = b.behind.filter(|n| *n > 0) {
27810×
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
27820×
        }
2783
        // Which remote, when there is a choice (oxygen#83).
27840×
        if !tail.is_empty() && repo.config.remotes.len() > 1 {
27850×
            if let Some(r) = &b.remote {
27860×
                tail += &ui::dim(format!(" {r}"));
27870×
            }
27880×
        }
27890×
        let shown = heads_newest_first(&repo, &b.heads);
2790
        // The newest head's subject, so a busy bookmark shows its latest work.
27910×
        let head = match shown.first() {
27920×
            Some(_) if verbose => String::new(),
27930×
            Some((_, m)) if b.heads.len() > 1 => format!(
2794
                "{} {}",
27950×
                ui::dim("newest"),
27960×
                ui::subject(subject_of(&m.message))
2797
            ),
27980×
            Some((_, m)) => ui::subject(subject_of(&m.message)),
27990×
            None => ui::dim("(empty)"),
2800
        };
28010×
        let head = if head.is_empty() {
28020×
            head
2803
        } else {
28040×
            format!("  {head}")
2805
        };
28060×
        println!(
2807
            "{mark} {}{}{}{tail}{head}",
28080×
            ui::bookmark(&b.name),
28090×
            ui::sep(),
28100×
            ui::dim(plural(b.heads.len(), "head"))
2811
        );
28120×
        if verbose {
28130×
            for (h, m) in &shown {
28140×
                print_head(&repo, "    ", h, m);
28150×
            }
28160×
        }
2817
    }
28180×
    if remote_only.is_empty() {
28190×
        return Ok(0);
28200×
    }
28210×
    if !all {
28220×
        println!(
2823
            "{}",
28240×
            ui::dim(format!(
2825
                "  and {} only on a remote: oxy bookmark list --all",
28260×
                plural(remote_only.len(), "bookmark")
2827
            ))
2828
        );
28290×
        return Ok(0);
28300×
    }
28310×
    for b in &remote_only {
28320×
        println!(
28330×
            "{} {}{}{}",
28340×
            ui::dim(ui::glyph("◌", ".")),
28350×
            ui::dim(format!("{}/{}", b.remote, b.name)),
28360×
            ui::sep(),
28370×
            ui::dim(plural(b.heads.len(), "head"))
28380×
        );
28390×
    }
28400×
    println!(
2841
        "  {} {}",
28420×
        ui::note(),
28430×
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2844
    );
28450×
    Ok(0)
28465×
}
2847
28483×
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
28493×
    let mut repo = open()?;
28503×
    let from = repo.config.bookmark.clone();
28513×
    let (local, created_from) = repo.local_bookmark_for(name)?;
28523×
    if let Some(remote) = created_from {
28530×
        println!(
28540×
            "{} {} from {}",
28550×
            ui::done("Created"),
28560×
            ui::bookmark(&local),
28570×
            ui::dim(format!("{remote}/{local}"))
28580×
        );
28593×
    }
28603×
    let name = local.as_str();
2861
    // Only behind its remote: take the remote's state, so the switch does
2862
    // not check out a stale one (oxygen#74).
28633×
    if let Some(n) = repo.catch_up_bookmark(name)? {
28640×
        println!(
28650×
            "{} {} with {}: {} it lacked",
28660×
            ui::done("Caught up"),
28670×
            ui::bookmark(name),
28680×
            ui::dim(format!("{}/{name}", repo.default_remote())),
28690×
            plural(n, "change")
28700×
        );
28713×
    }
28723×
    let sp = ui::spinner(&format!("Switching to {name}…"));
28733×
    let (r, carried) = if carry {
28740×
        repo.bookmark_switch_carry(name)?
2875
    } else {
28763×
        (repo.bookmark_switch(name, discard)?, vec![])
2877
    };
28783×
    sp.done(&format!(
2879
        "{} to {}: {} written, {} removed{}",
28803×
        ui::done("Switched"),
28813×
        ui::bookmark(name),
28823×
        plural(r.written, "file"),
2883
        r.removed,
28843×
        if carried.is_empty() {
28853×
            String::new()
2886
        } else {
28870×
            format!("; carried {}", plural(carried.len(), "changed path"))
2888
        }
2889
    ));
28903×
    print_removed(&r);
28913×
    if r.conflicted {
28920×
        println!(
28930×
            "  {} {}",
28940×
            ui::caution(),
28950×
            ui::warn("this state has conflicts; see oxy status")
28960×
        );
28973×
    }
2898
    // Say when the new state leaves out work the old one had: a state is
2899
    // its heads and what they depend on, which can be far less than a Git
2900
    // user expects.
29013×
    if r.lacks > 0 {
29021×
        println!(
29031×
            "  {} {}",
29041×
            ui::note(),
29051×
            ui::dim(format!(
29061×
                "{name} lacks {} that {from} has",
29071×
                plural(r.lacks, "change")
29081×
            ))
29091×
        );
29102×
    }
29113×
    super::sync::subrepos_behind(&repo);
29123×
    where_now(&repo);
29133×
    Ok(0)
29143×
}
2915
29160×
pub fn merge(bookmark: &str) -> Result<i32> {
29170×
    let repo = open()?;
29180×
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
29190×
    let r = repo.merge(bookmark)?;
29200×
    if !r.changed {
29210×
        sp.done(&format!(
29220×
            "{} {}",
29230×
            ui::ok(ui::glyph("✔", "*")),
29240×
            ui::dim(format!(
29250×
                "{} already contains {bookmark}",
29260×
                repo.config.bookmark
29270×
            ))
29280×
        ));
29290×
        return Ok(0);
29300×
    }
29310×
    sp.done(&format!(
2932
        "{} {} into {}: now {}{}",
29330×
        ui::done("Merged"),
29340×
        ui::bookmark(bookmark),
29350×
        ui::bookmark(&repo.config.bookmark),
29360×
        plural(r.heads.len(), "head"),
29370×
        ui::dim(if r.checked_out {
29380×
            "; working copy updated"
2939
        } else {
29400×
            "; run oxy checkout to update the working copy"
2941
        })
2942
    ));
29430×
    let snap = repo.snapshot("oxy merge")?;
29440×
    if snap.base_snapshot.is_conflicted() {
29450×
        println!(
29460×
            "  {} {}",
29470×
            ui::caution(),
29480×
            ui::warn("the result has conflicts; see oxy status")
29490×
        );
29500×
    }
29510×
    where_now(&repo);
29520×
    Ok(0)
29530×
}
2954
29550×
pub fn squash(change: &str, into: &str) -> Result<i32> {
29560×
    let repo = open()?;
29570×
    let c = repo.resolve_change(change)?;
29580×
    let d = repo.resolve_change(into)?;
29590×
    let sp = ui::spinner("Squashing…");
29600×
    let h = repo.squash(&c, &d)?;
29610×
    let new = repo.store().get_change_meta(&h)?;
29620×
    sp.done(&format!(
29630×
        "{} into {} {}  {}",
29640×
        ui::done("Squashed"),
29650×
        ui::id(new.change_id.short(8)),
29660×
        ui::hash(format!("#{}", h.short(12))),
29670×
        ui::subject(subject_of(&new.message))
29680×
    ));
29690×
    Ok(0)
29700×
}
2971
29720×
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
29730×
    let repo = open()?;
29740×
    let c = repo.resolve_change(change)?;
29750×
    let mut heads = Vec::new();
29760×
    for o in onto {
29770×
        heads.extend(repo.resolve_heads(o)?);
2978
    }
29790×
    let sp = ui::spinner("Rebasing…");
29800×
    let h = match repo.rebase(&c, &heads) {
29810×
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
29820×
            let r = repo.rebase_into_working_copy(&c, &heads)?;
29830×
            sp.done(&format!(
29840×
                "{} {} into {}: now {}",
29850×
                ui::done("Merged"),
29860×
                onto.join(" "),
29870×
                ui::bookmark(&repo.config.bookmark),
29880×
                plural(r.heads.len(), "head"),
29890×
            ));
29900×
            if r.checked_out {
29910×
                println!(
29920×
                    "  {} {}",
29930×
                    ui::caution(),
29940×
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
29950×
                );
29960×
            } else {
29970×
                println!(
29980×
                    "  {} {}",
29990×
                    ui::caution(),
30000×
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
30010×
                );
30020×
            }
30030×
            where_now(&repo);
30040×
            return Ok(0);
3005
        }
30060×
        other => other?,
3007
    };
30080×
    let new = repo.store().get_change_meta(&h)?;
30090×
    sp.done(&format!(
30100×
        "{} {} {}  {}",
30110×
        ui::done("Rebased"),
30120×
        ui::id(new.change_id.short(8)),
30130×
        ui::hash(format!("#{}", h.short(12))),
30140×
        ui::dim(format!(
30150×
            "now depends on {}",
30160×
            plural(new.deps.len(), "change")
30170×
        ))
30180×
    ));
30190×
    where_now(&repo);
30200×
    Ok(0)
30210×
}
3022
3023
#[cfg(test)]
3024
mod tests {
3025
    use super::*;
3026
3027
    #[test]
30281×
    fn id_prefixes_agree_with_the_whole_list() {
3029
        // Ids that share long prefixes, and some that differ only in a
3030
        // half byte, from a fixed sequence.
30311×
        let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
30327999×
        let mut next = || {
30337999×
            x ^= x << 13;
30347999×
            x ^= x >> 7;
30357999×
            x ^= x << 17;
30367999×
            x
30377999×
        };
30381×
        let mut ids: Vec<[u8; 16]> = Vec::new();
30391×
        for _ in 0..2000 {
30402000×
            let mut id = [0u8; 16];
30412000×
            id[..8].copy_from_slice(&next().to_le_bytes());
30422000×
            id[8..].copy_from_slice(&next().to_le_bytes());
30432000×
            let share = (next() % 4) as usize;
30442000×
            if let Some(prev) = ids.last() {
30451999×
                id[..share].copy_from_slice(&prev[..share]);
30461999×
                if next() % 2 == 0 {
3047973×
                    id[share] = (prev[share] & 0xf0) | (id[share] & 0x0f);
30481026×
                }
30491×
            }
30502000×
            ids.push(id);
3051
        }
30524000×
        let hex = |id: &[u8; 16]| oxy_core::ids::ChangeId(*id).to_hex();
30531×
        let whole = unique_prefixes(ids.iter().map(hex));
30541×
        let some = id_prefixes(ids.clone(), ids.iter().copied());
30552000×
        for id in &ids {
30562000×
            assert_eq!(some[id], whole[&hex(id)], "{}", hex(id));
3057
        }
30581×
    }
3059
}