OXYGENHUB

Coverage / src/cli/workspace.rs 39.0%

927 of 2376 lines run, 90 of 331 functions · run #279 on switch-says · 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 => {
10590×
            let (wc, base, snapshot) = repo.working_copy_with_base()?;
10600×
            let text = {
10610×
                let _t = oxy_core::timing::phase("diff: render the change");
10620×
                render_change(&wc, &base, &snapshot)
1063
            };
10640×
            print!("{text}");
1065
            // The process ends here: freeing the base's tree and graphs
1066
            // one by one would only cost time (about 27 ms on Linux).
10670×
            std::mem::forget((wc, base, snapshot));
1068
        }
1069
    }
10700×
    Ok(0)
10711×
}
1072
10732×
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
10742×
    let repo = open()?;
10752×
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
10762×
    let bytes = match repo.file_at(path, heads.as_deref()) {
10772×
        Ok(b) => b,
1078
        // -r CHANGE reads that change's dependency closure, not the
1079
        // bookmark it is on: say so when the bookmark has the file
1080
        // (oxygen#76).
10810×
        Err(e) => match change {
10820×
            Some(c)
10830×
                if !repo.view()?.bookmarks.contains_key(c)
10840×
                    && repo.tag_heads(c)?.is_none()
10850×
                    && repo.file_at(path, None).is_ok() =>
1086
            {
10870×
                anyhow::bail!(
1088
                    "{path} is not in {c}'s dependency closure (the change and what it \
1089
                     depends on); it is on the bookmark: try -r {}, or --at-op OP for the \
1090
                     state at an operation",
1091
                    repo.config.bookmark
1092
                )
1093
            }
10940×
            _ => return Err(e.into()),
1095
        },
1096
    };
1097
    use std::io::Write as _;
10982×
    std::io::stdout().write_all(&bytes)?;
10992×
    Ok(0)
11002×
}
1101
11021×
pub fn root(as_json: bool) -> Result<i32> {
11031×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
11040×
        if as_json {
11050×
            println!("null");
11060×
        }
11070×
        return Ok(1);
1108
    };
11091×
    if as_json {
11101×
        println!(
11111×
            "{}",
11121×
            json::obj([
11131×
                ("root", json::s(&repo.root().to_string_lossy())),
11141×
                ("workspace", json::s(&repo.workspace().to_hex())),
11151×
                ("bookmark", json::s(&repo.config.bookmark))
11161×
            ])
11171×
        );
11181×
    } else {
11190×
        println!("{}", repo.root().display());
11200×
    }
11211×
    Ok(0)
11221×
}
1123
11241×
pub fn version(as_json: bool) -> Result<i32> {
11251×
    if as_json {
11261×
        println!(
11271×
            "{}",
11281×
            json::obj([
11291×
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
11301×
                // What was built: a release's or install's `oxy describe`,
11311×
                // a Flow build's heads, or "local build".
11321×
                ("build", json::s(env!("OXY_BUILD_ID"))),
11331×
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
11341×
                ("format", json::n(2))
11351×
            ])
11361×
        );
11371×
    } else {
11380×
        println!(
11390×
            "oxy {} (repository format 2, protocol {})",
11400×
            env!("OXY_VERSION_LONG"),
11410×
            oxy_core::protocol::PROTOCOL_VERSION
11420×
        );
11430×
    }
11441×
    Ok(0)
11451×
}
1146
11472×
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
11482×
    let repo = open()?;
11492×
    if paths.is_empty() && hunks.is_empty() {
11500×
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
11512×
    }
11522×
    let mut n = 0;
11532×
    if !hunks.is_empty() {
11541×
        n += repo.discard_hunks(hunks)?;
11551×
    }
11562×
    if !paths.is_empty() {
11571×
        n += repo.discard(paths)?;
11581×
    }
11592×
    println!(
1160
        "{} {} restored to the working copy's base",
11612×
        ui::done("Discarded"),
11622×
        plural(n, "path")
1163
    );
11642×
    Ok(0)
11652×
}
1166
11672×
pub fn hunks(as_json: bool) -> Result<i32> {
11682×
    let repo = open()?;
11692×
    let (_, hunks) = repo.hunks()?;
11702×
    if as_json {
11712×
        println!(
1172
            "{}",
11735×
            json::arr(hunks.iter().map(|h| json::obj([
11745×
                ("index", json::n(h.index)),
11755×
                ("path", json::s(&h.path)),
11765×
                ("text", json::s(&h.text))
11775×
            ])))
1178
        );
11792×
        return Ok(0);
11800×
    }
11810×
    if hunks.is_empty() {
11820×
        println!(
11830×
            "{}",
11840×
            ui::dim("No hunks: the working copy matches its base.")
11850×
        );
11860×
    }
11870×
    for h in &hunks {
11880×
        println!(
1189
            "{} {}",
11900×
            ui::section(format!("hunk {}", h.index)),
11910×
            ui::path(&h.path)
1192
        );
11930×
        for line in h.text.lines() {
11940×
            let styled = if line.starts_with('+') {
11950×
                ui::ok(line)
11960×
            } else if line.starts_with('-') {
11970×
                ui::err(line)
1198
            } else {
11990×
                ui::dim(line)
1200
            };
12010×
            println!("  {styled}");
1202
        }
1203
    }
12040×
    Ok(0)
12052×
}
1206
12072×
pub fn show(change: Option<&str>, revset: Option<&str>, as_json: bool) -> Result<i32> {
12082×
    let repo = open()?;
12092×
    repo.snapshot_status("oxy show")?;
12102×
    let Some(r) = revset else {
12112×
        let h = repo.resolve_change(change.unwrap_or("@"))?;
12122×
        return show_one(&repo, h, as_json, false);
1213
    };
1214
    // Several changes: a JSON array, or the changes one after another.
12150×
    let hashes = repo.revset(r)?.hashes;
12160×
    if as_json {
12170×
        print!("[");
12180×
        for (i, h) in hashes.iter().enumerate() {
12190×
            if i > 0 {
12200×
                print!(",");
12210×
            }
12220×
            show_one(&repo, *h, true, true)?;
1223
        }
12240×
        println!("]");
12250×
        return Ok(0);
12260×
    }
12270×
    if hashes.is_empty() {
12280×
        println!("{}", ui::dim(format!("No change matches {r:?}.")));
12290×
        return Ok(0);
12300×
    }
12310×
    for (i, h) in hashes.iter().enumerate() {
12320×
        if i > 0 {
12330×
            println!();
12340×
        }
12350×
        show_one(&repo, *h, false, false)?;
1236
    }
12370×
    Ok(0)
12382×
}
1239
1240
/// One change, as `oxy show` prints it; `inline` JSON goes without its
1241
/// newline, for an array.
12422×
fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool) -> Result<i32> {
12432×
    let c = repo.store().get_change(&h)?;
12442×
    if as_json {
12451×
        let files = repo.diff_files(Some(&h))?;
12461×
        let heads = repo.bookmark_heads()?;
12471×
        let entry = oxy_core::repo::LogEntry {
12481×
            hash: h,
12491×
            change: oxy_core::state::ChangeMeta::of(&c),
12501×
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
12511×
            is_head: heads.contains(&h),
12521×
        };
12531×
        let mut body = log_entry_json(repo, &entry)?;
12541×
        body.pop();
12551×
        body.push_str(&format!(
1256
            ",{}:{}}}",
12571×
            json::s("files"),
12581×
            json::arr(files.iter().map(|f| json::obj([
12591×
                ("path", json::s(&f.path)),
12601×
                ("kind", json::s(&f.kind)),
12611×
                ("from", json::opt(f.from.as_deref(), json::s))
12621×
            ])))
1263
        ));
12641×
        if inline {
12650×
            print!("{body}");
12661×
        } else {
12671×
            println!("{body}");
12681×
        }
12691×
        return Ok(0);
12701×
    }
12711×
    println!(
1272
        "{} {} {}",
12731×
        ui::section("change"),
12741×
        ui::id(short_id(&c)),
12751×
        ui::hash(format!("#{h}"))
1276
    );
12771×
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1278
    // Fetched but not pulled (oxygen#56): say where it is.
12791×
    if let Some(at) = repo.remote_only_location(&h)? {
12800×
        println!(
12810×
            "{}",
12820×
            ui::kv(
12830×
                "only in",
12840×
                ui::warn(format!(
12850×
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
12860×
                ))
12870×
            )
12880×
        );
12891×
    }
12901×
    let meta = oxy_core::state::ChangeMeta::of(&c);
12911×
    let status = repo.authenticate_change_known(&h, Some(&meta))?;
12921×
    println!("{}", ui::kv("author", ui::author(author_name(repo, &meta))));
12931×
    if let Some(agent) = via(repo, &status, &meta.author) {
12940×
        println!("{}", ui::kv("via", agent.line()));
12951×
    }
12961×
    println!(
1297
        "{}",
12981×
        ui::kv(
12991×
            "date",
13001×
            format!(
1301
                "{} {}",
13021×
                when(c.hlc.wall_ms),
13031×
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1304
            )
1305
        )
1306
    );
13071×
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
13081×
    println!("{}", ui::kv("sig", signature_line(repo, &h)?));
13091×
    println!();
13104×
    for line in (if c.message.is_empty() {
13110×
        "(no description)"
1312
    } else {
13131×
        &c.message
1314
    })
13151×
    .lines()
13164×
    {
13174×
        println!("    {line}");
13184×
    }
13191×
    println!();
13201×
    print!("{}", repo.describe_change(&h)?);
13211×
    Ok(0)
13222×
}
1323
13240×
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
13250×
    let repo = open()?;
1326
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1327
    // BRANCH` is: checking its files out under another bookmark's name
1328
    // made the next commit move the wrong bookmark (oxygen#60).
13290×
    if let [name] = changes {
13300×
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
13310×
            drop(repo);
13320×
            return bookmark_switch(name, discard, carry);
13330×
        }
13340×
    }
13350×
    let heads = if changes.is_empty() {
13360×
        repo.bookmark_heads()?
1337
    } else {
13380×
        let mut heads = Vec::new();
13390×
        for c in changes {
13400×
            heads.extend(repo.resolve_heads(c)?);
1341
        }
13420×
        heads
1343
    };
13440×
    let spec = if changes.is_empty() {
13450×
        repo.config.bookmark.clone()
1346
    } else {
13470×
        changes.join(" ")
1348
    };
13490×
    let sp = ui::spinner(&format!("Checking out {spec}…"));
13500×
    let command = format!("oxy checkout {spec}");
13510×
    let (r, carried) = if carry {
13520×
        repo.checkout_carry(&heads, &spec, &command)?
1353
    } else {
13540×
        (repo.checkout(&heads, discard, &command)?, vec![])
1355
    };
13560×
    sp.done(&format!(
1357
        "{} on {}: {} written, {} removed{}",
13580×
        ui::done("Working copy"),
13590×
        ui::bookmark(&spec),
13600×
        plural(r.written, "file"),
1361
        r.removed,
13620×
        if carried.is_empty() {
13630×
            String::new()
1364
        } else {
13650×
            format!("; carried {}", plural(carried.len(), "changed path"))
1366
        }
1367
    ));
13680×
    print_removed(&r);
13690×
    for n in &r.notes {
13700×
        println!("  {} {n}", ui::note());
13710×
    }
13720×
    if r.conflicted {
13730×
        println!(
13740×
            "  {} {}",
13750×
            ui::caution(),
13760×
            ui::warn("this state has conflicts; see oxy status")
13770×
        );
13780×
    }
13790×
    where_now(&repo);
13800×
    Ok(0)
13810×
}
1382
13831×
pub fn resolve(as_json: bool) -> Result<i32> {
13841×
    let repo = open()?;
13851×
    let snap = repo.snapshot("oxy resolve")?;
13861×
    if as_json {
13871×
        println!("{}", repo.status_json(&snap)?);
13881×
        return Ok(if snap.base_snapshot.is_conflicted() {
13890×
            2
1390
        } else {
13911×
            0
1392
        });
13930×
    }
13940×
    if !snap.base_snapshot.is_conflicted() {
13950×
        println!("The working copy's base has no conflicts.");
13960×
        return Ok(0);
13970×
    }
13980×
    let mut remaining = 0;
13990×
    for (p, f) in &snap.base_snapshot.files {
14000×
        if !f.is_conflicted() {
14010×
            continue;
14020×
        }
14030×
        match snap
14040×
            .statuses
14050×
            .iter()
14060×
            .find(|s| s.path == *p)
14070×
            .map(|s| s.status)
1408
        {
14090×
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
14100×
            Some(ChangeStatus::ConflictEdited) => {
14110×
                remaining += 1;
14120×
                println!("markers    {p}");
14130×
            }
14140×
            _ => {
14150×
                remaining += 1;
14160×
                println!("unresolved {p}");
14170×
            }
1418
        }
1419
    }
14200×
    for c in &snap.base_snapshot.tree.conflicts {
14210×
        remaining += 1;
14220×
        println!("tree       {c:?}");
14230×
    }
14240×
    if remaining == 0 {
14250×
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
14260×
        Ok(0)
1427
    } else {
14280×
        Ok(2)
1429
    }
14301×
}
1431
14320×
pub fn undo() -> Result<i32> {
14330×
    let repo = open()?;
14340×
    let u = repo.undo()?;
14350×
    println!("{} {}", ui::done("Undone:"), u.command);
14360×
    for c in &u.changes {
14370×
        println!("  {} {}", ui::note(), change_words(&repo, c));
14380×
    }
14390×
    if u.others_kept > 0 {
14400×
        let s = if u.others_kept == 1 { "" } else { "s" };
14410×
        println!(
1442
            "  {} {}",
14430×
            ui::note(),
14440×
            ui::dim(format!(
1445
                "{} newer operation{s} from other workspaces left as they are",
1446
                u.others_kept
1447
            ))
1448
        );
14490×
    }
14500×
    for (bookmark, remote) in &u.pushed {
14510×
        println!(
14520×
            "  {} {}",
14530×
            ui::caution(),
14540×
            ui::warn(format!(
14550×
                "{remote}/{bookmark} already has what this undid: undone here only; the next push of {bookmark} needs --force to take it back there"
14560×
            ))
14570×
        );
14580×
    }
14590×
    where_now(&repo);
14600×
    Ok(0)
14610×
}
1462
14631×
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
14641×
    let repo = open()?;
14651×
    let ops = repo.op_log()?;
1466
    // What each operation changed, against the one before it.
146711×
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
146811×
        match ops.get(i + 1) {
146910×
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
14701×
            None => Ok(vec![]),
1471
        }
147211×
    };
14731×
    if as_json {
14741×
        let mut items = Vec::new();
147511×
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
147611×
            let summary: Vec<String> = changes_of(i)?
147711×
                .iter()
147811×
                .map(|c| change_words(&repo, c))
147911×
                .collect();
148011×
            items.push(json::obj([
148111×
                ("id", json::s(&r.to_hex())),
148211×
                ("when_ms", json::n(op.hlc.wall_ms)),
148311×
                ("command", json::s(&op.command)),
148411×
                ("snapshot", json::b(op.is_snapshot())),
148511×
                ("current", json::b(i == 0)),
148611×
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1487
            ]));
1488
        }
14891×
        println!("{}", json::arr(items));
14901×
        return Ok(0);
14910×
    }
14920×
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
14930×
    let id = |r: &oxy_core::hash::ObjectRef| {
14940×
        let hex = r.to_hex();
14950×
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
14960×
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
14970×
    };
14980×
    let rail = ui::dim(ui::glyph("│", "|"));
14990×
    let (mut i, mut shown) = (0, 0);
15000×
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
15010×
        let (r, op) = &ops[i];
15020×
        let bullet = if i == 0 {
15030×
            ui::ok(ui::glyph("@", "@"))
1504
        } else {
15050×
            ui::dim(ui::glyph("○", "o"))
1506
        };
1507
        // A run of snapshots folds into one entry.
15080×
        let mut run = 1;
15090×
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
15100×
            run += 1;
15110×
        }
15120×
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
15130×
        if op.is_snapshot() {
15140×
            let span = if run > 1 {
15150×
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1516
            } else {
15170×
                String::new()
1518
            };
15190×
            println!(
1520
                "{bullet}  {}{} {when}",
15210×
                id(r),
15220×
                if span.is_empty() {
15230×
                    String::new()
1524
                } else {
15250×
                    format!(" {span}")
1526
                }
1527
            );
15280×
            println!(
1529
                "{rail}  {}",
15300×
                ui::dim(if run == 1 {
15310×
                    "working-copy snapshot".to_string()
1532
                } else {
15330×
                    format!("{run} working-copy snapshots")
1534
                })
1535
            );
1536
        } else {
15370×
            println!("{bullet}  {} {when}", id(r));
15380×
            let words: Vec<String> = changes_of(i)?
15390×
                .iter()
15400×
                .map(|c| change_words(&repo, c))
15410×
                .collect();
15420×
            let summary = if words.is_empty() {
15430×
                if i + 1 == ops.len() {
15440×
                    "created the repository".to_string()
1545
                } else {
15460×
                    "no bookmark or working-copy change".to_string()
1547
                }
1548
            } else {
15490×
                words.join("; ")
1550
            };
15510×
            println!(
1552
                "{rail}  {}",
15530×
                if i == 0 {
15540×
                    ui::subject(&summary)
1555
                } else {
15560×
                    summary
1557
                }
1558
            );
15590×
            let cmd = op.command.lines().next().unwrap_or("");
15600×
            let cmd: String = cmd.chars().take(100).collect();
15610×
            println!("{rail}  {}", ui::dim(cmd));
1562
        }
15630×
        i += run;
15640×
        shown += 1;
1565
    }
15660×
    if i < ops.len() {
15670×
        println!(
15680×
            "{}",
15690×
            ui::dim(format!(
15700×
                "{} {} older; pass -n to see more",
15710×
                ui::glyph("…", "..."),
15720×
                plural(ops.len() - i, "operation")
15730×
            ))
15740×
        );
15750×
    }
15760×
    Ok(0)
15771×
}
1578
1579
/// One change an operation made, in words.
158011×
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1581
    use oxy_core::repo::ViewChange::*;
15822×
    match c {
15830×
        BookmarkCreated { name, heads } => {
15840×
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1585
        }
15860×
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
15872×
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
15881×
        BookmarkMoved { name, from, to } => format!(
1589
            "{name}: {from} {} {}",
15901×
            ui::glyph("→", "->"),
15911×
            plural(*to, "head")
1592
        ),
15931×
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
15940×
        TagCreated { name } => format!("tagged {name}"),
15950×
        TagDeleted { name } => format!("removed tag {name}"),
15960×
        Policy => "trust policy changed".to_string(),
15978×
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
15988×
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
15990×
            Err(_) => "working copy moved".to_string(),
1600
        },
1601
    }
160211×
}
1603
16040×
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
16050×
    let repo = open()?;
16060×
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
16070×
    let r = repo.op_restore(op, discard)?;
16080×
    sp.done(&format!(
16090×
        "{} to operation {} {}",
16100×
        ui::done("Restored"),
16110×
        ui::hash(r.op.short(12)),
16120×
        ui::dim(r.command.lines().next().unwrap_or(""))
16130×
    ));
16140×
    println!(
1615
        "  {} {}",
16160×
        ui::note(),
16170×
        ui::dim(format!(
1618
            "{} written, {} removed; oxy undo goes back again",
16190×
            plural(r.checkout.written, "file"),
1620
            r.checkout.removed
1621
        ))
1622
    );
16230×
    where_now(&repo);
16240×
    Ok(0)
16250×
}
1626
16270×
pub fn op_revert(op: &str) -> Result<i32> {
16280×
    let repo = open()?;
16290×
    let r = repo.op_revert(op)?;
16300×
    let view = repo.view()?;
16310×
    let names: Vec<String> = r
16320×
        .reverted
16330×
        .iter()
16340×
        .map(|n| {
16350×
            if view.bookmarks.contains_key(n) {
16360×
                ui::bookmark(n)
1637
            } else {
16380×
                format!("{} (removed)", ui::bookmark(n))
1639
            }
16400×
        })
16410×
        .collect();
16420×
    println!(
1643
        "{} operation {} {}",
16440×
        ui::done("Reverted"),
16450×
        ui::hash(r.op.short(12)),
16460×
        ui::dim(r.command.lines().next().unwrap_or(""))
1647
    );
16480×
    println!(
1649
        "  {} {}",
16500×
        ui::note(),
16510×
        ui::dim(format!("as before it: {}", names.join(", ")))
1652
    );
16530×
    if !r.kept.is_empty() {
16540×
        println!(
16550×
            "  {} {}",
16560×
            ui::caution(),
16570×
            ui::warn(format!(
16580×
                "left as they are, having moved again since: {}",
16590×
                r.kept.join(", ")
16600×
            ))
16610×
        );
16620×
    }
16630×
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
16640×
        println!(
16650×
            "  {} {}",
16660×
            ui::note(),
16670×
            ui::dim("the working copy has work of its own: oxy checkout to move it")
16680×
        );
16690×
    }
16700×
    where_now(&repo);
16710×
    Ok(0)
16720×
}
1673
1674
/// Where the working copy and bookmark are now, after a command moved
1675
/// them (as jj says "Working copy now at").
167631×
pub fn where_now(repo: &Repo) {
167731×
    let Ok((_, wc)) = repo.working_copy() else {
16780×
        return;
1679
    };
168031×
    let heads = repo.bookmark_heads().unwrap_or_default();
168131×
    let newest = heads
168231×
        .iter()
168343×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
168431×
        .max_by_key(|(m, _)| m.hlc);
168531×
    println!(
1686
        "  {} {}",
168731×
        ui::dim(format!("{:<13}", "Working copy")),
168831×
        ui::id(wc.change_id.short(8))
1689
    );
169031×
    let tail = match newest {
169131×
        Some((m, _)) => format!(
1692
            ", newest {} {}",
169331×
            ui::id(m.change_id.short(8)),
169431×
            subject_of(&m.message)
1695
        ),
16960×
        None => String::new(),
1697
    };
169831×
    println!(
1699
        "  {} {}: {}{tail}",
170031×
        ui::dim(format!("{:<13}", "Bookmark")),
170131×
        ui::bookmark(&repo.config.bookmark),
170231×
        plural(heads.len(), "head")
1703
    );
170431×
}
1705
17060×
pub fn gc(now: bool, expire_snapshots: bool) -> Result<i32> {
17070×
    let mut repo = open()?;
17080×
    if expire_snapshots {
17090×
        repo.config.snapshot_retention_days = 0;
17100×
    }
17110×
    let sp = ui::spinner("Packing and pruning…");
17120×
    let r = repo.gc_with(now, &mut |phase| sp.set(&format!("{phase}…")))?;
17130×
    sp.clear();
17140×
    if r.packed.objects > 0 {
17150×
        println!(
17160×
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
17170×
            plural(r.packed.objects, "object"),
17180×
            r.packed.raw_bytes,
17190×
            r.packed.packed_bytes,
17200×
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
17210×
        );
17220×
    }
17230×
    println!(
1724
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
17250×
        plural(r.reachable, "object"),
17260×
        plural(r.pruned.objects, "unreachable object"),
1727
        r.pruned.bytes,
17280×
        if r.pruned.deferred > 0 {
17290×
            format!(
1730
                "; {} deferred by the grace period (use --now)",
17310×
                plural(r.pruned.deferred, "object")
1732
            )
1733
        } else {
17340×
            String::new()
1735
        },
17360×
        if r.merged_packs > 0 {
17370×
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1738
        } else {
17390×
            String::new()
1740
        },
17410×
        plural(repo.store().pack_count(), "pack")
1742
    );
17430×
    Ok(0)
17440×
}
1745
1746
/// `oxy gc --remote NAME`: fold a store remote's bundles into one.
17472×
pub fn gc_remote(name: &str, now: bool) -> Result<i32> {
17482×
    let repo = open()?;
17492×
    let sp = ui::spinner(&format!("Folding {name}'s bundles…"));
17502×
    let r = repo.gc_remote(name, now)?;
17511×
    sp.clear();
17521×
    if r.merged > 0 {
17531×
        println!(
17541×
            "{} {} into one of {} bytes ({})",
17551×
            ui::done("Folded"),
17561×
            plural(r.merged, "bundle"),
17571×
            r.bundle_bytes,
17581×
            plural(r.changes, "change")
17591×
        );
17601×
    } else {
17610×
        println!(
17620×
            "{} {}",
17630×
            ui::note(),
17640×
            ui::dim("nothing to fold: one bundle holds everything")
17650×
        );
17660×
    }
17671×
    println!(
1768
        "  {} {}",
17691×
        ui::note(),
17701×
        ui::dim(format!(
1771
            "removed {}{}",
17721×
            plural(r.deleted, "superseded bundle"),
17731×
            if r.deferred > 0 {
17740×
                format!(
1775
                    "; {} kept for readers that may still fetch them (use --now)",
17760×
                    plural(r.deferred, "bundle")
1777
                )
1778
            } else {
17791×
                String::new()
1780
            }
1781
        ))
1782
    );
17831×
    Ok(0)
17842×
}
1785
1786
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
17870×
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1788
    use oxy_core::repo::Health;
17890×
    let repo = open()?;
17900×
    let sp = ui::spinner(if offline {
17910×
        "Checking…"
1792
    } else {
17930×
        "Checking, and contacting remotes…"
1794
    });
17950×
    let r = repo.doctor(!offline);
17960×
    sp.clear();
17970×
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
17980×
    let word = |h: Health| match h {
17990×
        Health::Ok => "ok",
18000×
        Health::Warn => "warning",
18010×
        Health::Fail => "fail",
18020×
    };
18030×
    if as_json {
18040×
        let checks: Vec<String> = r
18050×
            .checks
18060×
            .iter()
18070×
            .map(|c| {
18080×
                json::obj([
18090×
                    ("area", json::s(&c.area)),
18100×
                    ("health", json::s(word(c.health))),
18110×
                    ("message", json::s(&c.message)),
18120×
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
18130×
                ])
18140×
            })
18150×
            .collect();
18160×
        println!(
1817
            "{}",
18180×
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1819
        );
18200×
        return Ok(code);
18210×
    }
18220×
    let mut last = "";
18230×
    for c in &r.checks {
18240×
        if c.area != last {
18250×
            println!("{}", ui::section(&c.area));
18260×
            last = &c.area;
18270×
        }
18280×
        let mark = match c.health {
18290×
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
18300×
            Health::Warn => ui::caution(),
18310×
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1832
        };
18330×
        println!("  {mark} {}", c.message);
18340×
        if let Some(h) = &c.hint {
18350×
            println!("    {} {}", ui::dim("→"), ui::dim(h));
18360×
        }
1837
    }
18380×
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
18390×
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
18400×
    if fails + warns == 0 {
18410×
        println!("{}", ui::done("Everything looks right."));
18420×
    } else {
18430×
        println!(
1844
            "{} {}, {}.",
18450×
            if fails > 0 {
18460×
                ui::err(ui::glyph("✖", "x"))
1847
            } else {
18480×
                ui::caution()
1849
            },
18500×
            plural(fails, "problem"),
18510×
            plural(warns, "warning")
1852
        );
1853
    }
18540×
    Ok(code)
18550×
}
1856
1857
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
18580×
pub fn fsck(as_json: bool) -> Result<i32> {
1859
    use oxy_core::repo::Severity;
18600×
    let repo = open()?;
18610×
    let sp = ui::spinner("Checking every object…");
18620×
    let r = repo.fsck()?;
18630×
    sp.clear();
18640×
    let code = if r.errors() > 0 { 1 } else { 0 };
18650×
    if as_json {
18660×
        let problems: Vec<String> = r
18670×
            .problems
18680×
            .iter()
18690×
            .map(|p| {
18700×
                json::obj([
1871
                    (
1872
                        "severity",
18730×
                        json::s(match p.severity {
18740×
                            Severity::Error => "error",
18750×
                            Severity::Warning => "warning",
1876
                        }),
1877
                    ),
1878
                    (
18790×
                        "object",
18800×
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1881
                    ),
18820×
                    ("what", json::s(&p.what)),
1883
                ])
18840×
            })
18850×
            .collect();
18860×
        println!(
1887
            "{}",
18880×
            json::obj([
18890×
                ("ok", json::b(code == 0)),
18900×
                ("objects", json::n(r.objects)),
18910×
                ("ops", json::n(r.ops)),
18920×
                ("changes", json::n(r.changes)),
18930×
                ("signed", json::n(r.signed)),
18940×
                ("unsigned", json::n(r.unsigned)),
18950×
                ("checkpoints", json::n(r.checkpoints)),
18960×
                ("attestations", json::n(r.attestations)),
18970×
                ("errors", json::n(r.errors())),
18980×
                ("warnings", json::n(r.warnings())),
18990×
                ("problems", json::arr(problems)),
19000×
            ])
1901
        );
19020×
        return Ok(code);
19030×
    }
19040×
    println!(
1905
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
19060×
        plural(r.objects, "object"),
19070×
        plural(r.ops, "operation"),
19080×
        plural(r.changes, "change"),
1909
        r.signed,
1910
        r.unsigned,
19110×
        plural(r.checkpoints, "checkpoint"),
19120×
        plural(r.attestations, "attestation"),
1913
    );
19140×
    for p in &r.problems {
19150×
        let obj = p
19160×
            .object
19170×
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
19180×
            .unwrap_or_default();
19190×
        match p.severity {
19200×
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
19210×
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1922
        }
1923
    }
19240×
    if r.problems.is_empty() {
19250×
        println!("{}", ui::done("No problems found."));
19260×
    } else if code == 0 {
19270×
        println!(
19280×
            "{}",
19290×
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
19300×
        );
19310×
    } else {
19320×
        println!(
19330×
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
19340×
            ui::err(ui::glyph("✖", "x")),
19350×
            plural(r.errors(), "error"),
19360×
            plural(r.warnings(), "warning")
19370×
        );
19380×
    }
19390×
    Ok(code)
19400×
}
1941
1942
/// The head the working copy sits on, for commands that default to it. With
1943
/// several heads beneath the working copy, the most recently made one is
1944
/// chosen and announced.
19450×
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
19460×
    let snap = repo.snapshot_status("oxy")?;
19470×
    let base = snap.base.maximal(&snap.wc.deps);
19480×
    match base.as_slice() {
19490×
        [] => anyhow::bail!("the working copy sits on no change yet"),
19500×
        [h] => Ok(*h),
19510×
        many => {
19520×
            let latest = many
19530×
                .iter()
19540×
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
19550×
                .copied()
19560×
                .unwrap();
19570×
            let c = repo.store().get_change(&latest)?;
19580×
            println!(
1959
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
19600×
                short_id(&c),
19610×
                latest.short(12),
19620×
                many.len()
1963
            );
19640×
            Ok(latest)
1965
        }
1966
    }
19670×
}
1968
1969
/// `oxy describe` without -m: the working copy's name for a build.
19704×
pub fn describe_name(as_json: bool) -> Result<i32> {
19714×
    let repo = open()?;
19724×
    let d = repo.describe_working_copy()?;
19734×
    if as_json {
19743×
        println!(
1975
            "{}",
19763×
            json::obj([
19773×
                ("describe", json::s(&d.line())),
19783×
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
19793×
                ("distance", json::n(d.distance)),
19803×
                ("bookmark", json::s(&d.bookmark)),
19813×
                ("change", json::s(&d.change.to_hex())),
19823×
                ("hash", json::s(&d.hash.to_hex())),
19833×
                ("dirty", json::b(d.dirty)),
1984
            ])
1985
        );
19861×
    } else {
19871×
        println!("{}", d.line());
19881×
    }
19894×
    Ok(0)
19904×
}
1991
19920×
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
19930×
    let repo = open()?;
19940×
    let h = match change {
19950×
        Some(c) => repo.resolve_change(c)?,
19960×
        None => current_head(&repo)?,
1997
    };
19980×
    let new = repo.describe(&h, message)?;
19990×
    let c = repo.store().get_change_meta(&new)?;
20000×
    println!(
2001
        "{} {} {}  {}",
20020×
        ui::done("Described"),
20030×
        ui::id(c.change_id.short(8)),
20040×
        ui::hash(format!("#{}", new.short(12))),
20050×
        ui::subject(subject_of(message))
2006
    );
20070×
    Ok(0)
20080×
}
2009
20100×
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
20110×
    let repo = open()?;
20120×
    let before = repo.view()?;
20130×
    let new = match into {
20140×
        Some(spec) => {
20150×
            let target = repo.resolve_change(spec)?;
20160×
            repo.amend_into(&target, message)?
2017
        }
20180×
        None => repo.amend(message)?,
2019
    };
20200×
    let c = repo.store().get_change_meta(&new)?;
20210×
    println!(
2022
        "{} {} {}  {}",
20230×
        ui::done("Amended"),
20240×
        ui::id(c.change_id.short(8)),
20250×
        ui::hash(format!("#{}", new.short(12))),
20260×
        ui::subject(subject_of(&c.message))
2027
    );
2028
    // Rewriting what a remote already has means the next push replaces it
2029
    // there (oxygen#99): say so now, not when the push is refused.
20300×
    let bookmark = repo.config.bookmark.clone();
20310×
    let (had, has) = (
20320×
        repo.heads_of(&before, &bookmark)?,
20330×
        repo.heads_of(&repo.view()?, &bookmark)?,
2034
    );
20350×
    for (remote, bookmarks) in &before.remotes {
20360×
        let Some(st) = bookmarks.get(&bookmark) else {
20370×
            continue;
2038
        };
20390×
        let theirs = repo.store().get_state(st)?.heads;
20400×
        if theirs.iter().any(|h| had.contains(h) && !has.contains(h)) {
20410×
            println!(
20420×
                "  {} {}",
20430×
                ui::caution(),
20440×
                ui::warn(format!(
20450×
                    "{remote}/{bookmark} has the change as it was: the next push of {bookmark} needs --force to replace it"
20460×
                ))
20470×
            );
20480×
        }
2049
    }
20500×
    where_now(&repo);
20510×
    Ok(0)
20520×
}
2053
20540×
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
20550×
    let repo = open()?;
20560×
    let Some(r) = revset else {
20570×
        let h = repo.resolve_change(change.unwrap_or_default())?;
20580×
        abandon_one(&repo, h)?;
20590×
        where_now(&repo);
20600×
        return Ok(0);
2061
    };
2062
    // A revset: say what it selects, refuse an empty set, ask above a few.
20630×
    let selected = repo.revset(r)?;
20640×
    let wc = repo.working_copy().ok().map(|(h, _)| h);
20650×
    let hashes: Vec<ChangeHash> = selected
20660×
        .hashes
20670×
        .iter()
20680×
        .copied()
20690×
        .filter(|h| Some(*h) != wc)
20700×
        .collect();
20710×
    if hashes.is_empty() {
20720×
        anyhow::bail!("{r:?} selects no change to abandon");
20730×
    }
20740×
    println!(
2075
        "{} {} selects {}:",
20760×
        ui::section("abandon"),
20770×
        ui::id(r),
20780×
        plural(hashes.len(), "change")
2079
    );
20800×
    for h in &hashes {
20810×
        if let Some(m) = selected.metas.get(h) {
20820×
            println!(
20830×
                "  {} {}  {}",
20840×
                ui::id(m.change_id.short(8)),
20850×
                ui::hash(format!("#{}", h.short(12))),
20860×
                subject_of(&m.message)
20870×
            );
20880×
        }
2089
    }
2090
    const ASK_ABOVE: usize = 5;
20910×
    if hashes.len() > ASK_ABOVE && !yes {
20920×
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
20930×
    }
2094
    // Newest first: abandoning a change rewrites what depends on it, so a
2095
    // later member is found again by its ChangeId.
20960×
    let mut done = 0;
20970×
    for h in &hashes {
20980×
        let Some(m) = selected.metas.get(h) else {
20990×
            continue;
2100
        };
21010×
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
21020×
            Ok(h) => h,
21030×
            Err(_) => continue,
2104
        };
21050×
        abandon_one(&repo, now)?;
21060×
        done += 1;
2107
    }
21080×
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
21090×
    where_now(&repo);
21100×
    Ok(0)
21110×
}
2112
21130×
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
21140×
    let c = repo.store().get_change_meta(&h)?;
21150×
    let notes = repo.abandon(&h)?;
21160×
    println!(
2117
        "{} {} {}  {}",
21180×
        ui::done("Abandoned"),
21190×
        ui::id(c.change_id.short(8)),
21200×
        ui::hash(format!("#{}", h.short(12))),
21210×
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
2122
    );
21230×
    for n in notes {
21240×
        println!("  {} {n}", ui::note());
21250×
    }
21260×
    Ok(())
21270×
}
2128
21290×
pub fn checkpoint() -> Result<i32> {
21300×
    let repo = open()?;
21310×
    let sp = ui::spinner("Writing checkpoint…");
21320×
    let (r, changes, bytes) = repo.checkpoint()?;
21330×
    sp.done(&format!(
21340×
        "{} {} of {} ({} bytes) for {}",
21350×
        ui::done("Checkpoint"),
21360×
        ui::hash(format!("#{}", r.short(12))),
21370×
        plural(changes, "change"),
21380×
        bytes,
21390×
        ui::id(&repo.config.bookmark)
21400×
    ));
21410×
    Ok(0)
21420×
}
2143
2144
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
21450×
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
21460×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
21470×
        return Ok(1);
2148
    };
21490×
    let info = repo.quick_status()?;
21500×
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
21510×
        oxy_core::repo::GLYPH_PROMPT_FORMAT
2152
    } else {
21530×
        format
2154
    };
21550×
    let line = match color {
21560×
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
21570×
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
21580×
        Some(_) => info.format_colored(fmt, ("", "")),
21590×
        None => info.format(fmt),
2160
    };
21610×
    println!("{line}");
21620×
    Ok(0)
21630×
}
2164
21650×
pub fn sparse(paths: &[String]) -> Result<i32> {
21660×
    let mut repo = open()?;
21670×
    if paths.is_empty() {
21680×
        if repo.config.sparse_paths.is_empty() {
21690×
            println!("No sparse filter: the whole tree is materialized.");
21700×
        } else {
21710×
            println!("{}", ui::heading("Sparse filter"));
21720×
            for p in &repo.config.sparse_paths {
21730×
                println!("  {}", ui::path(p));
21740×
            }
2175
        }
21760×
        return Ok(0);
21770×
    }
21780×
    let snap = repo.snapshot("oxy sparse")?;
21790×
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
21800×
        anyhow::bail!(
2181
            "the working copy has changes; commit them before changing the sparse filter"
2182
        );
21830×
    }
21840×
    repo.config.set("filter.paths", &paths.join(","))?;
21850×
    repo.save_config()?;
21860×
    let heads = repo.bookmark_heads()?;
21870×
    let sp = ui::spinner("Re-checking out with the new filter…");
21880×
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
21890×
    sp.done(&format!(
21900×
        "{} {}: {} written, {} removed",
21910×
        ui::done("Sparse filter set to"),
21920×
        ui::path(paths.join(",")),
21930×
        plural(r.written, "file"),
21940×
        r.removed
21950×
    ));
21960×
    Ok(0)
21970×
}
2198
21992×
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
22002×
    let repo = open()?;
22012×
    repo.snapshot_status("oxy tag")?;
22022×
    let heads = if changes.is_empty() {
22032×
        repo.bookmark_heads()?
2204
    } else {
22050×
        let mut heads = Vec::new();
22060×
        for c in changes {
22070×
            heads.extend(repo.resolve_heads(c)?);
2208
        }
22090×
        heads
2210
    };
22112×
    let t = repo.tag_create(name, &heads, message)?;
22122×
    println!(
2213
        "{} {} {} {} ({}){}",
22142×
        ui::done("Tagged"),
22152×
        ui::bookmark(&t.name),
22162×
        ui::dim(ui::glyph("→", "->")),
22172×
        ui::hash(format!("#{}", t.state.short(12))),
22182×
        plural(t.heads.len(), "head"),
22192×
        t.signer
22202×
            .map(|s| format!(", signed by {s}"))
22212×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2222
    );
22232×
    Ok(0)
22242×
}
2225
22261×
pub fn tag_list(as_json: bool) -> Result<i32> {
22271×
    let repo = open()?;
22281×
    let tags = repo.tags()?;
22291×
    if as_json {
22301×
        println!(
2231
            "{}",
22321×
            json::arr(tags.iter().map(|t| {
22331×
                json::obj([
22341×
                    ("name", json::s(&t.name)),
22351×
                    ("state", json::s(&t.state.to_hex())),
22361×
                    ("heads", json::hashes(&t.heads)),
22371×
                    ("message", json::s(&t.message)),
2238
                    (
22391×
                        "signer",
22401×
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2241
                    ),
2242
                ])
22431×
            }))
2244
        );
22451×
        return Ok(0);
22460×
    }
22470×
    if tags.is_empty() {
22480×
        println!("{}", ui::dim("No tags."));
22490×
    }
22500×
    for t in tags {
22510×
        println!(
2252
            "{} {} {}{}{}{}",
22530×
            ui::ok(ui::glyph("⚑", "#")),
22540×
            ui::bookmark(&t.name),
2255
            // The heads, as `oxy log` shows changes, not the state hash.
22560×
            ui::hash(
22570×
                t.heads
22580×
                    .iter()
22590×
                    .map(|h| format!("#{}", h.short(12)))
22600×
                    .collect::<Vec<_>>()
22610×
                    .join(" ")
2262
            ),
22630×
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
22640×
            if t.message.is_empty() {
22650×
                String::new()
2266
            } else {
22670×
                format!("  {}", ui::subject(subject_of(&t.message)))
2268
            },
22690×
            t.signer
22700×
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
22710×
                .unwrap_or_default()
2272
        );
2273
    }
22740×
    Ok(0)
22751×
}
2276
2277
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2278
/// and workspace add take as "be on this bookmark" (oxygen#60).
22790×
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
22800×
    Ok(repo.view()?.bookmarks.contains_key(name)
22810×
        || repo
22820×
            .remote_only_bookmarks()?
22830×
            .iter()
22840×
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
22850×
}
2286
22870×
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
22880×
    let repo = open()?;
2289
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2290
    // this workspace's bookmark with that one's files.
22910×
    if let [name] = changes {
22920×
        if names_bookmark(&repo, name)? {
22930×
            let (local, _) = repo.local_bookmark_for(name)?;
22940×
            let heads = repo.resolve_heads(&local)?;
22950×
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
22960×
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
22970×
            sp.done(&format!(
22980×
                "{} {} (workspace {}) on {}",
22990×
                ui::done("Workspace created at"),
23000×
                ui::path(ws.root().display()),
23010×
                ui::id(ws.workspace().short(8)),
23020×
                ui::bookmark(&local)
23030×
            ));
23040×
            return Ok(0);
23050×
        }
23060×
    }
23070×
    let heads = if changes.is_empty() {
23080×
        None
2309
    } else {
23100×
        let mut heads = Vec::new();
23110×
        for c in changes {
23120×
            heads.extend(repo.resolve_heads(c)?);
2313
        }
23140×
        Some(heads)
2315
    };
23160×
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
23170×
    let ws = repo.workspace_add(path, heads.as_deref())?;
23180×
    sp.done(&format!(
23190×
        "{} {} (workspace {})",
23200×
        ui::done("Workspace created at"),
23210×
        ui::path(ws.root().display()),
23220×
        ui::id(ws.workspace().short(8))
23230×
    ));
23240×
    Ok(0)
23250×
}
2326
23271×
pub fn workspace_list(as_json: bool) -> Result<i32> {
23281×
    let repo = open()?;
23291×
    if as_json {
23301×
        println!(
2331
            "{}",
23321×
            json::arr(repo.workspaces()?.iter().map(|w| {
23331×
                json::obj([
23341×
                    ("id", json::s(&w.id.to_hex())),
23351×
                    ("path", json::s(&w.path.to_string_lossy())),
23361×
                    ("current", json::b(w.current)),
2337
                    (
23381×
                        "working_copy",
23391×
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2340
                    ),
2341
                ])
23421×
            }))
2343
        );
23441×
        return Ok(0);
23450×
    }
23460×
    for w in repo.workspaces()? {
23470×
        println!(
2348
            "{} {} {}{}",
23490×
            if w.current {
23500×
                ui::ok(ui::glyph("●", "*"))
2351
            } else {
23520×
                ui::dim(ui::glyph("○", "o"))
2353
            },
23540×
            ui::id(w.id.short(8)),
23550×
            ui::path(w.path.display()),
23560×
            w.working_copy
23570×
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
23580×
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2359
        );
2360
    }
23610×
    Ok(0)
23621×
}
2363
23640×
pub fn workspace_forget(spec: &str) -> Result<i32> {
23650×
    let repo = open()?;
23660×
    let all = repo.workspaces()?;
23670×
    let target = std::fs::canonicalize(spec).ok();
23680×
    let matches: Vec<_> = all
23690×
        .iter()
23700×
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
23710×
        .collect();
23720×
    let w = match matches.as_slice() {
23730×
        [w] => *w,
23740×
        [] => anyhow::bail!("no workspace matches {spec:?}"),
23750×
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2376
    };
23770×
    repo.workspace_forget(&w.id)?;
23780×
    println!(
2379
        "{} workspace {} at {}; its files were left in place.",
23800×
        ui::done("Forgot"),
23810×
        ui::id(w.id.short(8)),
23820×
        ui::path(w.path.display())
2383
    );
23840×
    Ok(0)
23850×
}
2386
23870×
pub fn lock(path: &str) -> Result<i32> {
23880×
    let repo = open()?;
23890×
    repo.lock_path(path)?;
23900×
    println!(
2391
        "{} {} {}",
23920×
        ui::done("Locked"),
23930×
        ui::path(path),
23940×
        ui::dim("(advisory, local)")
2395
    );
23960×
    Ok(0)
23970×
}
2398
23990×
pub fn unlock(path: &str) -> Result<i32> {
24000×
    let repo = open()?;
24010×
    repo.unlock_path(path)?;
24020×
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
24030×
    Ok(0)
24040×
}
2405
24060×
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
24070×
    let repo = open()?;
24080×
    let h = repo.resolve_change(change)?;
24090×
    let (h1, h2) = repo.split(&h, paths)?;
24100×
    let c1 = repo.store().get_change_meta(&h1)?;
24110×
    let c2 = repo.store().get_change_meta(&h2)?;
24120×
    println!(
2413
        "{} into {} {} and {} {}",
24140×
        ui::done("Split"),
24150×
        ui::id(c1.change_id.short(8)),
24160×
        ui::hash(format!("#{}", h1.short(12))),
24170×
        ui::id(c2.change_id.short(8)),
24180×
        ui::hash(format!("#{}", h2.short(12)))
2419
    );
24200×
    Ok(0)
24210×
}
2422
24236×
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
24246×
    let mut heads = Vec::new();
24256×
    for c in changes {
24266×
        heads.extend(repo.resolve_heads(c)?);
2427
    }
24286×
    Ok(heads)
24296×
}
2430
24316×
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
24326×
    let repo = open()?;
24336×
    repo.snapshot_status("oxy bookmark create")?;
24346×
    let heads = if changes.is_empty() {
24353×
        None
2436
    } else {
24373×
        let named = heads_from(&repo, changes)?;
24383×
        let (_, wc) = repo.working_copy()?;
24393×
        let gap = repo.state_gap(&wc.deps, &named)?;
24403×
        if upto {
24411×
            Some(gap.upto)
24422×
        } else if only || gap.earlier.is_empty() {
24431×
            Some(named)
2444
        } else {
24451×
            anyhow::bail!(
2446
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2447
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2448
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2449
                 or --only for just {0} and what it depends on.",
24501×
                changes.join(" "),
24511×
                plural(gap.earlier.len(), "change"),
24521×
                listed_changes(&repo, &gap.earlier)
2453
            );
2454
        }
2455
    };
24565×
    let heads = repo.bookmark_create(name, heads.as_deref())?;
24575×
    println!(
2458
        "{} bookmark {} {} {}",
24595×
        ui::done("Created"),
24605×
        ui::bookmark(name),
24615×
        ui::dim(ui::glyph("→", "->")),
24625×
        ui::dim(plural(heads.len(), "head"))
2463
    );
24645×
    println!(
2465
        "  {} {}",
24665×
        ui::note(),
24675×
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2468
    );
24695×
    Ok(0)
24706×
}
2471
2472
/// Up to five changes, newest last, as `  #hash subject` lines.
24732×
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
24742×
    let shown = changes.len().min(5);
24752×
    let mut lines: Vec<String> = changes[changes.len() - shown..]
24762×
        .iter()
24772×
        .map(|h| {
24782×
            let subject = repo
24792×
                .store()
24802×
                .get_change(h)
24812×
                .map(|c| subject_of(&c.message).to_string())
24822×
                .unwrap_or_default();
24832×
            format!("  #{} {subject}", h.short(12))
24842×
        })
24852×
        .collect();
24862×
    if changes.len() > shown {
24870×
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
24882×
    }
24892×
    lines.join("\n")
24902×
}
2491
24923×
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
24933×
    let repo = open()?;
24943×
    repo.snapshot_status("oxy bookmark set")?;
24953×
    let named = heads_from(&repo, changes)?;
2496
    // What the bookmark holds now and the new heads would leave out.
24973×
    let current = repo
24983×
        .bookmarks()?
24993×
        .into_iter()
25006×
        .find(|b| b.name == name)
25013×
        .map(|b| b.heads)
25023×
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
25033×
    let gap = repo.state_gap(&current, &named)?;
2504
    // A fast-forward: the new heads hold the bookmark's newest head, so
2505
    // what they leave out is older work nothing since has built on, such
2506
    // as an early change no later one depends on (oxygen#78). Keep it, as
2507
    // --upto does, and say so.
25083×
    let newest = current
25093×
        .iter()
25108×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m.hlc, *h)))
25113×
        .max()
25123×
        .map(|(_, h)| h);
2513
    // Ahead, too: a head the bookmark holds already (it would only drop
2514
    // the others) is not a move forward.
25153×
    let ahead = repo
25163×
        .load_state_history(&current)
25173×
        .is_ok_and(|st| named.iter().any(|h| !st.contains(h)));
25183×
    let forward = !only
25193×
        && ahead
25201×
        && !gap.earlier.is_empty()
25211×
        && newest.is_some_and(|n| {
25221×
            repo.load_state_history(&named)
25231×
                .is_ok_and(|st| st.contains(&n))
25241×
        });
25253×
    let heads = if upto {
25261×
        gap.upto
25272×
    } else if forward {
25281×
        println!(
2529
            "  {} {}",
25301×
            ui::note(),
25311×
            ui::dim(format!(
2532
                "{} builds on {name}'s newest head; keeping {} it holds that {0} does not depend on",
25331×
                changes.join(" "),
25341×
                plural(gap.earlier.len(), "change")
2535
            ))
2536
        );
25371×
        gap.upto
25381×
    } else if only || gap.earlier.is_empty() {
25390×
        named
2540
    } else {
25411×
        anyhow::bail!(
2542
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2543
             A state is its heads and what they depend on, not everything recorded before them.\n\
2544
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2545
             or --only for just {0} and what it depends on.",
25461×
            changes.join(" "),
25471×
            plural(gap.earlier.len(), "change"),
25481×
            listed_changes(&repo, &gap.earlier)
2549
        );
2550
    };
25512×
    let heads = repo.bookmark_set(name, &heads)?;
25522×
    println!(
2553
        "{} bookmark {} {} {}",
25542×
        ui::done("Moved"),
25552×
        ui::bookmark(name),
25562×
        ui::dim(ui::glyph("→", "->")),
25572×
        ui::dim(plural(heads.len(), "head"))
2558
    );
25592×
    Ok(0)
25603×
}
2561
25620×
pub fn bookmark_delete(name: &str) -> Result<i32> {
25630×
    let repo = open()?;
25640×
    repo.bookmark_delete(name)?;
25650×
    println!(
2566
        "{} bookmark {} {}",
25670×
        ui::done("Deleted"),
25680×
        ui::bookmark(name),
25690×
        ui::dim("(its changes stay until unreachable)")
2570
    );
25710×
    Ok(0)
25720×
}
2573
2574
/// Heads with their metadata, newest first.
25750×
fn heads_newest_first(
25760×
    repo: &Repo,
25770×
    heads: &[oxy_core::hash::ChangeHash],
25780×
) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> {
25790×
    let mut out: Vec<_> = heads
25800×
        .iter()
25810×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m)))
25820×
        .collect();
25830×
    out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc));
25840×
    out
25850×
}
2586
2587
/// One head as a line: id, hash, author, when, subject.
25880×
fn print_head(
25890×
    repo: &Repo,
25900×
    indent: &str,
25910×
    h: &oxy_core::hash::ChangeHash,
25920×
    m: &oxy_core::state::ChangeMeta,
25930×
) {
25940×
    println!(
2595
        "{indent}{} {} {}{}{}{}{}",
25960×
        ui::id(m.change_id.short(8)),
25970×
        ui::dim(format!("#{}", &h.to_hex()[..8])),
25980×
        author_name(repo, m),
25990×
        ui::sep(),
26000×
        ui::dim(ui::ago(m.hlc.wall_ms)),
26010×
        ui::sep(),
26020×
        ui::subject(subject_of(&m.message))
2603
    );
26040×
}
2605
26060×
pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result<i32> {
26070×
    let repo = open()?;
26080×
    let name = name.unwrap_or(&repo.config.bookmark).to_string();
26090×
    let view = repo.view()?;
26100×
    let st = match view.bookmarks.get(&name) {
26110×
        Some(st) => *st,
26120×
        None => match oxy_core::repo::remote_bookmark(&view, &name) {
26130×
            Some((_, _, st)) => st,
26140×
            None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"),
2615
        },
2616
    };
26170×
    let heads = repo.store().get_state(&st)?.heads;
26180×
    let shown = heads_newest_first(&repo, &heads);
26190×
    if as_json {
26200×
        println!(
2621
            "{}",
26220×
            json::obj([
26230×
                ("name", json::s(&name)),
26240×
                ("current", json::b(name == repo.config.bookmark)),
2625
                (
26260×
                    "heads",
26270×
                    json::arr(shown.iter().map(|(h, m)| {
26280×
                        json::obj([
26290×
                            ("hash", json::s(&h.to_hex())),
26300×
                            ("id", json::s(&m.change_id.to_string())),
26310×
                            ("author", json::s(&author_name(&repo, m))),
26320×
                            ("time_ms", json::n(m.hlc.wall_ms)),
26330×
                            ("subject", json::s(subject_of(&m.message))),
26340×
                        ])
26350×
                    }))
2636
                ),
2637
            ])
2638
        );
26390×
        return Ok(0);
26400×
    }
26410×
    println!(
2642
        "{} {}{}{}",
26430×
        ui::ok(ui::glyph("●", "*")),
26440×
        ui::bookmark(&name),
26450×
        ui::sep(),
26460×
        ui::dim(plural(heads.len(), "head"))
2647
    );
26480×
    for (h, m) in &shown {
26490×
        print_head(&repo, "  ", h, m);
26500×
    }
26510×
    if heads.len() > 1 {
26520×
        println!(
26530×
            "  {}",
26540×
            ui::dim("None depends on another: the bookmark is all of them and their dependencies.")
26550×
        );
26560×
    }
26570×
    Ok(0)
26580×
}
2659
26605×
pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result<i32> {
26615×
    let repo = open()?;
26625×
    let remote_only = repo.remote_only_bookmarks()?;
26635×
    if as_json {
26645×
        let mut items: Vec<String> = repo
26655×
            .bookmarks()?
26665×
            .into_iter()
266713×
            .map(|b| {
266813×
                json::obj([
266913×
                    ("name", json::s(&b.name)),
267013×
                    ("heads", json::hashes(&b.heads)),
267113×
                    ("current", json::b(b.current)),
267213×
                    ("ahead", json::opt(b.ahead, json::n)),
267313×
                    ("behind", json::opt(b.behind, json::n)),
267413×
                    ("remote", json::opt(b.remote.as_deref(), json::s)),
267513×
                ])
267613×
            })
26775×
            .collect();
26785×
        if all {
26790×
            items.extend(remote_only.iter().map(|b| {
26800×
                json::obj([
26810×
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
26820×
                    ("heads", json::hashes(&b.heads)),
26830×
                    ("current", json::b(false)),
26840×
                    ("ahead", "null".into()),
26850×
                    ("behind", "null".into()),
26860×
                    ("remote", json::s(&b.remote)),
26870×
                ])
26880×
            }));
26895×
        }
26905×
        println!("{}", json::arr(items));
26915×
        return Ok(0);
26920×
    }
26930×
    for b in repo.bookmarks()? {
26940×
        let mark = if b.current {
26950×
            ui::ok(ui::glyph("●", "*"))
2696
        } else {
26970×
            ui::dim(ui::glyph("○", "o"))
2698
        };
26990×
        let mut tail = String::new();
27000×
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
27010×
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
27020×
        }
27030×
        if let Some(n) = b.behind.filter(|n| *n > 0) {
27040×
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
27050×
        }
2706
        // Which remote, when there is a choice (oxygen#83).
27070×
        if !tail.is_empty() && repo.config.remotes.len() > 1 {
27080×
            if let Some(r) = &b.remote {
27090×
                tail += &ui::dim(format!(" {r}"));
27100×
            }
27110×
        }
27120×
        let shown = heads_newest_first(&repo, &b.heads);
2713
        // The newest head's subject, so a busy bookmark shows its latest work.
27140×
        let head = match shown.first() {
27150×
            Some(_) if verbose => String::new(),
27160×
            Some((_, m)) if b.heads.len() > 1 => format!(
2717
                "{} {}",
27180×
                ui::dim("newest"),
27190×
                ui::subject(subject_of(&m.message))
2720
            ),
27210×
            Some((_, m)) => ui::subject(subject_of(&m.message)),
27220×
            None => ui::dim("(empty)"),
2723
        };
27240×
        let head = if head.is_empty() {
27250×
            head
2726
        } else {
27270×
            format!("  {head}")
2728
        };
27290×
        println!(
2730
            "{mark} {}{}{}{tail}{head}",
27310×
            ui::bookmark(&b.name),
27320×
            ui::sep(),
27330×
            ui::dim(plural(b.heads.len(), "head"))
2734
        );
27350×
        if verbose {
27360×
            for (h, m) in &shown {
27370×
                print_head(&repo, "    ", h, m);
27380×
            }
27390×
        }
2740
    }
27410×
    if remote_only.is_empty() {
27420×
        return Ok(0);
27430×
    }
27440×
    if !all {
27450×
        println!(
2746
            "{}",
27470×
            ui::dim(format!(
2748
                "  and {} only on a remote: oxy bookmark list --all",
27490×
                plural(remote_only.len(), "bookmark")
2750
            ))
2751
        );
27520×
        return Ok(0);
27530×
    }
27540×
    for b in &remote_only {
27550×
        println!(
27560×
            "{} {}{}{}",
27570×
            ui::dim(ui::glyph("◌", ".")),
27580×
            ui::dim(format!("{}/{}", b.remote, b.name)),
27590×
            ui::sep(),
27600×
            ui::dim(plural(b.heads.len(), "head"))
27610×
        );
27620×
    }
27630×
    println!(
2764
        "  {} {}",
27650×
        ui::note(),
27660×
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2767
    );
27680×
    Ok(0)
27695×
}
2770
27713×
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
27723×
    let mut repo = open()?;
27733×
    let from = repo.config.bookmark.clone();
27743×
    let (local, created_from) = repo.local_bookmark_for(name)?;
27753×
    if let Some(remote) = created_from {
27760×
        println!(
27770×
            "{} {} from {}",
27780×
            ui::done("Created"),
27790×
            ui::bookmark(&local),
27800×
            ui::dim(format!("{remote}/{local}"))
27810×
        );
27823×
    }
27833×
    let name = local.as_str();
2784
    // Only behind its remote: take the remote's state, so the switch does
2785
    // not check out a stale one (oxygen#74).
27863×
    if let Some(n) = repo.catch_up_bookmark(name)? {
27870×
        println!(
27880×
            "{} {} with {}: {} it lacked",
27890×
            ui::done("Caught up"),
27900×
            ui::bookmark(name),
27910×
            ui::dim(format!("{}/{name}", repo.default_remote())),
27920×
            plural(n, "change")
27930×
        );
27943×
    }
27953×
    let sp = ui::spinner(&format!("Switching to {name}…"));
27963×
    let (r, carried) = if carry {
27970×
        repo.bookmark_switch_carry(name)?
2798
    } else {
27993×
        (repo.bookmark_switch(name, discard)?, vec![])
2800
    };
28013×
    sp.done(&format!(
2802
        "{} to {}: {} written, {} removed{}",
28033×
        ui::done("Switched"),
28043×
        ui::bookmark(name),
28053×
        plural(r.written, "file"),
2806
        r.removed,
28073×
        if carried.is_empty() {
28083×
            String::new()
2809
        } else {
28100×
            format!("; carried {}", plural(carried.len(), "changed path"))
2811
        }
2812
    ));
28133×
    print_removed(&r);
28143×
    if r.conflicted {
28150×
        println!(
28160×
            "  {} {}",
28170×
            ui::caution(),
28180×
            ui::warn("this state has conflicts; see oxy status")
28190×
        );
28203×
    }
2821
    // Say when the new state leaves out work the old one had: a state is
2822
    // its heads and what they depend on, which can be far less than a Git
2823
    // user expects.
28243×
    if r.lacks > 0 {
28251×
        println!(
28261×
            "  {} {}",
28271×
            ui::note(),
28281×
            ui::dim(format!(
28291×
                "{name} lacks {} that {from} has",
28301×
                plural(r.lacks, "change")
28311×
            ))
28321×
        );
28332×
    }
28343×
    super::sync::subrepos_behind(&repo);
28353×
    where_now(&repo);
28363×
    Ok(0)
28373×
}
2838
28390×
pub fn merge(bookmark: &str) -> Result<i32> {
28400×
    let repo = open()?;
28410×
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
28420×
    let r = repo.merge(bookmark)?;
28430×
    if !r.changed {
28440×
        sp.done(&format!(
28450×
            "{} {}",
28460×
            ui::ok(ui::glyph("✔", "*")),
28470×
            ui::dim(format!(
28480×
                "{} already contains {bookmark}",
28490×
                repo.config.bookmark
28500×
            ))
28510×
        ));
28520×
        return Ok(0);
28530×
    }
28540×
    sp.done(&format!(
2855
        "{} {} into {}: now {}{}",
28560×
        ui::done("Merged"),
28570×
        ui::bookmark(bookmark),
28580×
        ui::bookmark(&repo.config.bookmark),
28590×
        plural(r.heads.len(), "head"),
28600×
        ui::dim(if r.checked_out {
28610×
            "; working copy updated"
2862
        } else {
28630×
            "; run oxy checkout to update the working copy"
2864
        })
2865
    ));
28660×
    let snap = repo.snapshot("oxy merge")?;
28670×
    if snap.base_snapshot.is_conflicted() {
28680×
        println!(
28690×
            "  {} {}",
28700×
            ui::caution(),
28710×
            ui::warn("the result has conflicts; see oxy status")
28720×
        );
28730×
    }
28740×
    where_now(&repo);
28750×
    Ok(0)
28760×
}
2877
28780×
pub fn squash(change: &str, into: &str) -> Result<i32> {
28790×
    let repo = open()?;
28800×
    let c = repo.resolve_change(change)?;
28810×
    let d = repo.resolve_change(into)?;
28820×
    let sp = ui::spinner("Squashing…");
28830×
    let h = repo.squash(&c, &d)?;
28840×
    let new = repo.store().get_change_meta(&h)?;
28850×
    sp.done(&format!(
28860×
        "{} into {} {}  {}",
28870×
        ui::done("Squashed"),
28880×
        ui::id(new.change_id.short(8)),
28890×
        ui::hash(format!("#{}", h.short(12))),
28900×
        ui::subject(subject_of(&new.message))
28910×
    ));
28920×
    Ok(0)
28930×
}
2894
28950×
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
28960×
    let repo = open()?;
28970×
    let c = repo.resolve_change(change)?;
28980×
    let mut heads = Vec::new();
28990×
    for o in onto {
29000×
        heads.extend(repo.resolve_heads(o)?);
2901
    }
29020×
    let sp = ui::spinner("Rebasing…");
29030×
    let h = match repo.rebase(&c, &heads) {
29040×
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
29050×
            let r = repo.rebase_into_working_copy(&c, &heads)?;
29060×
            sp.done(&format!(
29070×
                "{} {} into {}: now {}",
29080×
                ui::done("Merged"),
29090×
                onto.join(" "),
29100×
                ui::bookmark(&repo.config.bookmark),
29110×
                plural(r.heads.len(), "head"),
29120×
            ));
29130×
            if r.checked_out {
29140×
                println!(
29150×
                    "  {} {}",
29160×
                    ui::caution(),
29170×
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
29180×
                );
29190×
            } else {
29200×
                println!(
29210×
                    "  {} {}",
29220×
                    ui::caution(),
29230×
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
29240×
                );
29250×
            }
29260×
            where_now(&repo);
29270×
            return Ok(0);
2928
        }
29290×
        other => other?,
2930
    };
29310×
    let new = repo.store().get_change_meta(&h)?;
29320×
    sp.done(&format!(
29330×
        "{} {} {}  {}",
29340×
        ui::done("Rebased"),
29350×
        ui::id(new.change_id.short(8)),
29360×
        ui::hash(format!("#{}", h.short(12))),
29370×
        ui::dim(format!(
29380×
            "now depends on {}",
29390×
            plural(new.deps.len(), "change")
29400×
        ))
29410×
    ));
29420×
    where_now(&repo);
29430×
    Ok(0)
29440×
}
2945
2946
#[cfg(test)]
2947
mod tests {
2948
    use super::*;
2949
2950
    #[test]
29511×
    fn id_prefixes_agree_with_the_whole_list() {
2952
        // Ids that share long prefixes, and some that differ only in a
2953
        // half byte, from a fixed sequence.
29541×
        let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
29557999×
        let mut next = || {
29567999×
            x ^= x << 13;
29577999×
            x ^= x >> 7;
29587999×
            x ^= x << 17;
29597999×
            x
29607999×
        };
29611×
        let mut ids: Vec<[u8; 16]> = Vec::new();
29621×
        for _ in 0..2000 {
29632000×
            let mut id = [0u8; 16];
29642000×
            id[..8].copy_from_slice(&next().to_le_bytes());
29652000×
            id[8..].copy_from_slice(&next().to_le_bytes());
29662000×
            let share = (next() % 4) as usize;
29672000×
            if let Some(prev) = ids.last() {
29681999×
                id[..share].copy_from_slice(&prev[..share]);
29691999×
                if next() % 2 == 0 {
2970973×
                    id[share] = (prev[share] & 0xf0) | (id[share] & 0x0f);
29711026×
                }
29721×
            }
29732000×
            ids.push(id);
2974
        }
29754000×
        let hex = |id: &[u8; 16]| oxy_core::ids::ChangeId(*id).to_hex();
29761×
        let whole = unique_prefixes(ids.iter().map(hex));
29771×
        let some = id_prefixes(ids.clone(), ids.iter().copied());
29782000×
        for id in &ids {
29792000×
            assert_eq!(some[id], whole[&hex(id)], "{}", hex(id));
2980
        }
29811×
    }
2982
}