OXYGENHUB

Coverage / src/cli/workspace.rs 38.8%

927 of 2391 lines run, 90 of 331 functions · run #329 on main · run missed

1
//! Commands that act on the local repository and working copy.
2
3
use super::format::{
4
    author_name, deps_line, deps_of, plural, short_id, signature_line, signature_mark_of,
5
    subject_of, via, when,
6
};
7
use super::json;
8
use super::open;
9
use super::ui;
10
use anyhow::Result;
11
use oxy_core::objects::ChangeKind;
12
use oxy_core::repo::SignatureStatus;
13
use oxy_core::repo::{render_change, ChangeStatus, Repo};
14
use std::io::Write;
15
use std::path::PathBuf;
16
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,
9391858×
            _ => 2 * bytes,
940
        }
9414004×
    };
9422×
    let mut out = std::collections::HashMap::new();
9432004×
    for id in wanted {
9442004×
        let Ok(i) = all.binary_search(&id) else {
9450×
            continue;
946
        };
9472004×
        let before = i.checked_sub(1).map_or(0, |j| common(&all[j], &id));
9482004×
        let after = all.get(i + 1).map_or(0, |n| common(&id, n));
9492004×
        out.insert(id, before.max(after) + 1);
950
    }
9512×
    out
9522×
}
953
9541×
fn unique_prefixes(ids: impl Iterator<Item = String>) -> std::collections::HashMap<String, usize> {
9551×
    let mut v: Vec<String> = ids.collect();
9561×
    v.sort();
9571×
    v.dedup();
95819576×
    let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
9591×
    let mut out = std::collections::HashMap::with_capacity(v.len());
9602000×
    for i in 0..v.len() {
9612000×
        let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 };
9622000×
        let after = if i + 1 < v.len() {
9631999×
            common(&v[i], &v[i + 1])
964
        } else {
9651×
            0
966
        };
9672000×
        out.insert(v[i].clone(), before.max(after) + 1);
968
    }
9691×
    out
9701×
}
971
972
/// Bookmark, remote bookmark and tag names to show beside the changes they
973
/// point at. A name is shown on each head of its state; one with more than
974
/// three heads names too much of the log to help, so it is left out (oxy
975
/// bookmark list shows it). A remote bookmark at the same state as the
976
/// local one of that name is not repeated.
9771×
fn reference_labels(repo: &Repo) -> Result<std::collections::HashMap<ChangeHash, Vec<String>>> {
978
    const MAX_HEADS: usize = 3;
9791×
    let view = repo.view()?;
9801×
    let mut out: std::collections::HashMap<ChangeHash, Vec<String>> = Default::default();
9811×
    let mut add = |heads: Vec<ChangeHash>, label: String| {
9821×
        if heads.len() <= MAX_HEADS {
9832×
            for h in heads {
9842×
                out.entry(h).or_default().push(label.clone());
9852×
            }
9860×
        }
9871×
    };
9881×
    for (name, st) in &view.bookmarks {
9891×
        add(repo.store().get_state(st)?.heads, ui::bookmark(name));
990
    }
9911×
    for (remote, bookmarks) in &view.remotes {
9920×
        for (name, st) in bookmarks {
9930×
            if view.bookmarks.get(name) == Some(st) {
9940×
                continue;
9950×
            }
9960×
            add(
9970×
                repo.store().get_state(st)?.heads,
9980×
                ui::dim(format!("{remote}/{name}")),
999
            );
1000
        }
1001
    }
10021×
    for t in repo.tags()? {
10030×
        add(t.heads.clone(), ui::warn(&t.name));
10040×
    }
10051×
    Ok(out)
10061×
}
1007
10081×
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
10091×
    let repo = open()?;
10101×
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
10111×
    if as_json {
10121×
        let files = repo.diff_files(hash.as_ref())?;
10133×
        let items = files.iter().map(|f| {
10143×
            json::obj([
10153×
                ("path", json::s(&f.path)),
10163×
                ("kind", json::s(&f.kind)),
10173×
                ("from", json::opt(f.from.as_deref(), json::s)),
1018
                (
10193×
                    "hunks",
10203×
                    json::arr(f.hunks.iter().map(|h| {
10213×
                        json::obj([
10223×
                            ("base_line", json::n(h.base_line)),
1023
                            (
10243×
                                "added",
10253×
                                json::arr(
10263×
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
1027
                                ),
1028
                            ),
1029
                            (
10303×
                                "removed",
10313×
                                json::arr(h.removed.iter().map(|(n, l)| {
10320×
                                    json::obj([
10330×
                                        ("line", json::n(*n)),
10340×
                                        ("text", json::s(&String::from_utf8_lossy(l))),
10350×
                                    ])
10360×
                                })),
1037
                            ),
1038
                        ])
10393×
                    })),
1040
                ),
1041
            ])
10423×
        });
10431×
        println!(
1044
            "{}",
10451×
            json::obj([
10461×
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
10471×
                ("files", json::arr(items))
1048
            ])
1049
        );
10501×
        return Ok(0);
10510×
    }
10520×
    match hash {
10530×
        Some(h) => {
10540×
            let c = repo.store().get_change(&h)?;
10550×
            let (base, snapshot) = repo.change_base(&c)?;
10560×
            print!("{}", render_change(&c, &base, &snapshot));
1057
        }
1058
        None => {
1059
            // Nothing changed: nothing to show, and no base to load.
10600×
            let Some((wc, base, snapshot)) = repo.working_copy_with_base_unless_unchanged()? else {
10610×
                return Ok(0);
1062
            };
10630×
            let text = {
10640×
                let _t = oxy_core::timing::phase("diff: render the change");
10650×
                render_change(&wc, &base, &snapshot)
1066
            };
10670×
            print!("{text}");
1068
            // The process ends here: freeing the base's tree and graphs
1069
            // one by one would only cost time (about 27 ms on Linux).
10700×
            std::mem::forget((wc, base, snapshot));
1071
        }
1072
    }
10730×
    Ok(0)
10741×
}
1075
10762×
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
10772×
    let repo = open()?;
10782×
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
10792×
    let bytes = match repo.file_at(path, heads.as_deref()) {
10802×
        Ok(b) => b,
1081
        // -r CHANGE reads that change's dependency closure, not the
1082
        // bookmark it is on: say so when the bookmark has the file
1083
        // (oxygen#76).
10840×
        Err(e) => match change {
10850×
            Some(c)
10860×
                if !repo.view()?.bookmarks.contains_key(c)
10870×
                    && repo.tag_heads(c)?.is_none()
10880×
                    && repo.file_at(path, None).is_ok() =>
1089
            {
10900×
                anyhow::bail!(
1091
                    "{path} is not in {c}'s dependency closure (the change and what it \
1092
                     depends on); it is on the bookmark: try -r {}, or --at-op OP for the \
1093
                     state at an operation",
1094
                    repo.config.bookmark
1095
                )
1096
            }
10970×
            _ => return Err(e.into()),
1098
        },
1099
    };
1100
    use std::io::Write as _;
11012×
    std::io::stdout().write_all(&bytes)?;
11022×
    Ok(0)
11032×
}
1104
11051×
pub fn root(as_json: bool) -> Result<i32> {
11061×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
11070×
        if as_json {
11080×
            println!("null");
11090×
        }
11100×
        return Ok(1);
1111
    };
11121×
    if as_json {
11131×
        println!(
11141×
            "{}",
11151×
            json::obj([
11161×
                ("root", json::s(&repo.root().to_string_lossy())),
11171×
                ("workspace", json::s(&repo.workspace().to_hex())),
11181×
                ("bookmark", json::s(&repo.config.bookmark))
11191×
            ])
11201×
        );
11211×
    } else {
11220×
        println!("{}", repo.root().display());
11230×
    }
11241×
    Ok(0)
11251×
}
1126
11271×
pub fn version(as_json: bool) -> Result<i32> {
11281×
    if as_json {
11291×
        println!(
11301×
            "{}",
11311×
            json::obj([
11321×
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
11331×
                // What was built: a release's or install's `oxy describe`,
11341×
                // a Flow build's heads, or "local build".
11351×
                ("build", json::s(env!("OXY_BUILD_ID"))),
11361×
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
11371×
                ("format", json::n(2))
11381×
            ])
11391×
        );
11401×
    } else {
11410×
        println!(
11420×
            "oxy {} (repository format 2, protocol {})",
11430×
            env!("OXY_VERSION_LONG"),
11440×
            oxy_core::protocol::PROTOCOL_VERSION
11450×
        );
11460×
    }
11471×
    Ok(0)
11481×
}
1149
11502×
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
11512×
    let repo = open()?;
11522×
    if paths.is_empty() && hunks.is_empty() {
11530×
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
11542×
    }
11552×
    let mut n = 0;
11562×
    if !hunks.is_empty() {
11571×
        n += repo.discard_hunks(hunks)?;
11581×
    }
11592×
    if !paths.is_empty() {
11601×
        n += repo.discard(paths)?;
11611×
    }
11622×
    println!(
1163
        "{} {} restored to the working copy's base",
11642×
        ui::done("Discarded"),
11652×
        plural(n, "path")
1166
    );
11672×
    Ok(0)
11682×
}
1169
11702×
pub fn hunks(as_json: bool) -> Result<i32> {
11712×
    let repo = open()?;
11722×
    let (_, hunks) = repo.hunks()?;
11732×
    if as_json {
11742×
        println!(
1175
            "{}",
11765×
            json::arr(hunks.iter().map(|h| json::obj([
11775×
                ("index", json::n(h.index)),
11785×
                ("path", json::s(&h.path)),
11795×
                ("text", json::s(&h.text))
11805×
            ])))
1181
        );
11822×
        return Ok(0);
11830×
    }
11840×
    if hunks.is_empty() {
11850×
        println!(
11860×
            "{}",
11870×
            ui::dim("No hunks: the working copy matches its base.")
11880×
        );
11890×
    }
11900×
    for h in &hunks {
11910×
        println!(
1192
            "{} {}",
11930×
            ui::section(format!("hunk {}", h.index)),
11940×
            ui::path(&h.path)
1195
        );
11960×
        for line in h.text.lines() {
11970×
            let styled = if line.starts_with('+') {
11980×
                ui::ok(line)
11990×
            } else if line.starts_with('-') {
12000×
                ui::err(line)
1201
            } else {
12020×
                ui::dim(line)
1203
            };
12040×
            println!("  {styled}");
1205
        }
1206
    }
12070×
    Ok(0)
12082×
}
1209
12102×
pub fn show(change: Option<&str>, revset: Option<&str>, as_json: bool) -> Result<i32> {
12112×
    let repo = open()?;
12122×
    repo.snapshot_status("oxy show")?;
12132×
    let Some(r) = revset else {
12142×
        let h = repo.resolve_change(change.unwrap_or("@"))?;
12152×
        return show_one(&repo, h, as_json, false);
1216
    };
1217
    // Several changes: a JSON array, or the changes one after another.
12180×
    let hashes = repo.revset(r)?.hashes;
12190×
    if as_json {
12200×
        print!("[");
12210×
        for (i, h) in hashes.iter().enumerate() {
12220×
            if i > 0 {
12230×
                print!(",");
12240×
            }
12250×
            show_one(&repo, *h, true, true)?;
1226
        }
12270×
        println!("]");
12280×
        return Ok(0);
12290×
    }
12300×
    if hashes.is_empty() {
12310×
        println!("{}", ui::dim(format!("No change matches {r:?}.")));
12320×
        return Ok(0);
12330×
    }
12340×
    for (i, h) in hashes.iter().enumerate() {
12350×
        if i > 0 {
12360×
            println!();
12370×
        }
12380×
        show_one(&repo, *h, false, false)?;
1239
    }
12400×
    Ok(0)
12412×
}
1242
1243
/// One change, as `oxy show` prints it; `inline` JSON goes without its
1244
/// newline, for an array.
12452×
fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool) -> Result<i32> {
12462×
    let c = repo.store().get_change(&h)?;
12472×
    if as_json {
12481×
        let files = repo.diff_files(Some(&h))?;
12491×
        let heads = repo.bookmark_heads()?;
12501×
        let entry = oxy_core::repo::LogEntry {
12511×
            hash: h,
12521×
            change: oxy_core::state::ChangeMeta::of(&c),
12531×
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
12541×
            is_head: heads.contains(&h),
12551×
        };
12561×
        let mut body = log_entry_json(repo, &entry)?;
12571×
        body.pop();
12581×
        body.push_str(&format!(
1259
            ",{}:{}}}",
12601×
            json::s("files"),
12611×
            json::arr(files.iter().map(|f| json::obj([
12621×
                ("path", json::s(&f.path)),
12631×
                ("kind", json::s(&f.kind)),
12641×
                ("from", json::opt(f.from.as_deref(), json::s))
12651×
            ])))
1266
        ));
12671×
        if inline {
12680×
            print!("{body}");
12691×
        } else {
12701×
            println!("{body}");
12711×
        }
12721×
        return Ok(0);
12731×
    }
12741×
    println!(
1275
        "{} {} {}",
12761×
        ui::section("change"),
12771×
        ui::id(short_id(&c)),
12781×
        ui::hash(format!("#{h}"))
1279
    );
12801×
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1281
    // Fetched but not pulled (oxygen#56): say where it is.
12821×
    if let Some(at) = repo.remote_only_location(&h)? {
12830×
        println!(
12840×
            "{}",
12850×
            ui::kv(
12860×
                "only in",
12870×
                ui::warn(format!(
12880×
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
12890×
                ))
12900×
            )
12910×
        );
12921×
    }
12931×
    let meta = oxy_core::state::ChangeMeta::of(&c);
12941×
    let status = repo.authenticate_change_known(&h, Some(&meta))?;
12951×
    println!("{}", ui::kv("author", ui::author(author_name(repo, &meta))));
12961×
    if let Some(agent) = via(repo, &status, &meta.author) {
12970×
        println!("{}", ui::kv("via", agent.line()));
12981×
    }
12991×
    println!(
1300
        "{}",
13011×
        ui::kv(
13021×
            "date",
13031×
            format!(
1304
                "{} {}",
13051×
                when(c.hlc.wall_ms),
13061×
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1307
            )
1308
        )
1309
    );
13101×
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
13111×
    println!("{}", ui::kv("sig", signature_line(repo, &h)?));
13121×
    println!();
13134×
    for line in (if c.message.is_empty() {
13140×
        "(no description)"
1315
    } else {
13161×
        &c.message
1317
    })
13181×
    .lines()
13194×
    {
13204×
        println!("    {line}");
13214×
    }
13221×
    println!();
13231×
    print!("{}", repo.describe_change(&h)?);
13241×
    Ok(0)
13252×
}
1326
13270×
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
13280×
    let repo = open()?;
1329
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1330
    // BRANCH` is: checking its files out under another bookmark's name
1331
    // made the next commit move the wrong bookmark (oxygen#60).
13320×
    if let [name] = changes {
13330×
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
13340×
            drop(repo);
13350×
            return bookmark_switch(name, discard, carry);
13360×
        }
13370×
    }
13380×
    let heads = if changes.is_empty() {
13390×
        repo.bookmark_heads()?
1340
    } else {
13410×
        let mut heads = Vec::new();
13420×
        for c in changes {
13430×
            heads.extend(repo.resolve_heads(c)?);
1344
        }
13450×
        heads
1346
    };
13470×
    let spec = if changes.is_empty() {
13480×
        repo.config.bookmark.clone()
1349
    } else {
13500×
        changes.join(" ")
1351
    };
13520×
    let sp = ui::spinner(&format!("Checking out {spec}…"));
13530×
    let command = format!("oxy checkout {spec}");
13540×
    let (r, carried) = if carry {
13550×
        repo.checkout_carry(&heads, &spec, &command)?
1356
    } else {
13570×
        (repo.checkout(&heads, discard, &command)?, vec![])
1358
    };
13590×
    sp.done(&format!(
1360
        "{} on {}: {} written, {} removed{}",
13610×
        ui::done("Working copy"),
13620×
        ui::bookmark(&spec),
13630×
        plural(r.written, "file"),
1364
        r.removed,
13650×
        if carried.is_empty() {
13660×
            String::new()
1367
        } else {
13680×
            format!("; carried {}", plural(carried.len(), "changed path"))
1369
        }
1370
    ));
13710×
    print_removed(&r);
13720×
    for n in &r.notes {
13730×
        println!("  {} {n}", ui::note());
13740×
    }
13750×
    if r.conflicted {
13760×
        println!(
13770×
            "  {} {}",
13780×
            ui::caution(),
13790×
            ui::warn("this state has conflicts; see oxy status")
13800×
        );
13810×
    }
13820×
    where_now(&repo);
13830×
    Ok(0)
13840×
}
1385
13861×
pub fn resolve(as_json: bool) -> Result<i32> {
13871×
    let repo = open()?;
13881×
    let snap = repo.snapshot("oxy resolve")?;
13891×
    if as_json {
13901×
        println!("{}", repo.status_json(&snap)?);
13911×
        return Ok(if snap.base_snapshot.is_conflicted() {
13920×
            2
1393
        } else {
13941×
            0
1395
        });
13960×
    }
13970×
    if !snap.base_snapshot.is_conflicted() {
13980×
        println!("The working copy's base has no conflicts.");
13990×
        return Ok(0);
14000×
    }
14010×
    let mut remaining = 0;
14020×
    for (p, f) in &snap.base_snapshot.files {
14030×
        if !f.is_conflicted() {
14040×
            continue;
14050×
        }
14060×
        match snap
14070×
            .statuses
14080×
            .iter()
14090×
            .find(|s| s.path == *p)
14100×
            .map(|s| s.status)
1411
        {
14120×
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
14130×
            Some(ChangeStatus::ConflictEdited) => {
14140×
                remaining += 1;
14150×
                println!("markers    {p}");
14160×
            }
14170×
            _ => {
14180×
                remaining += 1;
14190×
                println!("unresolved {p}");
14200×
            }
1421
        }
1422
    }
14230×
    for c in &snap.base_snapshot.tree.conflicts {
14240×
        remaining += 1;
14250×
        println!("tree       {c:?}");
14260×
    }
14270×
    if remaining == 0 {
14280×
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
14290×
        Ok(0)
1430
    } else {
14310×
        Ok(2)
1432
    }
14331×
}
1434
14350×
pub fn undo() -> Result<i32> {
14360×
    let repo = open()?;
14370×
    let u = repo.undo()?;
14380×
    println!("{} {}", ui::done("Undone:"), u.command);
14390×
    for c in &u.changes {
14400×
        println!("  {} {}", ui::note(), change_words(&repo, c));
14410×
    }
14420×
    if u.others_kept > 0 {
14430×
        let s = if u.others_kept == 1 { "" } else { "s" };
14440×
        println!(
1445
            "  {} {}",
14460×
            ui::note(),
14470×
            ui::dim(format!(
1448
                "{} newer operation{s} from other workspaces left as they are",
1449
                u.others_kept
1450
            ))
1451
        );
14520×
    }
14530×
    for (bookmark, remote) in &u.pushed {
14540×
        println!(
14550×
            "  {} {}",
14560×
            ui::caution(),
14570×
            ui::warn(format!(
14580×
                "{remote}/{bookmark} already has what this undid: undone here only; the next push of {bookmark} needs --force to take it back there"
14590×
            ))
14600×
        );
14610×
    }
14620×
    where_now(&repo);
14630×
    Ok(0)
14640×
}
1465
14661×
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
14671×
    let repo = open()?;
14681×
    let ops = repo.op_log()?;
1469
    // What each operation changed, against the one before it.
147011×
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
147111×
        match ops.get(i + 1) {
147210×
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
14731×
            None => Ok(vec![]),
1474
        }
147511×
    };
14761×
    if as_json {
14771×
        let mut items = Vec::new();
147811×
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
147911×
            let summary: Vec<String> = changes_of(i)?
148011×
                .iter()
148111×
                .map(|c| change_words(&repo, c))
148211×
                .collect();
148311×
            items.push(json::obj([
148411×
                ("id", json::s(&r.to_hex())),
148511×
                ("when_ms", json::n(op.hlc.wall_ms)),
148611×
                ("command", json::s(&op.command)),
148711×
                ("snapshot", json::b(op.is_snapshot())),
148811×
                ("current", json::b(i == 0)),
148911×
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1490
            ]));
1491
        }
14921×
        println!("{}", json::arr(items));
14931×
        return Ok(0);
14940×
    }
14950×
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
14960×
    let id = |r: &oxy_core::hash::ObjectRef| {
14970×
        let hex = r.to_hex();
14980×
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
14990×
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
15000×
    };
15010×
    let rail = ui::dim(ui::glyph("│", "|"));
15020×
    let (mut i, mut shown) = (0, 0);
15030×
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
15040×
        let (r, op) = &ops[i];
15050×
        let bullet = if i == 0 {
15060×
            ui::ok(ui::glyph("@", "@"))
1507
        } else {
15080×
            ui::dim(ui::glyph("○", "o"))
1509
        };
1510
        // A run of snapshots folds into one entry.
15110×
        let mut run = 1;
15120×
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
15130×
            run += 1;
15140×
        }
15150×
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
15160×
        if op.is_snapshot() {
15170×
            let span = if run > 1 {
15180×
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1519
            } else {
15200×
                String::new()
1521
            };
15220×
            println!(
1523
                "{bullet}  {}{} {when}",
15240×
                id(r),
15250×
                if span.is_empty() {
15260×
                    String::new()
1527
                } else {
15280×
                    format!(" {span}")
1529
                }
1530
            );
15310×
            println!(
1532
                "{rail}  {}",
15330×
                ui::dim(if run == 1 {
15340×
                    "working-copy snapshot".to_string()
1535
                } else {
15360×
                    format!("{run} working-copy snapshots")
1537
                })
1538
            );
1539
        } else {
15400×
            println!("{bullet}  {} {when}", id(r));
15410×
            let words: Vec<String> = changes_of(i)?
15420×
                .iter()
15430×
                .map(|c| change_words(&repo, c))
15440×
                .collect();
15450×
            let summary = if words.is_empty() {
15460×
                if i + 1 == ops.len() {
15470×
                    "created the repository".to_string()
1548
                } else {
15490×
                    "no bookmark or working-copy change".to_string()
1550
                }
1551
            } else {
15520×
                words.join("; ")
1553
            };
15540×
            println!(
1555
                "{rail}  {}",
15560×
                if i == 0 {
15570×
                    ui::subject(&summary)
1558
                } else {
15590×
                    summary
1560
                }
1561
            );
15620×
            let cmd = op.command.lines().next().unwrap_or("");
15630×
            let cmd: String = cmd.chars().take(100).collect();
15640×
            println!("{rail}  {}", ui::dim(cmd));
1565
        }
15660×
        i += run;
15670×
        shown += 1;
1568
    }
15690×
    if i < ops.len() {
15700×
        println!(
15710×
            "{}",
15720×
            ui::dim(format!(
15730×
                "{} {} older; pass -n to see more",
15740×
                ui::glyph("…", "..."),
15750×
                plural(ops.len() - i, "operation")
15760×
            ))
15770×
        );
15780×
    }
15790×
    Ok(0)
15801×
}
1581
1582
/// One change an operation made, in words.
158311×
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1584
    use oxy_core::repo::ViewChange::*;
15852×
    match c {
15860×
        BookmarkCreated { name, heads } => {
15870×
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1588
        }
15890×
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
15902×
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
15911×
        BookmarkMoved { name, from, to } => format!(
1592
            "{name}: {from} {} {}",
15931×
            ui::glyph("→", "->"),
15941×
            plural(*to, "head")
1595
        ),
15961×
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
15970×
        TagCreated { name } => format!("tagged {name}"),
15980×
        TagDeleted { name } => format!("removed tag {name}"),
15990×
        Policy => "trust policy changed".to_string(),
16008×
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
16018×
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
16020×
            Err(_) => "working copy moved".to_string(),
1603
        },
1604
    }
160511×
}
1606
16070×
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
16080×
    let repo = open()?;
16090×
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
16100×
    let r = repo.op_restore(op, discard)?;
16110×
    sp.done(&format!(
16120×
        "{} to operation {} {}",
16130×
        ui::done("Restored"),
16140×
        ui::hash(r.op.short(12)),
16150×
        ui::dim(r.command.lines().next().unwrap_or(""))
16160×
    ));
16170×
    println!(
1618
        "  {} {}",
16190×
        ui::note(),
16200×
        ui::dim(format!(
1621
            "{} written, {} removed; oxy undo goes back again",
16220×
            plural(r.checkout.written, "file"),
1623
            r.checkout.removed
1624
        ))
1625
    );
16260×
    where_now(&repo);
16270×
    Ok(0)
16280×
}
1629
16300×
pub fn op_revert(op: &str) -> Result<i32> {
16310×
    let repo = open()?;
16320×
    let r = repo.op_revert(op)?;
16330×
    let view = repo.view()?;
16340×
    let names: Vec<String> = r
16350×
        .reverted
16360×
        .iter()
16370×
        .map(|n| {
16380×
            if view.bookmarks.contains_key(n) {
16390×
                ui::bookmark(n)
1640
            } else {
16410×
                format!("{} (removed)", ui::bookmark(n))
1642
            }
16430×
        })
16440×
        .collect();
16450×
    println!(
1646
        "{} operation {} {}",
16470×
        ui::done("Reverted"),
16480×
        ui::hash(r.op.short(12)),
16490×
        ui::dim(r.command.lines().next().unwrap_or(""))
1650
    );
16510×
    println!(
1652
        "  {} {}",
16530×
        ui::note(),
16540×
        ui::dim(format!("as before it: {}", names.join(", ")))
1655
    );
16560×
    if !r.kept.is_empty() {
16570×
        println!(
16580×
            "  {} {}",
16590×
            ui::caution(),
16600×
            ui::warn(format!(
16610×
                "left as they are, having moved again since: {}",
16620×
                r.kept.join(", ")
16630×
            ))
16640×
        );
16650×
    }
16660×
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
16670×
        println!(
16680×
            "  {} {}",
16690×
            ui::note(),
16700×
            ui::dim("the working copy has work of its own: oxy checkout to move it")
16710×
        );
16720×
    }
16730×
    where_now(&repo);
16740×
    Ok(0)
16750×
}
1676
1677
/// Where the working copy and bookmark are now, after a command moved
1678
/// them (as jj says "Working copy now at").
167931×
pub fn where_now(repo: &Repo) {
168031×
    let Ok((_, wc)) = repo.working_copy() else {
16810×
        return;
1682
    };
168331×
    let heads = repo.bookmark_heads().unwrap_or_default();
168431×
    let newest = heads
168531×
        .iter()
168643×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
168731×
        .max_by_key(|(m, _)| m.hlc);
168831×
    println!(
1689
        "  {} {}",
169031×
        ui::dim(format!("{:<13}", "Working copy")),
169131×
        ui::id(wc.change_id.short(8))
1692
    );
169331×
    let tail = match newest {
169431×
        Some((m, _)) => format!(
1695
            ", newest {} {}",
169631×
            ui::id(m.change_id.short(8)),
169731×
            subject_of(&m.message)
1698
        ),
16990×
        None => String::new(),
1700
    };
170131×
    println!(
1702
        "  {} {}: {}{tail}",
170331×
        ui::dim(format!("{:<13}", "Bookmark")),
170431×
        ui::bookmark(&repo.config.bookmark),
170531×
        plural(heads.len(), "head")
1706
    );
170731×
}
1708
17090×
pub fn gc(now: bool, expire_snapshots: bool) -> Result<i32> {
17100×
    let mut repo = open()?;
17110×
    if expire_snapshots {
17120×
        repo.config.snapshot_retention_days = 0;
17130×
    }
17140×
    let sp = ui::spinner("Packing and pruning…");
17150×
    let r = repo.gc_with(now, &mut |phase| sp.set(&format!("{phase}…")))?;
17160×
    sp.clear();
17170×
    if r.packed.objects > 0 {
17180×
        println!(
17190×
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
17200×
            plural(r.packed.objects, "object"),
17210×
            r.packed.raw_bytes,
17220×
            r.packed.packed_bytes,
17230×
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
17240×
        );
17250×
    }
17260×
    println!(
1727
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
17280×
        plural(r.reachable, "object"),
17290×
        plural(r.pruned.objects, "unreachable object"),
1730
        r.pruned.bytes,
17310×
        if r.pruned.deferred > 0 {
17320×
            format!(
1733
                "; {} deferred by the grace period (use --now)",
17340×
                plural(r.pruned.deferred, "object")
1735
            )
1736
        } else {
17370×
            String::new()
1738
        },
17390×
        if r.merged_packs > 0 {
17400×
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1741
        } else {
17420×
            String::new()
1743
        },
17440×
        plural(repo.store().pack_count(), "pack")
1745
    );
1746
    // What earlier repacks replaced stays an hour for readers still using
1747
    // it (oxygenhub#249); a collection after that deletes it.
17480×
    let kept = if r.retired.kept > 0 {
17490×
        format!(
1750
            "{} retired less than an hour ago kept for readers",
17510×
            plural(r.retired.kept, "file")
1752
        )
1753
    } else {
17540×
        String::new()
1755
    };
17560×
    if r.retired.packs + r.retired.loose > 0 {
17570×
        println!(
1758
            "Deleted {} and {} retired by earlier repacks{}.",
17590×
            plural(r.retired.packs, "pack"),
17600×
            plural(r.retired.loose, "loose object"),
17610×
            if kept.is_empty() {
17620×
                String::new()
1763
            } else {
17640×
                format!("; {kept}")
1765
            }
1766
        );
17670×
    } else if !kept.is_empty() {
17680×
        println!("{kept}.");
17690×
    }
17700×
    Ok(0)
17710×
}
1772
1773
/// `oxy gc --remote NAME`: fold a store remote's bundles into one.
17742×
pub fn gc_remote(name: &str, now: bool) -> Result<i32> {
17752×
    let repo = open()?;
17762×
    let sp = ui::spinner(&format!("Folding {name}'s bundles…"));
17772×
    let r = repo.gc_remote(name, now)?;
17781×
    sp.clear();
17791×
    if r.merged > 0 {
17801×
        println!(
17811×
            "{} {} into one of {} bytes ({})",
17821×
            ui::done("Folded"),
17831×
            plural(r.merged, "bundle"),
17841×
            r.bundle_bytes,
17851×
            plural(r.changes, "change")
17861×
        );
17871×
    } else {
17880×
        println!(
17890×
            "{} {}",
17900×
            ui::note(),
17910×
            ui::dim("nothing to fold: one bundle holds everything")
17920×
        );
17930×
    }
17941×
    println!(
1795
        "  {} {}",
17961×
        ui::note(),
17971×
        ui::dim(format!(
1798
            "removed {}{}",
17991×
            plural(r.deleted, "superseded bundle"),
18001×
            if r.deferred > 0 {
18010×
                format!(
1802
                    "; {} kept for readers that may still fetch them (use --now)",
18030×
                    plural(r.deferred, "bundle")
1804
                )
1805
            } else {
18061×
                String::new()
1807
            }
1808
        ))
1809
    );
18101×
    Ok(0)
18112×
}
1812
1813
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
18140×
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1815
    use oxy_core::repo::Health;
18160×
    let repo = open()?;
18170×
    let sp = ui::spinner(if offline {
18180×
        "Checking…"
1819
    } else {
18200×
        "Checking, and contacting remotes…"
1821
    });
18220×
    let r = repo.doctor(!offline);
18230×
    sp.clear();
18240×
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
18250×
    let word = |h: Health| match h {
18260×
        Health::Ok => "ok",
18270×
        Health::Warn => "warning",
18280×
        Health::Fail => "fail",
18290×
    };
18300×
    if as_json {
18310×
        let checks: Vec<String> = r
18320×
            .checks
18330×
            .iter()
18340×
            .map(|c| {
18350×
                json::obj([
18360×
                    ("area", json::s(&c.area)),
18370×
                    ("health", json::s(word(c.health))),
18380×
                    ("message", json::s(&c.message)),
18390×
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
18400×
                ])
18410×
            })
18420×
            .collect();
18430×
        println!(
1844
            "{}",
18450×
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1846
        );
18470×
        return Ok(code);
18480×
    }
18490×
    let mut last = "";
18500×
    for c in &r.checks {
18510×
        if c.area != last {
18520×
            println!("{}", ui::section(&c.area));
18530×
            last = &c.area;
18540×
        }
18550×
        let mark = match c.health {
18560×
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
18570×
            Health::Warn => ui::caution(),
18580×
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1859
        };
18600×
        println!("  {mark} {}", c.message);
18610×
        if let Some(h) = &c.hint {
18620×
            println!("    {} {}", ui::dim("→"), ui::dim(h));
18630×
        }
1864
    }
18650×
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
18660×
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
18670×
    if fails + warns == 0 {
18680×
        println!("{}", ui::done("Everything looks right."));
18690×
    } else {
18700×
        println!(
1871
            "{} {}, {}.",
18720×
            if fails > 0 {
18730×
                ui::err(ui::glyph("✖", "x"))
1874
            } else {
18750×
                ui::caution()
1876
            },
18770×
            plural(fails, "problem"),
18780×
            plural(warns, "warning")
1879
        );
1880
    }
18810×
    Ok(code)
18820×
}
1883
1884
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
18850×
pub fn fsck(as_json: bool) -> Result<i32> {
1886
    use oxy_core::repo::Severity;
18870×
    let repo = open()?;
18880×
    let sp = ui::spinner("Checking every object…");
18890×
    let r = repo.fsck()?;
18900×
    sp.clear();
18910×
    let code = if r.errors() > 0 { 1 } else { 0 };
18920×
    if as_json {
18930×
        let problems: Vec<String> = r
18940×
            .problems
18950×
            .iter()
18960×
            .map(|p| {
18970×
                json::obj([
1898
                    (
1899
                        "severity",
19000×
                        json::s(match p.severity {
19010×
                            Severity::Error => "error",
19020×
                            Severity::Warning => "warning",
1903
                        }),
1904
                    ),
1905
                    (
19060×
                        "object",
19070×
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1908
                    ),
19090×
                    ("what", json::s(&p.what)),
1910
                ])
19110×
            })
19120×
            .collect();
19130×
        println!(
1914
            "{}",
19150×
            json::obj([
19160×
                ("ok", json::b(code == 0)),
19170×
                ("objects", json::n(r.objects)),
19180×
                ("ops", json::n(r.ops)),
19190×
                ("changes", json::n(r.changes)),
19200×
                ("signed", json::n(r.signed)),
19210×
                ("unsigned", json::n(r.unsigned)),
19220×
                ("checkpoints", json::n(r.checkpoints)),
19230×
                ("attestations", json::n(r.attestations)),
19240×
                ("errors", json::n(r.errors())),
19250×
                ("warnings", json::n(r.warnings())),
19260×
                ("problems", json::arr(problems)),
19270×
            ])
1928
        );
19290×
        return Ok(code);
19300×
    }
19310×
    println!(
1932
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
19330×
        plural(r.objects, "object"),
19340×
        plural(r.ops, "operation"),
19350×
        plural(r.changes, "change"),
1936
        r.signed,
1937
        r.unsigned,
19380×
        plural(r.checkpoints, "checkpoint"),
19390×
        plural(r.attestations, "attestation"),
1940
    );
19410×
    for p in &r.problems {
19420×
        let obj = p
19430×
            .object
19440×
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
19450×
            .unwrap_or_default();
19460×
        match p.severity {
19470×
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
19480×
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1949
        }
1950
    }
19510×
    if r.problems.is_empty() {
19520×
        println!("{}", ui::done("No problems found."));
19530×
    } else if code == 0 {
19540×
        println!(
19550×
            "{}",
19560×
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
19570×
        );
19580×
    } else {
19590×
        println!(
19600×
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
19610×
            ui::err(ui::glyph("✖", "x")),
19620×
            plural(r.errors(), "error"),
19630×
            plural(r.warnings(), "warning")
19640×
        );
19650×
    }
19660×
    Ok(code)
19670×
}
1968
1969
/// The head the working copy sits on, for commands that default to it. With
1970
/// several heads beneath the working copy, the most recently made one is
1971
/// chosen and announced.
19720×
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
19730×
    let snap = repo.snapshot_status("oxy")?;
19740×
    let base = snap.base.maximal(&snap.wc.deps);
19750×
    match base.as_slice() {
19760×
        [] => anyhow::bail!("the working copy sits on no change yet"),
19770×
        [h] => Ok(*h),
19780×
        many => {
19790×
            let latest = many
19800×
                .iter()
19810×
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
19820×
                .copied()
19830×
                .unwrap();
19840×
            let c = repo.store().get_change(&latest)?;
19850×
            println!(
1986
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
19870×
                short_id(&c),
19880×
                latest.short(12),
19890×
                many.len()
1990
            );
19910×
            Ok(latest)
1992
        }
1993
    }
19940×
}
1995
1996
/// `oxy describe` without -m: the working copy's name for a build.
19974×
pub fn describe_name(as_json: bool) -> Result<i32> {
19984×
    let repo = open()?;
19994×
    let d = repo.describe_working_copy()?;
20004×
    if as_json {
20013×
        println!(
2002
            "{}",
20033×
            json::obj([
20043×
                ("describe", json::s(&d.line())),
20053×
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
20063×
                ("distance", json::n(d.distance)),
20073×
                ("bookmark", json::s(&d.bookmark)),
20083×
                ("change", json::s(&d.change.to_hex())),
20093×
                ("hash", json::s(&d.hash.to_hex())),
20103×
                ("dirty", json::b(d.dirty)),
2011
            ])
2012
        );
20131×
    } else {
20141×
        println!("{}", d.line());
20151×
    }
20164×
    Ok(0)
20174×
}
2018
20190×
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
20200×
    let repo = open()?;
20210×
    let h = match change {
20220×
        Some(c) => repo.resolve_change(c)?,
20230×
        None => current_head(&repo)?,
2024
    };
20250×
    let new = repo.describe(&h, message)?;
20260×
    let c = repo.store().get_change_meta(&new)?;
20270×
    println!(
2028
        "{} {} {}  {}",
20290×
        ui::done("Described"),
20300×
        ui::id(c.change_id.short(8)),
20310×
        ui::hash(format!("#{}", new.short(12))),
20320×
        ui::subject(subject_of(message))
2033
    );
20340×
    Ok(0)
20350×
}
2036
20370×
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
20380×
    let repo = open()?;
20390×
    let before = repo.view()?;
20400×
    let new = match into {
20410×
        Some(spec) => {
20420×
            let target = repo.resolve_change(spec)?;
20430×
            repo.amend_into(&target, message)?
2044
        }
20450×
        None => repo.amend(message)?,
2046
    };
20470×
    let c = repo.store().get_change_meta(&new)?;
20480×
    println!(
2049
        "{} {} {}  {}",
20500×
        ui::done("Amended"),
20510×
        ui::id(c.change_id.short(8)),
20520×
        ui::hash(format!("#{}", new.short(12))),
20530×
        ui::subject(subject_of(&c.message))
2054
    );
2055
    // Rewriting what a remote already has means the next push replaces it
2056
    // there (oxygen#99): say so now, not when the push is refused.
20570×
    let bookmark = repo.config.bookmark.clone();
20580×
    let (had, has) = (
20590×
        repo.heads_of(&before, &bookmark)?,
20600×
        repo.heads_of(&repo.view()?, &bookmark)?,
2061
    );
20620×
    for (remote, bookmarks) in &before.remotes {
20630×
        let Some(st) = bookmarks.get(&bookmark) else {
20640×
            continue;
2065
        };
20660×
        let theirs = repo.store().get_state(st)?.heads;
20670×
        if theirs.iter().any(|h| had.contains(h) && !has.contains(h)) {
20680×
            println!(
20690×
                "  {} {}",
20700×
                ui::caution(),
20710×
                ui::warn(format!(
20720×
                    "{remote}/{bookmark} has the change as it was: the next push of {bookmark} needs --force to replace it"
20730×
                ))
20740×
            );
20750×
        }
2076
    }
20770×
    where_now(&repo);
20780×
    Ok(0)
20790×
}
2080
20810×
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
20820×
    let repo = open()?;
20830×
    let Some(r) = revset else {
20840×
        let h = repo.resolve_change(change.unwrap_or_default())?;
20850×
        abandon_one(&repo, h)?;
20860×
        where_now(&repo);
20870×
        return Ok(0);
2088
    };
2089
    // A revset: say what it selects, refuse an empty set, ask above a few.
20900×
    let selected = repo.revset(r)?;
20910×
    let wc = repo.working_copy().ok().map(|(h, _)| h);
20920×
    let hashes: Vec<ChangeHash> = selected
20930×
        .hashes
20940×
        .iter()
20950×
        .copied()
20960×
        .filter(|h| Some(*h) != wc)
20970×
        .collect();
20980×
    if hashes.is_empty() {
20990×
        anyhow::bail!("{r:?} selects no change to abandon");
21000×
    }
21010×
    println!(
2102
        "{} {} selects {}:",
21030×
        ui::section("abandon"),
21040×
        ui::id(r),
21050×
        plural(hashes.len(), "change")
2106
    );
21070×
    for h in &hashes {
21080×
        if let Some(m) = selected.metas.get(h) {
21090×
            println!(
21100×
                "  {} {}  {}",
21110×
                ui::id(m.change_id.short(8)),
21120×
                ui::hash(format!("#{}", h.short(12))),
21130×
                subject_of(&m.message)
21140×
            );
21150×
        }
2116
    }
2117
    const ASK_ABOVE: usize = 5;
21180×
    if hashes.len() > ASK_ABOVE && !yes {
21190×
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
21200×
    }
2121
    // Newest first: abandoning a change rewrites what depends on it, so a
2122
    // later member is found again by its ChangeId.
21230×
    let mut done = 0;
21240×
    for h in &hashes {
21250×
        let Some(m) = selected.metas.get(h) else {
21260×
            continue;
2127
        };
21280×
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
21290×
            Ok(h) => h,
21300×
            Err(_) => continue,
2131
        };
21320×
        abandon_one(&repo, now)?;
21330×
        done += 1;
2134
    }
21350×
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
21360×
    where_now(&repo);
21370×
    Ok(0)
21380×
}
2139
21400×
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
21410×
    let c = repo.store().get_change_meta(&h)?;
21420×
    let notes = repo.abandon(&h)?;
21430×
    println!(
2144
        "{} {} {}  {}",
21450×
        ui::done("Abandoned"),
21460×
        ui::id(c.change_id.short(8)),
21470×
        ui::hash(format!("#{}", h.short(12))),
21480×
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
2149
    );
21500×
    for n in notes {
21510×
        println!("  {} {n}", ui::note());
21520×
    }
21530×
    Ok(())
21540×
}
2155
21560×
pub fn checkpoint() -> Result<i32> {
21570×
    let repo = open()?;
21580×
    let sp = ui::spinner("Writing checkpoint…");
21590×
    let (r, changes, bytes) = repo.checkpoint()?;
21600×
    sp.done(&format!(
21610×
        "{} {} of {} ({} bytes) for {}",
21620×
        ui::done("Checkpoint"),
21630×
        ui::hash(format!("#{}", r.short(12))),
21640×
        plural(changes, "change"),
21650×
        bytes,
21660×
        ui::id(&repo.config.bookmark)
21670×
    ));
21680×
    Ok(0)
21690×
}
2170
2171
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
21720×
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
21730×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
21740×
        return Ok(1);
2175
    };
21760×
    let info = repo.quick_status()?;
21770×
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
21780×
        oxy_core::repo::GLYPH_PROMPT_FORMAT
2179
    } else {
21800×
        format
2181
    };
21820×
    let line = match color {
21830×
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
21840×
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
21850×
        Some(_) => info.format_colored(fmt, ("", "")),
21860×
        None => info.format(fmt),
2187
    };
21880×
    println!("{line}");
21890×
    Ok(0)
21900×
}
2191
21920×
pub fn sparse(paths: &[String]) -> Result<i32> {
21930×
    let mut repo = open()?;
21940×
    if paths.is_empty() {
21950×
        if repo.config.sparse_paths.is_empty() {
21960×
            println!("No sparse filter: the whole tree is materialized.");
21970×
        } else {
21980×
            println!("{}", ui::heading("Sparse filter"));
21990×
            for p in &repo.config.sparse_paths {
22000×
                println!("  {}", ui::path(p));
22010×
            }
2202
        }
22030×
        return Ok(0);
22040×
    }
22050×
    let snap = repo.snapshot("oxy sparse")?;
22060×
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
22070×
        anyhow::bail!(
2208
            "the working copy has changes; commit them before changing the sparse filter"
2209
        );
22100×
    }
22110×
    repo.config.set("filter.paths", &paths.join(","))?;
22120×
    repo.save_config()?;
22130×
    let heads = repo.bookmark_heads()?;
22140×
    let sp = ui::spinner("Re-checking out with the new filter…");
22150×
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
22160×
    sp.done(&format!(
22170×
        "{} {}: {} written, {} removed",
22180×
        ui::done("Sparse filter set to"),
22190×
        ui::path(paths.join(",")),
22200×
        plural(r.written, "file"),
22210×
        r.removed
22220×
    ));
22230×
    Ok(0)
22240×
}
2225
22262×
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
22272×
    let repo = open()?;
22282×
    repo.snapshot_status("oxy tag")?;
22292×
    let heads = if changes.is_empty() {
22302×
        repo.bookmark_heads()?
2231
    } else {
22320×
        let mut heads = Vec::new();
22330×
        for c in changes {
22340×
            heads.extend(repo.resolve_heads(c)?);
2235
        }
22360×
        heads
2237
    };
22382×
    let t = repo.tag_create(name, &heads, message)?;
22392×
    println!(
2240
        "{} {} {} {} ({}){}",
22412×
        ui::done("Tagged"),
22422×
        ui::bookmark(&t.name),
22432×
        ui::dim(ui::glyph("→", "->")),
22442×
        ui::hash(format!("#{}", t.state.short(12))),
22452×
        plural(t.heads.len(), "head"),
22462×
        t.signer
22472×
            .map(|s| format!(", signed by {s}"))
22482×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2249
    );
22502×
    Ok(0)
22512×
}
2252
22531×
pub fn tag_list(as_json: bool) -> Result<i32> {
22541×
    let repo = open()?;
22551×
    let tags = repo.tags()?;
22561×
    if as_json {
22571×
        println!(
2258
            "{}",
22591×
            json::arr(tags.iter().map(|t| {
22601×
                json::obj([
22611×
                    ("name", json::s(&t.name)),
22621×
                    ("state", json::s(&t.state.to_hex())),
22631×
                    ("heads", json::hashes(&t.heads)),
22641×
                    ("message", json::s(&t.message)),
2265
                    (
22661×
                        "signer",
22671×
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2268
                    ),
2269
                ])
22701×
            }))
2271
        );
22721×
        return Ok(0);
22730×
    }
22740×
    if tags.is_empty() {
22750×
        println!("{}", ui::dim("No tags."));
22760×
    }
22770×
    for t in tags {
22780×
        println!(
2279
            "{} {} {}{}{}{}",
22800×
            ui::ok(ui::glyph("⚑", "#")),
22810×
            ui::bookmark(&t.name),
2282
            // The heads, as `oxy log` shows changes, not the state hash.
22830×
            ui::hash(
22840×
                t.heads
22850×
                    .iter()
22860×
                    .map(|h| format!("#{}", h.short(12)))
22870×
                    .collect::<Vec<_>>()
22880×
                    .join(" ")
2289
            ),
22900×
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
22910×
            if t.message.is_empty() {
22920×
                String::new()
2293
            } else {
22940×
                format!("  {}", ui::subject(subject_of(&t.message)))
2295
            },
22960×
            t.signer
22970×
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
22980×
                .unwrap_or_default()
2299
        );
2300
    }
23010×
    Ok(0)
23021×
}
2303
2304
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2305
/// and workspace add take as "be on this bookmark" (oxygen#60).
23060×
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
23070×
    Ok(repo.view()?.bookmarks.contains_key(name)
23080×
        || repo
23090×
            .remote_only_bookmarks()?
23100×
            .iter()
23110×
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
23120×
}
2313
23140×
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
23150×
    let repo = open()?;
2316
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2317
    // this workspace's bookmark with that one's files.
23180×
    if let [name] = changes {
23190×
        if names_bookmark(&repo, name)? {
23200×
            let (local, _) = repo.local_bookmark_for(name)?;
23210×
            let heads = repo.resolve_heads(&local)?;
23220×
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
23230×
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
23240×
            sp.done(&format!(
23250×
                "{} {} (workspace {}) on {}",
23260×
                ui::done("Workspace created at"),
23270×
                ui::path(ws.root().display()),
23280×
                ui::id(ws.workspace().short(8)),
23290×
                ui::bookmark(&local)
23300×
            ));
23310×
            return Ok(0);
23320×
        }
23330×
    }
23340×
    let heads = if changes.is_empty() {
23350×
        None
2336
    } else {
23370×
        let mut heads = Vec::new();
23380×
        for c in changes {
23390×
            heads.extend(repo.resolve_heads(c)?);
2340
        }
23410×
        Some(heads)
2342
    };
23430×
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
23440×
    let ws = repo.workspace_add(path, heads.as_deref())?;
23450×
    sp.done(&format!(
23460×
        "{} {} (workspace {})",
23470×
        ui::done("Workspace created at"),
23480×
        ui::path(ws.root().display()),
23490×
        ui::id(ws.workspace().short(8))
23500×
    ));
23510×
    Ok(0)
23520×
}
2353
23541×
pub fn workspace_list(as_json: bool) -> Result<i32> {
23551×
    let repo = open()?;
23561×
    if as_json {
23571×
        println!(
2358
            "{}",
23591×
            json::arr(repo.workspaces()?.iter().map(|w| {
23601×
                json::obj([
23611×
                    ("id", json::s(&w.id.to_hex())),
23621×
                    ("path", json::s(&w.path.to_string_lossy())),
23631×
                    ("current", json::b(w.current)),
2364
                    (
23651×
                        "working_copy",
23661×
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2367
                    ),
2368
                ])
23691×
            }))
2370
        );
23711×
        return Ok(0);
23720×
    }
23730×
    for w in repo.workspaces()? {
23740×
        println!(
2375
            "{} {} {}{}",
23760×
            if w.current {
23770×
                ui::ok(ui::glyph("●", "*"))
2378
            } else {
23790×
                ui::dim(ui::glyph("○", "o"))
2380
            },
23810×
            ui::id(w.id.short(8)),
23820×
            ui::path(w.path.display()),
23830×
            w.working_copy
23840×
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
23850×
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2386
        );
2387
    }
23880×
    Ok(0)
23891×
}
2390
23910×
pub fn workspace_forget(spec: &str) -> Result<i32> {
23920×
    let repo = open()?;
23930×
    let all = repo.workspaces()?;
23940×
    let target = std::fs::canonicalize(spec).ok();
23950×
    let matches: Vec<_> = all
23960×
        .iter()
23970×
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
23980×
        .collect();
23990×
    let w = match matches.as_slice() {
24000×
        [w] => *w,
24010×
        [] => anyhow::bail!("no workspace matches {spec:?}"),
24020×
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2403
    };
24040×
    repo.workspace_forget(&w.id)?;
24050×
    println!(
2406
        "{} workspace {} at {}; its files were left in place.",
24070×
        ui::done("Forgot"),
24080×
        ui::id(w.id.short(8)),
24090×
        ui::path(w.path.display())
2410
    );
24110×
    Ok(0)
24120×
}
2413
24140×
pub fn lock(path: &str) -> Result<i32> {
24150×
    let repo = open()?;
24160×
    repo.lock_path(path)?;
24170×
    println!(
2418
        "{} {} {}",
24190×
        ui::done("Locked"),
24200×
        ui::path(path),
24210×
        ui::dim("(advisory, local)")
2422
    );
24230×
    Ok(0)
24240×
}
2425
24260×
pub fn unlock(path: &str) -> Result<i32> {
24270×
    let repo = open()?;
24280×
    repo.unlock_path(path)?;
24290×
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
24300×
    Ok(0)
24310×
}
2432
24330×
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
24340×
    let repo = open()?;
24350×
    let h = repo.resolve_change(change)?;
24360×
    let (h1, h2) = repo.split(&h, paths)?;
24370×
    let c1 = repo.store().get_change_meta(&h1)?;
24380×
    let c2 = repo.store().get_change_meta(&h2)?;
24390×
    println!(
2440
        "{} into {} {} and {} {}",
24410×
        ui::done("Split"),
24420×
        ui::id(c1.change_id.short(8)),
24430×
        ui::hash(format!("#{}", h1.short(12))),
24440×
        ui::id(c2.change_id.short(8)),
24450×
        ui::hash(format!("#{}", h2.short(12)))
2446
    );
24470×
    Ok(0)
24480×
}
2449
24506×
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
24516×
    let mut heads = Vec::new();
24526×
    for c in changes {
24536×
        heads.extend(repo.resolve_heads(c)?);
2454
    }
24556×
    Ok(heads)
24566×
}
2457
24586×
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
24596×
    let repo = open()?;
24606×
    repo.snapshot_status("oxy bookmark create")?;
24616×
    let heads = if changes.is_empty() {
24623×
        None
2463
    } else {
24643×
        let named = heads_from(&repo, changes)?;
24653×
        let (_, wc) = repo.working_copy()?;
24663×
        let gap = repo.state_gap(&wc.deps, &named)?;
24673×
        if upto {
24681×
            Some(gap.upto)
24692×
        } else if only || gap.earlier.is_empty() {
24701×
            Some(named)
2471
        } else {
24721×
            anyhow::bail!(
2473
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2474
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2475
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2476
                 or --only for just {0} and what it depends on.",
24771×
                changes.join(" "),
24781×
                plural(gap.earlier.len(), "change"),
24791×
                listed_changes(&repo, &gap.earlier)
2480
            );
2481
        }
2482
    };
24835×
    let heads = repo.bookmark_create(name, heads.as_deref())?;
24845×
    println!(
2485
        "{} bookmark {} {} {}",
24865×
        ui::done("Created"),
24875×
        ui::bookmark(name),
24885×
        ui::dim(ui::glyph("→", "->")),
24895×
        ui::dim(plural(heads.len(), "head"))
2490
    );
24915×
    println!(
2492
        "  {} {}",
24935×
        ui::note(),
24945×
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2495
    );
24965×
    Ok(0)
24976×
}
2498
2499
/// Up to five changes, newest last, as `  #hash subject` lines.
25002×
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
25012×
    let shown = changes.len().min(5);
25022×
    let mut lines: Vec<String> = changes[changes.len() - shown..]
25032×
        .iter()
25042×
        .map(|h| {
25052×
            let subject = repo
25062×
                .store()
25072×
                .get_change(h)
25082×
                .map(|c| subject_of(&c.message).to_string())
25092×
                .unwrap_or_default();
25102×
            format!("  #{} {subject}", h.short(12))
25112×
        })
25122×
        .collect();
25132×
    if changes.len() > shown {
25140×
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
25152×
    }
25162×
    lines.join("\n")
25172×
}
2518
25193×
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
25203×
    let repo = open()?;
25213×
    repo.snapshot_status("oxy bookmark set")?;
25223×
    let named = heads_from(&repo, changes)?;
2523
    // What the bookmark holds now and the new heads would leave out.
25243×
    let current = repo
25253×
        .bookmarks()?
25263×
        .into_iter()
25276×
        .find(|b| b.name == name)
25283×
        .map(|b| b.heads)
25293×
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
25303×
    let gap = repo.state_gap(&current, &named)?;
2531
    // A fast-forward: the new heads hold the bookmark's newest head, so
2532
    // what they leave out is older work nothing since has built on, such
2533
    // as an early change no later one depends on (oxygen#78). Keep it, as
2534
    // --upto does, and say so.
25353×
    let newest = current
25363×
        .iter()
25378×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m.hlc, *h)))
25383×
        .max()
25393×
        .map(|(_, h)| h);
2540
    // Ahead, too: a head the bookmark holds already (it would only drop
2541
    // the others) is not a move forward.
25423×
    let ahead = repo
25433×
        .load_state_history(&current)
25443×
        .is_ok_and(|st| named.iter().any(|h| !st.contains(h)));
25453×
    let forward = !only
25463×
        && ahead
25471×
        && !gap.earlier.is_empty()
25481×
        && newest.is_some_and(|n| {
25491×
            repo.load_state_history(&named)
25501×
                .is_ok_and(|st| st.contains(&n))
25511×
        });
25523×
    let heads = if upto {
25531×
        gap.upto
25542×
    } else if forward {
25551×
        println!(
2556
            "  {} {}",
25571×
            ui::note(),
25581×
            ui::dim(format!(
2559
                "{} builds on {name}'s newest head; keeping {} it holds that {0} does not depend on",
25601×
                changes.join(" "),
25611×
                plural(gap.earlier.len(), "change")
2562
            ))
2563
        );
25641×
        gap.upto
25651×
    } else if only || gap.earlier.is_empty() {
25660×
        named
2567
    } else {
25681×
        anyhow::bail!(
2569
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2570
             A state is its heads and what they depend on, not everything recorded before them.\n\
2571
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2572
             or --only for just {0} and what it depends on.",
25731×
            changes.join(" "),
25741×
            plural(gap.earlier.len(), "change"),
25751×
            listed_changes(&repo, &gap.earlier)
2576
        );
2577
    };
25782×
    let heads = repo.bookmark_set(name, &heads)?;
25792×
    println!(
2580
        "{} bookmark {} {} {}",
25812×
        ui::done("Moved"),
25822×
        ui::bookmark(name),
25832×
        ui::dim(ui::glyph("→", "->")),
25842×
        ui::dim(plural(heads.len(), "head"))
2585
    );
25862×
    Ok(0)
25873×
}
2588
25890×
pub fn bookmark_delete(name: &str) -> Result<i32> {
25900×
    let repo = open()?;
25910×
    repo.bookmark_delete(name)?;
25920×
    println!(
2593
        "{} bookmark {} {}",
25940×
        ui::done("Deleted"),
25950×
        ui::bookmark(name),
25960×
        ui::dim("(its changes stay until unreachable)")
2597
    );
25980×
    Ok(0)
25990×
}
2600
2601
/// Heads with their metadata, newest first.
26020×
fn heads_newest_first(
26030×
    repo: &Repo,
26040×
    heads: &[oxy_core::hash::ChangeHash],
26050×
) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> {
26060×
    let mut out: Vec<_> = heads
26070×
        .iter()
26080×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m)))
26090×
        .collect();
26100×
    out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc));
26110×
    out
26120×
}
2613
2614
/// One head as a line: id, hash, author, when, subject.
26150×
fn print_head(
26160×
    repo: &Repo,
26170×
    indent: &str,
26180×
    h: &oxy_core::hash::ChangeHash,
26190×
    m: &oxy_core::state::ChangeMeta,
26200×
) {
26210×
    println!(
2622
        "{indent}{} {} {}{}{}{}{}",
26230×
        ui::id(m.change_id.short(8)),
26240×
        ui::dim(format!("#{}", &h.to_hex()[..8])),
26250×
        author_name(repo, m),
26260×
        ui::sep(),
26270×
        ui::dim(ui::ago(m.hlc.wall_ms)),
26280×
        ui::sep(),
26290×
        ui::subject(subject_of(&m.message))
2630
    );
26310×
}
2632
26330×
pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result<i32> {
26340×
    let repo = open()?;
26350×
    let name = name.unwrap_or(&repo.config.bookmark).to_string();
26360×
    let view = repo.view()?;
26370×
    let st = match view.bookmarks.get(&name) {
26380×
        Some(st) => *st,
26390×
        None => match oxy_core::repo::remote_bookmark(&view, &name) {
26400×
            Some((_, _, st)) => st,
26410×
            None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"),
2642
        },
2643
    };
26440×
    let heads = repo.store().get_state(&st)?.heads;
26450×
    let shown = heads_newest_first(&repo, &heads);
26460×
    if as_json {
26470×
        println!(
2648
            "{}",
26490×
            json::obj([
26500×
                ("name", json::s(&name)),
26510×
                ("current", json::b(name == repo.config.bookmark)),
2652
                (
26530×
                    "heads",
26540×
                    json::arr(shown.iter().map(|(h, m)| {
26550×
                        json::obj([
26560×
                            ("hash", json::s(&h.to_hex())),
26570×
                            ("id", json::s(&m.change_id.to_string())),
26580×
                            ("author", json::s(&author_name(&repo, m))),
26590×
                            ("time_ms", json::n(m.hlc.wall_ms)),
26600×
                            ("subject", json::s(subject_of(&m.message))),
26610×
                        ])
26620×
                    }))
2663
                ),
2664
            ])
2665
        );
26660×
        return Ok(0);
26670×
    }
26680×
    println!(
2669
        "{} {}{}{}",
26700×
        ui::ok(ui::glyph("●", "*")),
26710×
        ui::bookmark(&name),
26720×
        ui::sep(),
26730×
        ui::dim(plural(heads.len(), "head"))
2674
    );
26750×
    for (h, m) in &shown {
26760×
        print_head(&repo, "  ", h, m);
26770×
    }
26780×
    if heads.len() > 1 {
26790×
        println!(
26800×
            "  {}",
26810×
            ui::dim("None depends on another: the bookmark is all of them and their dependencies.")
26820×
        );
26830×
    }
26840×
    Ok(0)
26850×
}
2686
26875×
pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result<i32> {
26885×
    let repo = open()?;
26895×
    let remote_only = repo.remote_only_bookmarks()?;
26905×
    if as_json {
26915×
        let mut items: Vec<String> = repo
26925×
            .bookmarks()?
26935×
            .into_iter()
269413×
            .map(|b| {
269513×
                json::obj([
269613×
                    ("name", json::s(&b.name)),
269713×
                    ("heads", json::hashes(&b.heads)),
269813×
                    ("current", json::b(b.current)),
269913×
                    ("ahead", json::opt(b.ahead, json::n)),
270013×
                    ("behind", json::opt(b.behind, json::n)),
270113×
                    ("remote", json::opt(b.remote.as_deref(), json::s)),
270213×
                ])
270313×
            })
27045×
            .collect();
27055×
        if all {
27060×
            items.extend(remote_only.iter().map(|b| {
27070×
                json::obj([
27080×
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
27090×
                    ("heads", json::hashes(&b.heads)),
27100×
                    ("current", json::b(false)),
27110×
                    ("ahead", "null".into()),
27120×
                    ("behind", "null".into()),
27130×
                    ("remote", json::s(&b.remote)),
27140×
                ])
27150×
            }));
27165×
        }
27175×
        println!("{}", json::arr(items));
27185×
        return Ok(0);
27190×
    }
27200×
    for b in repo.bookmarks()? {
27210×
        let mark = if b.current {
27220×
            ui::ok(ui::glyph("●", "*"))
2723
        } else {
27240×
            ui::dim(ui::glyph("○", "o"))
2725
        };
27260×
        let mut tail = String::new();
27270×
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
27280×
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
27290×
        }
27300×
        if let Some(n) = b.behind.filter(|n| *n > 0) {
27310×
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
27320×
        }
2733
        // Which remote, when there is a choice (oxygen#83).
27340×
        if !tail.is_empty() && repo.config.remotes.len() > 1 {
27350×
            if let Some(r) = &b.remote {
27360×
                tail += &ui::dim(format!(" {r}"));
27370×
            }
27380×
        }
27390×
        let shown = heads_newest_first(&repo, &b.heads);
2740
        // The newest head's subject, so a busy bookmark shows its latest work.
27410×
        let head = match shown.first() {
27420×
            Some(_) if verbose => String::new(),
27430×
            Some((_, m)) if b.heads.len() > 1 => format!(
2744
                "{} {}",
27450×
                ui::dim("newest"),
27460×
                ui::subject(subject_of(&m.message))
2747
            ),
27480×
            Some((_, m)) => ui::subject(subject_of(&m.message)),
27490×
            None => ui::dim("(empty)"),
2750
        };
27510×
        let head = if head.is_empty() {
27520×
            head
2753
        } else {
27540×
            format!("  {head}")
2755
        };
27560×
        println!(
2757
            "{mark} {}{}{}{tail}{head}",
27580×
            ui::bookmark(&b.name),
27590×
            ui::sep(),
27600×
            ui::dim(plural(b.heads.len(), "head"))
2761
        );
27620×
        if verbose {
27630×
            for (h, m) in &shown {
27640×
                print_head(&repo, "    ", h, m);
27650×
            }
27660×
        }
2767
    }
27680×
    if remote_only.is_empty() {
27690×
        return Ok(0);
27700×
    }
27710×
    if !all {
27720×
        println!(
2773
            "{}",
27740×
            ui::dim(format!(
2775
                "  and {} only on a remote: oxy bookmark list --all",
27760×
                plural(remote_only.len(), "bookmark")
2777
            ))
2778
        );
27790×
        return Ok(0);
27800×
    }
27810×
    for b in &remote_only {
27820×
        println!(
27830×
            "{} {}{}{}",
27840×
            ui::dim(ui::glyph("◌", ".")),
27850×
            ui::dim(format!("{}/{}", b.remote, b.name)),
27860×
            ui::sep(),
27870×
            ui::dim(plural(b.heads.len(), "head"))
27880×
        );
27890×
    }
27900×
    println!(
2791
        "  {} {}",
27920×
        ui::note(),
27930×
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2794
    );
27950×
    Ok(0)
27965×
}
2797
27983×
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
27993×
    let mut repo = open()?;
28003×
    let from = repo.config.bookmark.clone();
28013×
    let (local, created_from) = repo.local_bookmark_for(name)?;
28023×
    if let Some(remote) = created_from {
28030×
        println!(
28040×
            "{} {} from {}",
28050×
            ui::done("Created"),
28060×
            ui::bookmark(&local),
28070×
            ui::dim(format!("{remote}/{local}"))
28080×
        );
28093×
    }
28103×
    let name = local.as_str();
2811
    // Only behind its remote: take the remote's state, so the switch does
2812
    // not check out a stale one (oxygen#74).
28133×
    if let Some(n) = repo.catch_up_bookmark(name)? {
28140×
        println!(
28150×
            "{} {} with {}: {} it lacked",
28160×
            ui::done("Caught up"),
28170×
            ui::bookmark(name),
28180×
            ui::dim(format!("{}/{name}", repo.default_remote())),
28190×
            plural(n, "change")
28200×
        );
28213×
    }
28223×
    let sp = ui::spinner(&format!("Switching to {name}…"));
28233×
    let (r, carried) = if carry {
28240×
        repo.bookmark_switch_carry(name)?
2825
    } else {
28263×
        (repo.bookmark_switch(name, discard)?, vec![])
2827
    };
28283×
    sp.done(&format!(
2829
        "{} to {}: {} written, {} removed{}",
28303×
        ui::done("Switched"),
28313×
        ui::bookmark(name),
28323×
        plural(r.written, "file"),
2833
        r.removed,
28343×
        if carried.is_empty() {
28353×
            String::new()
2836
        } else {
28370×
            format!("; carried {}", plural(carried.len(), "changed path"))
2838
        }
2839
    ));
28403×
    print_removed(&r);
28413×
    if r.conflicted {
28420×
        println!(
28430×
            "  {} {}",
28440×
            ui::caution(),
28450×
            ui::warn("this state has conflicts; see oxy status")
28460×
        );
28473×
    }
2848
    // Say when the new state leaves out work the old one had: a state is
2849
    // its heads and what they depend on, which can be far less than a Git
2850
    // user expects.
28513×
    if r.lacks > 0 {
28521×
        println!(
28531×
            "  {} {}",
28541×
            ui::note(),
28551×
            ui::dim(format!(
28561×
                "{name} lacks {} that {from} has",
28571×
                plural(r.lacks, "change")
28581×
            ))
28591×
        );
28602×
    }
28613×
    super::sync::subrepos_behind(&repo);
28623×
    where_now(&repo);
28633×
    Ok(0)
28643×
}
2865
28660×
pub fn merge(bookmark: &str) -> Result<i32> {
28670×
    let repo = open()?;
28680×
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
28690×
    let r = repo.merge(bookmark)?;
28700×
    if !r.changed {
28710×
        sp.done(&format!(
28720×
            "{} {}",
28730×
            ui::ok(ui::glyph("✔", "*")),
28740×
            ui::dim(format!(
28750×
                "{} already contains {bookmark}",
28760×
                repo.config.bookmark
28770×
            ))
28780×
        ));
28790×
        return Ok(0);
28800×
    }
28810×
    sp.done(&format!(
2882
        "{} {} into {}: now {}{}",
28830×
        ui::done("Merged"),
28840×
        ui::bookmark(bookmark),
28850×
        ui::bookmark(&repo.config.bookmark),
28860×
        plural(r.heads.len(), "head"),
28870×
        ui::dim(if r.checked_out {
28880×
            "; working copy updated"
2889
        } else {
28900×
            "; run oxy checkout to update the working copy"
2891
        })
2892
    ));
28930×
    let snap = repo.snapshot("oxy merge")?;
28940×
    if snap.base_snapshot.is_conflicted() {
28950×
        println!(
28960×
            "  {} {}",
28970×
            ui::caution(),
28980×
            ui::warn("the result has conflicts; see oxy status")
28990×
        );
29000×
    }
29010×
    where_now(&repo);
29020×
    Ok(0)
29030×
}
2904
29050×
pub fn squash(change: &str, into: &str) -> Result<i32> {
29060×
    let repo = open()?;
29070×
    let c = repo.resolve_change(change)?;
29080×
    let d = repo.resolve_change(into)?;
29090×
    let sp = ui::spinner("Squashing…");
29100×
    let h = repo.squash(&c, &d)?;
29110×
    let new = repo.store().get_change_meta(&h)?;
29120×
    sp.done(&format!(
29130×
        "{} into {} {}  {}",
29140×
        ui::done("Squashed"),
29150×
        ui::id(new.change_id.short(8)),
29160×
        ui::hash(format!("#{}", h.short(12))),
29170×
        ui::subject(subject_of(&new.message))
29180×
    ));
29190×
    Ok(0)
29200×
}
2921
29220×
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
29230×
    let repo = open()?;
29240×
    let c = repo.resolve_change(change)?;
29250×
    let mut heads = Vec::new();
29260×
    for o in onto {
29270×
        heads.extend(repo.resolve_heads(o)?);
2928
    }
29290×
    let sp = ui::spinner("Rebasing…");
29300×
    let h = match repo.rebase(&c, &heads) {
29310×
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
29320×
            let r = repo.rebase_into_working_copy(&c, &heads)?;
29330×
            sp.done(&format!(
29340×
                "{} {} into {}: now {}",
29350×
                ui::done("Merged"),
29360×
                onto.join(" "),
29370×
                ui::bookmark(&repo.config.bookmark),
29380×
                plural(r.heads.len(), "head"),
29390×
            ));
29400×
            if r.checked_out {
29410×
                println!(
29420×
                    "  {} {}",
29430×
                    ui::caution(),
29440×
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
29450×
                );
29460×
            } else {
29470×
                println!(
29480×
                    "  {} {}",
29490×
                    ui::caution(),
29500×
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
29510×
                );
29520×
            }
29530×
            where_now(&repo);
29540×
            return Ok(0);
2955
        }
29560×
        other => other?,
2957
    };
29580×
    let new = repo.store().get_change_meta(&h)?;
29590×
    sp.done(&format!(
29600×
        "{} {} {}  {}",
29610×
        ui::done("Rebased"),
29620×
        ui::id(new.change_id.short(8)),
29630×
        ui::hash(format!("#{}", h.short(12))),
29640×
        ui::dim(format!(
29650×
            "now depends on {}",
29660×
            plural(new.deps.len(), "change")
29670×
        ))
29680×
    ));
29690×
    where_now(&repo);
29700×
    Ok(0)
29710×
}
2972
2973
#[cfg(test)]
2974
mod tests {
2975
    use super::*;
2976
2977
    #[test]
29781×
    fn id_prefixes_agree_with_the_whole_list() {
2979
        // Ids that share long prefixes, and some that differ only in a
2980
        // half byte, from a fixed sequence.
29811×
        let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
29827999×
        let mut next = || {
29837999×
            x ^= x << 13;
29847999×
            x ^= x >> 7;
29857999×
            x ^= x << 17;
29867999×
            x
29877999×
        };
29881×
        let mut ids: Vec<[u8; 16]> = Vec::new();
29891×
        for _ in 0..2000 {
29902000×
            let mut id = [0u8; 16];
29912000×
            id[..8].copy_from_slice(&next().to_le_bytes());
29922000×
            id[8..].copy_from_slice(&next().to_le_bytes());
29932000×
            let share = (next() % 4) as usize;
29942000×
            if let Some(prev) = ids.last() {
29951999×
                id[..share].copy_from_slice(&prev[..share]);
29961999×
                if next() % 2 == 0 {
2997973×
                    id[share] = (prev[share] & 0xf0) | (id[share] & 0x0f);
29981026×
                }
29991×
            }
30002000×
            ids.push(id);
3001
        }
30024000×
        let hex = |id: &[u8; 16]| oxy_core::ids::ChangeId(*id).to_hex();
30031×
        let whole = unique_prefixes(ids.iter().map(hex));
30041×
        let some = id_prefixes(ids.clone(), ids.iter().copied());
30052000×
        for id in &ids {
30062000×
            assert_eq!(some[id], whole[&hex(id)], "{}", hex(id));
3007
        }
30081×
    }
3009
}