OXYGENHUB

Coverage / src/cli/workspace.rs 38.7%

913 of 2359 lines run, 89 of 329 functions · run #276 on bare-hashes · 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
/// Folders holding a repository of their own, which oxy leaves out (oxygen#43):
103
/// named, with how to track them.
10431×
fn print_untracked_nested(repo: &Repo, nested: &[String]) {
10531×
    if nested.is_empty() {
10629×
        return;
1072×
    }
1082×
    println!();
1092×
    println!(
110
        "{} {}",
1112×
        ui::section(ui::warn("Not tracked")),
1122×
        ui::dim("folders holding a repository of their own")
113
    );
1142×
    for p in nested {
1152×
        let kind = if repo.root().join(p).join(".git").exists() {
1162×
            "Git"
117
        } else {
1180×
            "Oxygen"
119
        };
1202×
        println!(
121
            "  {} {}  {}",
1222×
            ui::caution(),
1232×
            ui::path(format!("{p}/")),
1242×
            ui::dim(format!("a nested {kind} repository"))
125
        );
126
    }
1272×
    println!(
128
        "  {} {}",
1292×
        ui::note(),
1302×
        ui::dim(
131
            "to track one's files, remove its .git (or .oxy); to keep it a repository of its own, \
132
             oxy submodule add URL PATH; to leave it out quietly, list it in .oxyignore"
133
        )
134
    );
13531×
}
136
137
/// The working copy's changed paths, or that it is clean.
1385×
fn print_statuses(statuses: &[oxy_core::repo::PathStatus]) {
1395×
    if statuses.is_empty() {
1403×
        println!(
141
            "  {} {}",
1423×
            ui::ok(ui::glyph("✔", "*")),
1433×
            ui::dim("nothing to commit, working copy clean")
144
        );
1453×
        return;
1462×
    }
1472×
    println!();
1482×
    for s in statuses {
1492×
        println!(
1502×
            "  {} {}",
1512×
            ui::status_mark(status_tag(s.status)),
1522×
            ui::path(&s.path)
1532×
        );
1542×
    }
1555×
}
156
157
/// Say when the working copy has fallen behind its own bookmark: a
158
/// "clean" status there hid a pull that left it on old code (oxygen#89).
1595×
fn print_behind(repo: &Repo) {
1605×
    if let Ok(Some(n)) = repo.working_copy_behind() {
1610×
        println!(
1620×
            "  {} {}",
1630×
            ui::caution(),
1640×
            ui::warn(format!(
1650×
                "the working copy is behind {}: it lacks {} the bookmark has; oxy checkout brings it up",
1660×
                repo.config.bookmark,
1670×
                plural(n, "change")
1680×
            ))
1690×
        );
1705×
    }
1715×
}
172
1738×
pub fn status(json: bool) -> Result<i32> {
1748×
    let repo = open()?;
175
    // Answered by the manifest alone, with no history to load (oxygen#35,
176
    // #41): a clean working copy, or one as the last snapshot left it.
1778×
    let known = if json {
1783×
        None
179
    } else {
1805×
        repo.status_by_manifest()?
181
    };
1828×
    if let Some(statuses) = known {
1833×
        let (_, wc) = repo.working_copy()?;
1843×
        let heads = repo.bookmark_heads()?;
1853×
        println!(
186
            "{} {}{}working copy {}{}{}",
1873×
            ui::dim("On"),
1883×
            ui::bookmark(&repo.config.bookmark),
1893×
            ui::sep(),
1903×
            ui::id(wc.change_id.short(8)),
1913×
            ui::sep(),
1923×
            ui::dim(plural(heads.len(), "head"))
193
        );
1943×
        print_behind(&repo);
1953×
        print_statuses(&statuses);
1963×
        print_untracked_nested(&repo, &repo.untracked_nested());
1973×
        print_skipped_large(&repo);
1983×
        return Ok(0);
1995×
    }
2005×
    let sp = ui::spinner("Snapshotting the working copy…");
2015×
    let snap = repo.snapshot_status("oxy status")?;
2025×
    let heads = {
2035×
        let _t = oxy_core::timing::phase("status: heads");
2045×
        repo.bookmark_heads()?
205
    };
2065×
    let _drop = oxy_core::timing::phase("status: print and drop");
2075×
    sp.clear();
2085×
    if json {
2093×
        println!("{}", repo.status_json(&snap)?);
2103×
        return Ok(if snap.base_snapshot.is_conflicted() {
2110×
            2
212
        } else {
2133×
            0
214
        });
2152×
    }
2162×
    println!(
217
        "{} {}{}working copy {}{}{}",
2182×
        ui::dim("On"),
2192×
        ui::bookmark(&repo.config.bookmark),
2202×
        ui::sep(),
2212×
        ui::id(snap.wc.change_id.short(8)),
2222×
        ui::sep(),
2232×
        ui::dim(plural(heads.len(), "head"))
224
    );
2252×
    print_behind(&repo);
2262×
    print_statuses(&snap.statuses);
2272×
    print_untracked_nested(&repo, &snap.untracked_nested);
2282×
    print_skipped_large(&repo);
2292×
    if !snap.base_snapshot.is_conflicted() {
2302×
        return Ok(0);
2310×
    }
2320×
    println!();
2330×
    println!(
234
        "{} {}",
2350×
        ui::section(ui::err("Conflicts")),
2360×
        ui::dim("edit the marked files, or the .oxy-conflict-N candidates, then commit")
237
    );
2380×
    for c in &snap.base_snapshot.tree.conflicts {
2390×
        println!("  {} tree: {c:?}", ui::err(ui::glyph("✱", "!")));
2400×
    }
2410×
    for (p, f) in &snap.base_snapshot.files {
2420×
        if f.is_conflicted() {
2430×
            let state = match snap
2440×
                .statuses
2450×
                .iter()
2460×
                .find(|s| s.path == *p)
2470×
                .map(|s| s.status)
248
            {
249
                Some(ChangeStatus::Resolved) => {
2500×
                    ui::ok(format!("{} resolved in working copy", ui::glyph("✔", "*")))
251
                }
252
                Some(ChangeStatus::ConflictEdited) => {
2530×
                    ui::warn(format!("{} markers remain", ui::glyph("‼", "!")))
254
                }
2550×
                _ => ui::err(format!("{} unresolved", ui::glyph("✱", "!"))),
256
            };
2570×
            println!("  {}  {state}", ui::path(p));
2580×
        }
259
    }
2600×
    Ok(2)
2618×
}
262
26326×
pub fn commit(
26426×
    message: &str,
26526×
    depends_on: &[String],
26626×
    paths: &[String],
26726×
    interactive: bool,
26826×
    hunks: &[usize],
26926×
) -> Result<i32> {
27026×
    let repo = open()?;
27126×
    let mut deps = Vec::new();
27226×
    for d in depends_on {
2730×
        deps.push(repo.resolve_change(d)?);
274
    }
27526×
    let selection = if !hunks.is_empty() {
2761×
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
27725×
    } else if interactive {
2780×
        let (_, hunks) = repo.hunks()?;
2790×
        if hunks.is_empty() {
2800×
            anyhow::bail!("nothing to commit: the working copy matches its base");
2810×
        }
2820×
        let hunks: Vec<_> = hunks
2830×
            .into_iter()
2840×
            .filter(|h| {
2850×
                paths.is_empty()
2860×
                    || paths.iter().any(|p| {
2870×
                        h.path == *p || h.path.starts_with(&format!("{}/", p.trim_end_matches('/')))
2880×
                    })
2890×
            })
2900×
            .collect();
2910×
        let mut chosen = Vec::new();
2920×
        let stdin = std::io::stdin();
2930×
        let mut take_rest = false;
2940×
        for (n, h) in hunks.iter().enumerate() {
2950×
            if take_rest {
2960×
                chosen.push(h.index);
2970×
                continue;
2980×
            }
2990×
            println!(
300
                "{} {} {}",
3010×
                ui::section(format!("hunk {} of {}", n + 1, hunks.len())),
3020×
                ui::path(&h.path),
3030×
                ui::dim(format!("(#{})", h.index))
304
            );
3050×
            for line in h.text.lines() {
3060×
                let styled = if line.starts_with('+') {
3070×
                    ui::ok(line)
3080×
                } else if line.starts_with('-') {
3090×
                    ui::err(line)
310
                } else {
3110×
                    ui::dim(line)
312
                };
3130×
                println!("  {styled}");
314
            }
315
            loop {
3160×
                print!(
317
                    "{} ",
3180×
                    ui::warn("Commit this hunk? [y]es [n]o [a]ll remaining [q]uit:")
319
                );
320
                use std::io::Write as _;
3210×
                std::io::stdout().flush()?;
3220×
                let mut answer = String::new();
3230×
                if stdin.read_line(&mut answer)? == 0 {
3240×
                    anyhow::bail!("aborted");
3250×
                }
3260×
                match answer.trim() {
3270×
                    "y" | "Y" => {
3280×
                        chosen.push(h.index);
3290×
                        break;
330
                    }
3310×
                    "n" | "N" | "" => break,
3320×
                    "a" | "A" => {
3330×
                        chosen.push(h.index);
3340×
                        take_rest = true;
3350×
                        break;
336
                    }
3370×
                    "q" | "Q" => anyhow::bail!("aborted; nothing committed"),
3380×
                    _ => continue,
339
                }
340
            }
341
        }
3420×
        if chosen.is_empty() {
3430×
            anyhow::bail!("no hunks chosen; nothing committed");
3440×
        }
3450×
        oxy_core::repo::Selection::Hunks(chosen)
34625×
    } else if paths.is_empty() {
34723×
        oxy_core::repo::Selection::All
348
    } else {
3492×
        oxy_core::repo::Selection::Paths(paths.to_vec())
350
    };
35126×
    let sp = ui::spinner("Committing…");
35226×
    let (h, partial) = repo.commit_selection_partial(message, &deps, &selection)?;
353
    // The metadata only: a first commit's change holds the whole tree.
35426×
    let meta = repo.store().get_change_meta(&h)?;
35526×
    sp.done(&format!(
35626×
        "{} {} {}  {}",
35726×
        ui::done("Committed"),
35826×
        ui::id(meta.change_id.short(8)),
35926×
        ui::hash(format!("#{}", h.short(12))),
36026×
        ui::subject(subject_of(message))
36126×
    ));
36226×
    print_untracked_nested(&repo, &repo.untracked_nested());
36326×
    print_skipped_large(&repo);
364
    // Only a commit that took part of the working copy leaves anything.
36526×
    if partial {
3662×
        let rest = repo.snapshot_status("oxy commit")?;
3672×
        if !rest.statuses.is_empty() {
3682×
            println!(
3692×
                "  {} {}",
3702×
                ui::note(),
3712×
                ui::dim(format!(
3722×
                    "{} left uncommitted",
3732×
                    plural(rest.statuses.len(), "path")
3742×
                ))
3752×
            );
3762×
        }
37724×
    }
37826×
    where_now(&repo);
37926×
    Ok(0)
38026×
}
381
3820×
pub fn blame(path: &str, json: bool) -> Result<i32> {
3830×
    let repo = open()?;
3840×
    let lines = repo.blame(path)?;
3850×
    if json {
3860×
        let items = lines.iter().map(|l| {
3870×
            format!(
388
                "{{\"line\":{},\"change_id\":{},\"hash\":{},\"index\":{},\"author\":{},\"when_ms\":{}}}",
389
                l.line,
3900×
                oxy_core::repo::json_str(&l.change_id.to_hex()),
3910×
                oxy_core::repo::json_str(&l.hash.to_hex()),
392
                l.index,
3930×
                oxy_core::repo::json_str(&l.author),
394
                l.when_ms
395
            )
3960×
        });
3970×
        println!("{}", oxy_core::repo::json_array(items));
3980×
        return Ok(0);
3990×
    }
4000×
    let width = lines
4010×
        .iter()
4020×
        .map(|l| l.author.chars().count())
4030×
        .max()
4040×
        .unwrap_or(0)
4050×
        .min(20);
4060×
    let digits = lines.len().to_string().len();
4070×
    let _t = oxy_core::timing::phase("blame: print");
408
    // Most lines share their change with many others: each change's id,
409
    // author and age are formatted once, and the lines go out through one
410
    // buffered lock on stdout.
4110×
    let mut prefix: std::collections::HashMap<oxy_core::hash::ChangeHash, String> =
4120×
        std::collections::HashMap::new();
4130×
    let bar = ui::dim(ui::glyph("│", "|"));
4140×
    let mut out = std::io::BufWriter::with_capacity(1 << 16, std::io::stdout().lock());
4150×
    for l in &lines {
4160×
        let p = prefix.entry(l.hash).or_insert_with(|| {
4170×
            let author: String = l.author.chars().take(20).collect();
4180×
            format!(
419
                "{} {} {}",
4200×
                ui::id(l.change_id.short(8)),
4210×
                ui::author(format!("{author:<width$}")),
4220×
                ui::dim(ui::ago(l.when_ms))
423
            )
4240×
        });
4250×
        let text = String::from_utf8_lossy(&l.text);
4260×
        if writeln!(
4270×
            out,
428
            "{p} {:>digits$}{bar} {}",
429
            l.line,
4300×
            text.trim_end_matches('\n')
431
        )
4320×
        .is_err()
433
        {
434
            // A closed pipe (blame | head): stop quietly.
4350×
            return Ok(0);
4360×
        }
437
    }
4380×
    let _ = out.flush();
4390×
    Ok(0)
4400×
}
441
4420×
fn bisect_report(repo: &Repo, step: &oxy_core::repo::BisectStep) -> Result<i32> {
443
    use oxy_core::repo::BisectStep::*;
4440×
    match step {
4450×
        NeedMarks { good, bad } => {
4460×
            println!(
447
                "{} {} {}",
4480×
                ui::note(),
4490×
                ui::dim(format!("{good} good, {bad} bad;")),
4500×
                ui::dim(if *good == 0 {
4510×
                    "mark a known-good change or bookmark: oxy bisect good CHANGE"
452
                } else {
4530×
                    "mark a known-bad change or bookmark: oxy bisect bad CHANGE"
454
                })
455
            );
4560×
            Ok(0)
457
        }
458
        Testing {
4590×
            heads,
4600×
            remaining,
4610×
            steps_left,
462
        } => {
4630×
            println!(
464
                "{} {} {}",
4650×
                ui::done("Testing"),
4660×
                ui::dim(format!(
467
                    "{} in the state under test;",
4680×
                    plural(heads.len(), "head")
469
                )),
4700×
                ui::dim(format!(
471
                    "{remaining} candidates left, about {steps_left} more steps"
472
                ))
473
            );
4740×
            println!(
475
                "  {} {}",
4760×
                ui::note(),
4770×
                ui::dim("run your test, then oxy bisect good | bad | skip")
478
            );
4790×
            Ok(0)
480
        }
4810×
        Found { culprit } => {
4820×
            let c = repo.store().get_change(culprit)?;
4830×
            println!(
484
                "{} {} {}  {}",
4850×
                ui::done("Found"),
4860×
                ui::id(short_id(&c)),
4870×
                ui::hash(format!("#{}", culprit.short(12))),
4880×
                ui::subject(subject_of(&c.message))
489
            );
4900×
            println!("  {} {}", ui::note(), ui::dim("the first change whose inclusion makes the state bad; oxy bisect reset to return"));
4910×
            Ok(0)
492
        }
4930×
        Inconclusive { candidates } => {
4940×
            println!(
495
                "{} {}",
4960×
                ui::caution(),
4970×
                ui::warn(format!(
498
                    "every remaining candidate was skipped ({}); oxy bisect reset to return",
4990×
                    plural(candidates.len(), "change")
500
                ))
501
            );
5020×
            Ok(1)
503
        }
504
    }
5050×
}
506
5070×
pub fn bisect_start() -> Result<i32> {
5080×
    let repo = open()?;
5090×
    repo.bisect_start()?;
5100×
    println!(
511
        "{} bisect; {}",
5120×
        ui::done("Started"),
5130×
        ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE")
514
    );
5150×
    Ok(0)
5160×
}
517
5180×
pub fn bisect_mark(good: Option<bool>, changes: &[String]) -> Result<i32> {
5190×
    let repo = open()?;
5200×
    let mut heads = Vec::new();
5210×
    for c in changes {
5220×
        heads.extend(repo.resolve_heads(c)?);
523
    }
5240×
    let step = repo.bisect_mark(good, &heads)?;
5250×
    bisect_report(&repo, &step)
5260×
}
527
5280×
pub fn bisect_run(command: &[String]) -> Result<i32> {
5290×
    let repo = open()?;
5300×
    let step = repo.bisect_run(command)?;
5310×
    bisect_report(&repo, &step)
5320×
}
533
5341×
pub fn bisect_status(as_json: bool) -> Result<i32> {
5351×
    let repo = open()?;
5361×
    if as_json {
537
        use oxy_core::repo::BisectStep::*;
5381×
        let v = match repo.bisect_status()? {
5391×
            None => "null".to_string(),
5400×
            Some(NeedMarks { good, bad }) => json::obj([
5410×
                ("state", json::s("need-marks")),
5420×
                ("good", json::n(good)),
5430×
                ("bad", json::n(bad)),
5440×
            ]),
545
            Some(Testing {
5460×
                heads,
5470×
                remaining,
5480×
                steps_left,
5490×
            }) => json::obj([
5500×
                ("state", json::s("testing")),
5510×
                ("heads", json::hashes(&heads)),
5520×
                ("remaining", json::n(remaining)),
5530×
                ("steps_left", json::n(steps_left)),
5540×
            ]),
5550×
            Some(Found { culprit }) => json::obj([
5560×
                ("state", json::s("found")),
5570×
                ("culprit", json::s(&culprit.to_hex())),
5580×
            ]),
5590×
            Some(Inconclusive { candidates }) => json::obj([
5600×
                ("state", json::s("inconclusive")),
5610×
                ("candidates", json::hashes(&candidates)),
5620×
            ]),
563
        };
5641×
        println!("{v}");
5651×
        return Ok(0);
5660×
    }
5670×
    match repo.bisect_status()? {
568
        None => {
5690×
            println!("{}", ui::dim("No bisect in progress."));
5700×
            Ok(0)
571
        }
5720×
        Some(step) => bisect_report(&repo, &step),
573
    }
5741×
}
575
5760×
pub fn bisect_reset() -> Result<i32> {
5770×
    let repo = open()?;
5780×
    repo.bisect_reset()?;
5790×
    println!("{} bisect; working copy restored", ui::done("Reset"));
5800×
    Ok(0)
5810×
}
582
583
/// The log: one entry per change, newest first, joined by a rail. The
584
/// default view is the subject and a metadata line; `verbose` adds the full
585
/// message, dependencies, and the authenticating key.
58614×
fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
58714×
    Ok(match repo.authenticate_change(h)? {
5889×
        SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]),
589
        SignatureStatus::Valid {
5905×
            key,
5915×
            name,
5925×
            email,
5935×
            sealed,
5945×
            revoked,
5955×
        } => json::obj([
5965×
            ("status", json::s(if sealed { "sealed" } else { "signed" })),
5975×
            ("key", json::s(&key.to_hex())),
5985×
            ("name", json::s(&name)),
5995×
            ("email", json::s(&email)),
6005×
            ("revoked", json::b(revoked)),
601
        ]),
6020×
        SignatureStatus::Invalid(why) => {
6030×
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
604
        }
605
    })
60614×
}
607
60818×
fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result<String> {
60918×
    let c = &e.change;
61018×
    Ok(json::obj([
61118×
        ("hash", json::s(&e.hash.to_hex())),
61218×
        ("change_id", json::s(&c.change_id.to_hex())),
61318×
        ("author", json::s(&author_name(repo, c))),
61418×
        ("author_key", json::s(&c.author.to_hex())),
615
        (
61618×
            "via",
61718×
            match via(
61818×
                repo,
61918×
                &repo.authenticate_change_known(&e.hash, Some(c))?,
62018×
                &c.author,
621
            ) {
6220×
                Some(v) => json::obj([
6230×
                    ("name", json::s(&v.name)),
6240×
                    ("email", json::s(&v.email)),
6250×
                    ("key", json::s(&v.key.to_hex())),
6260×
                    ("scope", json::opt(v.scope.as_deref(), json::s)),
6270×
                    ("expires_ms", json::opt(v.expires, json::n)),
6280×
                    ("revoked", json::b(v.revoked)),
6290×
                ]),
63018×
                None => "null".to_string(),
631
            },
632
        ),
63318×
        ("when_ms", json::n(c.hlc.wall_ms)),
63418×
        ("message", json::s(&c.message)),
63518×
        ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())),
63618×
        ("deps", json::hashes(&c.deps)),
63718×
        ("head", json::b(e.is_head)),
63818×
        ("working_copy", json::b(e.is_working_copy)),
639
        (
64018×
            "signature",
64118×
            if e.is_working_copy {
6424×
                "null".into()
643
            } else {
64414×
                signature_json(repo, &e.hash)?
645
            },
646
        ),
647
    ]))
64818×
}
649
650
/// `START,END:PATH` for `oxy log -L`.
6512×
fn parse_line_range(spec: &str) -> Result<(usize, usize, &str)> {
6522×
    let bad = || anyhow::anyhow!("-L {spec}: expected START,END:PATH, as 10,24:src/lib.rs");
6532×
    let (range, path) = spec.split_once(':').ok_or_else(bad)?;
6542×
    let (a, b) = range.split_once(',').ok_or_else(bad)?;
655
    Ok((
6561×
        a.trim().parse().map_err(|_| bad())?,
6571×
        b.trim().parse().map_err(|_| bad())?,
6581×
        path,
659
    ))
6602×
}
661
6628×
pub fn log(
6638×
    revset: Option<&str>,
6648×
    limit: Option<usize>,
6658×
    verbose: bool,
6668×
    path: Option<&str>,
6678×
    lines: Option<&str>,
6688×
    as_json: bool,
6698×
) -> Result<i32> {
6708×
    let repo = open()?;
671
    // Whether the working copy is clean and conflicted: from the manifest
672
    // when it proves the working copy clean, else from a snapshot.
673
    // The working copy as last recorded, without looking at the files (as
674
    // Git's log does not): whether its change holds edits, and whether its
675
    // base was conflicted. `oxy status` is what checks the disk.
6768×
    let conflicted = !repo.is_at_op() && repo.recorded_conflicted()?;
6778×
    let listing = oxy_core::timing::phase("log: entries");
6788×
    let entries = match (path, lines) {
6798×
        _ if revset.is_some() => repo.log_revset(revset.unwrap_or_default())?,
6802×
        (_, Some(spec)) => {
6812×
            let (first, last, p) = parse_line_range(spec)?;
6821×
            let (_, wc) = repo.working_copy()?;
6831×
            let base = repo.load_state_history(&wc.deps)?.maximal(&wc.deps);
6841×
            repo.line_history(&base, p, first, last)?
685
        }
6861×
        (Some(p), None) => repo.log_for_path(p)?,
6875×
        (None, None) => repo.log()?,
688
    };
6897×
    drop(listing);
6907×
    let _print = oxy_core::timing::phase("log: print");
6917×
    if as_json {
6926×
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
6936×
        let mut items = Vec::new();
69417×
        for e in entries.iter().take(shown) {
69517×
            items.push(log_entry_json(&repo, e)?);
696
        }
6976×
        println!(
698
            "{}",
6996×
            json::obj([
7006×
                ("bookmark", json::s(&repo.config.bookmark)),
7016×
                ("total", json::n(entries.len())),
7026×
                ("changes", json::arr(items))
7036×
            ])
704
        );
7056×
        return Ok(0);
7061×
    }
7071×
    let total = entries.len();
7081×
    let shown = limit.unwrap_or(total).min(total);
709
    // Lay out a little past what is shown, so edges into the cut are drawn.
7101×
    let window: Vec<(ChangeHash, Vec<ChangeHash>)> = entries
7111×
        .iter()
7121×
        .take((shown + MAX_EDGE).min(total))
7134×
        .map(|e| (e.hash, e.change.deps.clone()))
7141×
        .collect();
7151×
    let rows = oxy_core::lanes::graph(&window, MAX_EDGE);
716
    // Highlight the shortest prefix that names each change: against the
717
    // whole log, which is what `resolve_change` searches.
718
    let everything;
7191×
    let all = if path.is_some() || lines.is_some() || revset.is_some() {
7200×
        everything = repo.log()?;
7210×
        &everything
722
    } else {
7231×
        &entries
724
    };
7251×
    let prefixes = oxy_core::timing::phase("log: id prefixes");
7261×
    let id_prefix = id_prefixes(
7271×
        all.iter().map(|e| e.change.change_id.0).collect(),
7281×
        entries.iter().take(shown).map(|e| e.change.change_id.0),
729
    );
7301×
    drop(prefixes);
7311×
    let labels = reference_labels(&repo)?;
7324×
    for (e, row) in entries.iter().take(shown).zip(&rows) {
7334×
        let c = &e.change;
7344×
        let bullet = ui::log_bullet(
7354×
            e.is_working_copy,
7364×
            e.is_head,
7374×
            e.is_working_copy && conflicted,
738
        );
7394×
        let id = c.change_id.to_hex();
7404×
        let n = id_prefix.get(&c.change_id.0).copied().unwrap_or(8).min(8);
7414×
        let mut head = vec![format!("{}{}", ui::id(&id[..n]), ui::dim(&id[n..8]))];
7424×
        head.push(ui::author(author_name(&repo, c)));
7434×
        head.push(ui::dim(ui::ago(c.hlc.wall_ms)));
7444×
        if let Some(names) = labels.get(&e.hash) {
7452×
            head.push(names.join(" "));
7462×
        }
7474×
        if c.kind == ChangeKind::Resolution {
7480×
            head.push(ui::warn("resolution"));
7494×
        }
7504×
        if !e.is_working_copy {
7513×
            head.push(ui::hash(format!("#{}", e.hash.short(8))));
7523×
            let status = repo.authenticate_change_known(&e.hash, Some(c))?;
7533×
            if let Some(agent) = via(&repo, &status, &c.author) {
7540×
                head.push(ui::dim(format!("via {}", agent.name)));
7553×
            }
7563×
            head.push(signature_mark_of(&status));
7571×
        }
7584×
        println!("{}{}", node_line(row, &bullet), head.join(" "));
7594×
        let subject = if e.is_working_copy && c.message.is_empty() {
7601×
            let edited = repo
7611×
                .store()
7621×
                .get_change(&e.hash)
7631×
                .is_ok_and(|w| !w.tree_ops.is_empty() || !w.edits.is_empty());
7641×
            ui::dim(if edited {
7650×
                "(working copy, uncommitted changes)"
766
            } else {
7671×
                "(working copy)"
768
            })
7693×
        } else if c.message.trim().is_empty() {
7700×
            ui::dim("(no description)")
771
        } else {
7723×
            subject_of(&c.message).to_string()
773
        };
7744×
        println!("{}{subject}", below_line(row));
7754×
        if verbose {
7760×
            let rail = continuation(row);
7770×
            if !e.is_working_copy {
7780×
                println!(
779
                    "{rail}{}",
7800×
                    ui::dim(format!(
781
                        "{} {}",
7820×
                        when(c.hlc.wall_ms),
7830×
                        signature_line(&repo, &e.hash)?
784
                    ))
785
                );
7860×
            }
7870×
            if !c.deps.is_empty() {
7880×
                println!(
7890×
                    "{rail}{} {}",
7900×
                    ui::dim(ui::glyph("↳", "->")),
7910×
                    ui::dim(deps_of(&c.deps))
7920×
                );
7930×
            }
7940×
            let body: Vec<&str> = c
7950×
                .message
7960×
                .lines()
7970×
                .skip(1)
7980×
                .skip_while(|l| l.trim().is_empty())
7990×
                .collect();
8000×
            for line in body {
8010×
                println!("{rail}  {line}");
8020×
            }
8034×
        }
804
    }
8051×
    if shown < total {
8060×
        if let Some(last) = rows.get(shown.saturating_sub(1)) {
8070×
            let cut: String = last
8080×
                .below
8090×
                .iter()
8100×
                .map(|c| match c {
8110×
                    Cell::Blank | Cell::Elided | Cell::JoinRight => "  ",
8120×
                    _ => "~ ",
8130×
                })
8140×
                .collect();
8150×
            if cut.trim().is_empty() {
8160×
                println!("{}", ui::dim("~"));
8170×
            } else {
8180×
                println!("{}", ui::dim(cut.trim_end()));
8190×
            }
8200×
        }
8210×
        println!(
822
            "{}",
8230×
            ui::dim(format!(
824
                "{} {} more; pass -n to see them",
8250×
                ui::glyph("…", "..."),
8260×
                total - shown
827
            ))
828
        );
8291×
    }
8301×
    Ok(0)
8318×
}
832
833
/// Rows a drawn edge may span in `oxy log`; a longer one is elided (`~`).
834
const MAX_EDGE: usize = 12;
835
836
use oxy_core::hash::ChangeHash;
837
use oxy_core::lanes::{Cell, GraphRow};
838
839
/// A graph cell, two columns wide.
8406×
fn cell(c: Cell) -> &'static str {
8416×
    match c {
8421×
        Cell::Blank => "  ",
8433×
        Cell::Line => ui::glyph("│ ", "| "),
8440×
        Cell::Elided => "~ ",
8451×
        Cell::JoinLeft => ui::glyph("├─", "|-"),
8460×
        Cell::JoinPass => ui::glyph("──", "--"),
8470×
        Cell::JoinCross => ui::glyph("┼─", "+-"),
8481×
        Cell::JoinRight => ui::glyph("╯ ", "' "),
849
    }
8506×
}
851
852
/// The graph part of a change's own line, its bullet in its column.
8534×
fn node_line(row: &GraphRow, bullet: &str) -> String {
8544×
    let width = row
8554×
        .passing
8564×
        .iter()
8574×
        .copied()
8584×
        .max()
8594×
        .unwrap_or(0)
8604×
        .max(row.column)
8614×
        + 1;
8624×
    let mut out = String::new();
8635×
    for c in 0..width {
8645×
        if c == row.column {
8654×
            out.push_str(bullet);
8664×
            out.push(' ');
8674×
        } else if row.passing.contains(&c) {
8681×
            out.push_str(&ui::dim(cell(Cell::Line)));
8691×
        } else {
8700×
            out.push_str("  ");
8710×
        }
872
    }
8734×
    out.push(' ');
8744×
    out
8754×
}
876
877
/// The graph part of the line under a change: lanes carrying on, a join,
878
/// or `~` for an elided edge.
8794×
fn below_line(row: &GraphRow) -> String {
8805×
    let g: String = row.below.iter().map(|c| cell(*c)).collect();
8814×
    format!("{} ", ui::dim(g))
8824×
}
883
884
/// The graph part of any further line of a change (`-v`).
8850×
fn continuation(row: &GraphRow) -> String {
8860×
    let g: String = row
8870×
        .below
8880×
        .iter()
8890×
        .map(|c| match c {
8900×
            Cell::Line | Cell::JoinLeft | Cell::JoinCross => cell(Cell::Line),
8910×
            _ => "  ",
8920×
        })
8930×
        .collect();
8940×
    format!("{} ", ui::dim(g))
8950×
}
896
897
/// For each hex ID, the length of its shortest prefix no other ID shares.
898
/// The shortest prefix, in hex digits, that names each of `wanted` among
899
/// `all`: worked out for the few shown rather than for the whole history.
9002×
fn id_prefixes(
9012×
    mut all: Vec<[u8; 16]>,
9022×
    wanted: impl Iterator<Item = [u8; 16]>,
9032×
) -> std::collections::HashMap<[u8; 16], usize> {
9042×
    all.sort_unstable();
9052×
    all.dedup();
906
    // Hex digits two ids share at the start.
9074004×
    let common = |a: &[u8; 16], b: &[u8; 16]| {
90810720×
        let bytes = a.iter().zip(b).take_while(|(x, y)| x == y).count();
9094004×
        match (a.get(bytes), b.get(bytes)) {
9104004×
            (Some(x), Some(y)) if x >> 4 == y >> 4 => 2 * bytes + 1,
9111858×
            _ => 2 * bytes,
912
        }
9134004×
    };
9142×
    let mut out = std::collections::HashMap::new();
9152004×
    for id in wanted {
9162004×
        let Ok(i) = all.binary_search(&id) else {
9170×
            continue;
918
        };
9192004×
        let before = i.checked_sub(1).map_or(0, |j| common(&all[j], &id));
9202004×
        let after = all.get(i + 1).map_or(0, |n| common(&id, n));
9212004×
        out.insert(id, before.max(after) + 1);
922
    }
9232×
    out
9242×
}
925
9261×
fn unique_prefixes(ids: impl Iterator<Item = String>) -> std::collections::HashMap<String, usize> {
9271×
    let mut v: Vec<String> = ids.collect();
9281×
    v.sort();
9291×
    v.dedup();
93019576×
    let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
9311×
    let mut out = std::collections::HashMap::with_capacity(v.len());
9322000×
    for i in 0..v.len() {
9332000×
        let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 };
9342000×
        let after = if i + 1 < v.len() {
9351999×
            common(&v[i], &v[i + 1])
936
        } else {
9371×
            0
938
        };
9392000×
        out.insert(v[i].clone(), before.max(after) + 1);
940
    }
9411×
    out
9421×
}
943
944
/// Bookmark, remote bookmark and tag names to show beside the changes they
945
/// point at. A name is shown on each head of its state; one with more than
946
/// three heads names too much of the log to help, so it is left out (oxy
947
/// bookmark list shows it). A remote bookmark at the same state as the
948
/// local one of that name is not repeated.
9491×
fn reference_labels(repo: &Repo) -> Result<std::collections::HashMap<ChangeHash, Vec<String>>> {
950
    const MAX_HEADS: usize = 3;
9511×
    let view = repo.view()?;
9521×
    let mut out: std::collections::HashMap<ChangeHash, Vec<String>> = Default::default();
9531×
    let mut add = |heads: Vec<ChangeHash>, label: String| {
9541×
        if heads.len() <= MAX_HEADS {
9552×
            for h in heads {
9562×
                out.entry(h).or_default().push(label.clone());
9572×
            }
9580×
        }
9591×
    };
9601×
    for (name, st) in &view.bookmarks {
9611×
        add(repo.store().get_state(st)?.heads, ui::bookmark(name));
962
    }
9631×
    for (remote, bookmarks) in &view.remotes {
9640×
        for (name, st) in bookmarks {
9650×
            if view.bookmarks.get(name) == Some(st) {
9660×
                continue;
9670×
            }
9680×
            add(
9690×
                repo.store().get_state(st)?.heads,
9700×
                ui::dim(format!("{remote}/{name}")),
971
            );
972
        }
973
    }
9741×
    for t in repo.tags()? {
9750×
        add(t.heads.clone(), ui::warn(&t.name));
9760×
    }
9771×
    Ok(out)
9781×
}
979
9801×
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
9811×
    let repo = open()?;
9821×
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
9831×
    if as_json {
9841×
        let files = repo.diff_files(hash.as_ref())?;
9853×
        let items = files.iter().map(|f| {
9863×
            json::obj([
9873×
                ("path", json::s(&f.path)),
9883×
                ("kind", json::s(&f.kind)),
9893×
                ("from", json::opt(f.from.as_deref(), json::s)),
990
                (
9913×
                    "hunks",
9923×
                    json::arr(f.hunks.iter().map(|h| {
9933×
                        json::obj([
9943×
                            ("base_line", json::n(h.base_line)),
995
                            (
9963×
                                "added",
9973×
                                json::arr(
9983×
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
999
                                ),
1000
                            ),
1001
                            (
10023×
                                "removed",
10033×
                                json::arr(h.removed.iter().map(|(n, l)| {
10040×
                                    json::obj([
10050×
                                        ("line", json::n(*n)),
10060×
                                        ("text", json::s(&String::from_utf8_lossy(l))),
10070×
                                    ])
10080×
                                })),
1009
                            ),
1010
                        ])
10113×
                    })),
1012
                ),
1013
            ])
10143×
        });
10151×
        println!(
1016
            "{}",
10171×
            json::obj([
10181×
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
10191×
                ("files", json::arr(items))
1020
            ])
1021
        );
10221×
        return Ok(0);
10230×
    }
10240×
    match hash {
10250×
        Some(h) => {
10260×
            let c = repo.store().get_change(&h)?;
10270×
            let (base, snapshot) = repo.change_base(&c)?;
10280×
            print!("{}", render_change(&c, &base, &snapshot));
1029
        }
1030
        None => {
10310×
            let (wc, base, snapshot) = repo.working_copy_with_base()?;
10320×
            let text = {
10330×
                let _t = oxy_core::timing::phase("diff: render the change");
10340×
                render_change(&wc, &base, &snapshot)
1035
            };
10360×
            print!("{text}");
1037
            // The process ends here: freeing the base's tree and graphs
1038
            // one by one would only cost time (about 27 ms on Linux).
10390×
            std::mem::forget((wc, base, snapshot));
1040
        }
1041
    }
10420×
    Ok(0)
10431×
}
1044
10452×
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
10462×
    let repo = open()?;
10472×
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
10482×
    let bytes = match repo.file_at(path, heads.as_deref()) {
10492×
        Ok(b) => b,
1050
        // -r CHANGE reads that change's dependency closure, not the
1051
        // bookmark it is on: say so when the bookmark has the file
1052
        // (oxygen#76).
10530×
        Err(e) => match change {
10540×
            Some(c)
10550×
                if !repo.view()?.bookmarks.contains_key(c)
10560×
                    && repo.tag_heads(c)?.is_none()
10570×
                    && repo.file_at(path, None).is_ok() =>
1058
            {
10590×
                anyhow::bail!(
1060
                    "{path} is not in {c}'s dependency closure (the change and what it \
1061
                     depends on); it is on the bookmark: try -r {}, or --at-op OP for the \
1062
                     state at an operation",
1063
                    repo.config.bookmark
1064
                )
1065
            }
10660×
            _ => return Err(e.into()),
1067
        },
1068
    };
1069
    use std::io::Write as _;
10702×
    std::io::stdout().write_all(&bytes)?;
10712×
    Ok(0)
10722×
}
1073
10741×
pub fn root(as_json: bool) -> Result<i32> {
10751×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
10760×
        if as_json {
10770×
            println!("null");
10780×
        }
10790×
        return Ok(1);
1080
    };
10811×
    if as_json {
10821×
        println!(
10831×
            "{}",
10841×
            json::obj([
10851×
                ("root", json::s(&repo.root().to_string_lossy())),
10861×
                ("workspace", json::s(&repo.workspace().to_hex())),
10871×
                ("bookmark", json::s(&repo.config.bookmark))
10881×
            ])
10891×
        );
10901×
    } else {
10910×
        println!("{}", repo.root().display());
10920×
    }
10931×
    Ok(0)
10941×
}
1095
10961×
pub fn version(as_json: bool) -> Result<i32> {
10971×
    if as_json {
10981×
        println!(
10991×
            "{}",
11001×
            json::obj([
11011×
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
11021×
                // What was built: a release's or install's `oxy describe`,
11031×
                // a Flow build's heads, or "local build".
11041×
                ("build", json::s(env!("OXY_BUILD_ID"))),
11051×
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
11061×
                ("format", json::n(2))
11071×
            ])
11081×
        );
11091×
    } else {
11100×
        println!(
11110×
            "oxy {} (repository format 2, protocol {})",
11120×
            env!("OXY_VERSION_LONG"),
11130×
            oxy_core::protocol::PROTOCOL_VERSION
11140×
        );
11150×
    }
11161×
    Ok(0)
11171×
}
1118
11192×
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
11202×
    let repo = open()?;
11212×
    if paths.is_empty() && hunks.is_empty() {
11220×
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
11232×
    }
11242×
    let mut n = 0;
11252×
    if !hunks.is_empty() {
11261×
        n += repo.discard_hunks(hunks)?;
11271×
    }
11282×
    if !paths.is_empty() {
11291×
        n += repo.discard(paths)?;
11301×
    }
11312×
    println!(
1132
        "{} {} restored to the working copy's base",
11332×
        ui::done("Discarded"),
11342×
        plural(n, "path")
1135
    );
11362×
    Ok(0)
11372×
}
1138
11392×
pub fn hunks(as_json: bool) -> Result<i32> {
11402×
    let repo = open()?;
11412×
    let (_, hunks) = repo.hunks()?;
11422×
    if as_json {
11432×
        println!(
1144
            "{}",
11455×
            json::arr(hunks.iter().map(|h| json::obj([
11465×
                ("index", json::n(h.index)),
11475×
                ("path", json::s(&h.path)),
11485×
                ("text", json::s(&h.text))
11495×
            ])))
1150
        );
11512×
        return Ok(0);
11520×
    }
11530×
    if hunks.is_empty() {
11540×
        println!(
11550×
            "{}",
11560×
            ui::dim("No hunks: the working copy matches its base.")
11570×
        );
11580×
    }
11590×
    for h in &hunks {
11600×
        println!(
1161
            "{} {}",
11620×
            ui::section(format!("hunk {}", h.index)),
11630×
            ui::path(&h.path)
1164
        );
11650×
        for line in h.text.lines() {
11660×
            let styled = if line.starts_with('+') {
11670×
                ui::ok(line)
11680×
            } else if line.starts_with('-') {
11690×
                ui::err(line)
1170
            } else {
11710×
                ui::dim(line)
1172
            };
11730×
            println!("  {styled}");
1174
        }
1175
    }
11760×
    Ok(0)
11772×
}
1178
11792×
pub fn show(change: Option<&str>, revset: Option<&str>, as_json: bool) -> Result<i32> {
11802×
    let repo = open()?;
11812×
    repo.snapshot_status("oxy show")?;
11822×
    let Some(r) = revset else {
11832×
        let h = repo.resolve_change(change.unwrap_or("@"))?;
11842×
        return show_one(&repo, h, as_json, false);
1185
    };
1186
    // Several changes: a JSON array, or the changes one after another.
11870×
    let hashes = repo.revset(r)?.hashes;
11880×
    if as_json {
11890×
        print!("[");
11900×
        for (i, h) in hashes.iter().enumerate() {
11910×
            if i > 0 {
11920×
                print!(",");
11930×
            }
11940×
            show_one(&repo, *h, true, true)?;
1195
        }
11960×
        println!("]");
11970×
        return Ok(0);
11980×
    }
11990×
    if hashes.is_empty() {
12000×
        println!("{}", ui::dim(format!("No change matches {r:?}.")));
12010×
        return Ok(0);
12020×
    }
12030×
    for (i, h) in hashes.iter().enumerate() {
12040×
        if i > 0 {
12050×
            println!();
12060×
        }
12070×
        show_one(&repo, *h, false, false)?;
1208
    }
12090×
    Ok(0)
12102×
}
1211
1212
/// One change, as `oxy show` prints it; `inline` JSON goes without its
1213
/// newline, for an array.
12142×
fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool) -> Result<i32> {
12152×
    let c = repo.store().get_change(&h)?;
12162×
    if as_json {
12171×
        let files = repo.diff_files(Some(&h))?;
12181×
        let heads = repo.bookmark_heads()?;
12191×
        let entry = oxy_core::repo::LogEntry {
12201×
            hash: h,
12211×
            change: oxy_core::state::ChangeMeta::of(&c),
12221×
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
12231×
            is_head: heads.contains(&h),
12241×
        };
12251×
        let mut body = log_entry_json(repo, &entry)?;
12261×
        body.pop();
12271×
        body.push_str(&format!(
1228
            ",{}:{}}}",
12291×
            json::s("files"),
12301×
            json::arr(files.iter().map(|f| json::obj([
12311×
                ("path", json::s(&f.path)),
12321×
                ("kind", json::s(&f.kind)),
12331×
                ("from", json::opt(f.from.as_deref(), json::s))
12341×
            ])))
1235
        ));
12361×
        if inline {
12370×
            print!("{body}");
12381×
        } else {
12391×
            println!("{body}");
12401×
        }
12411×
        return Ok(0);
12421×
    }
12431×
    println!(
1244
        "{} {} {}",
12451×
        ui::section("change"),
12461×
        ui::id(short_id(&c)),
12471×
        ui::hash(format!("#{h}"))
1248
    );
12491×
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1250
    // Fetched but not pulled (oxygen#56): say where it is.
12511×
    if let Some(at) = repo.remote_only_location(&h)? {
12520×
        println!(
12530×
            "{}",
12540×
            ui::kv(
12550×
                "only in",
12560×
                ui::warn(format!(
12570×
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
12580×
                ))
12590×
            )
12600×
        );
12611×
    }
12621×
    let meta = oxy_core::state::ChangeMeta::of(&c);
12631×
    let status = repo.authenticate_change_known(&h, Some(&meta))?;
12641×
    println!("{}", ui::kv("author", ui::author(author_name(repo, &meta))));
12651×
    if let Some(agent) = via(repo, &status, &meta.author) {
12660×
        println!("{}", ui::kv("via", agent.line()));
12671×
    }
12681×
    println!(
1269
        "{}",
12701×
        ui::kv(
12711×
            "date",
12721×
            format!(
1273
                "{} {}",
12741×
                when(c.hlc.wall_ms),
12751×
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1276
            )
1277
        )
1278
    );
12791×
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
12801×
    println!("{}", ui::kv("sig", signature_line(repo, &h)?));
12811×
    println!();
12824×
    for line in (if c.message.is_empty() {
12830×
        "(no description)"
1284
    } else {
12851×
        &c.message
1286
    })
12871×
    .lines()
12884×
    {
12894×
        println!("    {line}");
12904×
    }
12911×
    println!();
12921×
    print!("{}", repo.describe_change(&h)?);
12931×
    Ok(0)
12942×
}
1295
12960×
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
12970×
    let repo = open()?;
1298
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1299
    // BRANCH` is: checking its files out under another bookmark's name
1300
    // made the next commit move the wrong bookmark (oxygen#60).
13010×
    if let [name] = changes {
13020×
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
13030×
            drop(repo);
13040×
            return bookmark_switch(name, discard, carry);
13050×
        }
13060×
    }
13070×
    let heads = if changes.is_empty() {
13080×
        repo.bookmark_heads()?
1309
    } else {
13100×
        let mut heads = Vec::new();
13110×
        for c in changes {
13120×
            heads.extend(repo.resolve_heads(c)?);
1313
        }
13140×
        heads
1315
    };
13160×
    let spec = if changes.is_empty() {
13170×
        repo.config.bookmark.clone()
1318
    } else {
13190×
        changes.join(" ")
1320
    };
13210×
    let sp = ui::spinner(&format!("Checking out {spec}…"));
13220×
    let command = format!("oxy checkout {spec}");
13230×
    let (r, carried) = if carry {
13240×
        repo.checkout_carry(&heads, &spec, &command)?
1325
    } else {
13260×
        (repo.checkout(&heads, discard, &command)?, vec![])
1327
    };
13280×
    sp.done(&format!(
1329
        "{} on {}: {} written, {} removed{}",
13300×
        ui::done("Working copy"),
13310×
        ui::bookmark(&spec),
13320×
        plural(r.written, "file"),
1333
        r.removed,
13340×
        if carried.is_empty() {
13350×
            String::new()
1336
        } else {
13370×
            format!("; carried {}", plural(carried.len(), "changed path"))
1338
        }
1339
    ));
13400×
    for n in &r.notes {
13410×
        println!("  {} {n}", ui::note());
13420×
    }
13430×
    if r.conflicted {
13440×
        println!(
13450×
            "  {} {}",
13460×
            ui::caution(),
13470×
            ui::warn("this state has conflicts; see oxy status")
13480×
        );
13490×
    }
13500×
    where_now(&repo);
13510×
    Ok(0)
13520×
}
1353
13541×
pub fn resolve(as_json: bool) -> Result<i32> {
13551×
    let repo = open()?;
13561×
    let snap = repo.snapshot("oxy resolve")?;
13571×
    if as_json {
13581×
        println!("{}", repo.status_json(&snap)?);
13591×
        return Ok(if snap.base_snapshot.is_conflicted() {
13600×
            2
1361
        } else {
13621×
            0
1363
        });
13640×
    }
13650×
    if !snap.base_snapshot.is_conflicted() {
13660×
        println!("The working copy's base has no conflicts.");
13670×
        return Ok(0);
13680×
    }
13690×
    let mut remaining = 0;
13700×
    for (p, f) in &snap.base_snapshot.files {
13710×
        if !f.is_conflicted() {
13720×
            continue;
13730×
        }
13740×
        match snap
13750×
            .statuses
13760×
            .iter()
13770×
            .find(|s| s.path == *p)
13780×
            .map(|s| s.status)
1379
        {
13800×
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
13810×
            Some(ChangeStatus::ConflictEdited) => {
13820×
                remaining += 1;
13830×
                println!("markers    {p}");
13840×
            }
13850×
            _ => {
13860×
                remaining += 1;
13870×
                println!("unresolved {p}");
13880×
            }
1389
        }
1390
    }
13910×
    for c in &snap.base_snapshot.tree.conflicts {
13920×
        remaining += 1;
13930×
        println!("tree       {c:?}");
13940×
    }
13950×
    if remaining == 0 {
13960×
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
13970×
        Ok(0)
1398
    } else {
13990×
        Ok(2)
1400
    }
14011×
}
1402
14030×
pub fn undo() -> Result<i32> {
14040×
    let repo = open()?;
14050×
    let u = repo.undo()?;
14060×
    println!("{} {}", ui::done("Undone:"), u.command);
14070×
    for c in &u.changes {
14080×
        println!("  {} {}", ui::note(), change_words(&repo, c));
14090×
    }
14100×
    if u.others_kept > 0 {
14110×
        let s = if u.others_kept == 1 { "" } else { "s" };
14120×
        println!(
1413
            "  {} {}",
14140×
            ui::note(),
14150×
            ui::dim(format!(
1416
                "{} newer operation{s} from other workspaces left as they are",
1417
                u.others_kept
1418
            ))
1419
        );
14200×
    }
14210×
    for (bookmark, remote) in &u.pushed {
14220×
        println!(
14230×
            "  {} {}",
14240×
            ui::caution(),
14250×
            ui::warn(format!(
14260×
                "{remote}/{bookmark} already has what this undid: undone here only; the next push of {bookmark} needs --force to take it back there"
14270×
            ))
14280×
        );
14290×
    }
14300×
    where_now(&repo);
14310×
    Ok(0)
14320×
}
1433
14341×
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
14351×
    let repo = open()?;
14361×
    let ops = repo.op_log()?;
1437
    // What each operation changed, against the one before it.
143811×
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
143911×
        match ops.get(i + 1) {
144010×
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
14411×
            None => Ok(vec![]),
1442
        }
144311×
    };
14441×
    if as_json {
14451×
        let mut items = Vec::new();
144611×
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
144711×
            let summary: Vec<String> = changes_of(i)?
144811×
                .iter()
144911×
                .map(|c| change_words(&repo, c))
145011×
                .collect();
145111×
            items.push(json::obj([
145211×
                ("id", json::s(&r.to_hex())),
145311×
                ("when_ms", json::n(op.hlc.wall_ms)),
145411×
                ("command", json::s(&op.command)),
145511×
                ("snapshot", json::b(op.is_snapshot())),
145611×
                ("current", json::b(i == 0)),
145711×
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1458
            ]));
1459
        }
14601×
        println!("{}", json::arr(items));
14611×
        return Ok(0);
14620×
    }
14630×
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
14640×
    let id = |r: &oxy_core::hash::ObjectRef| {
14650×
        let hex = r.to_hex();
14660×
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
14670×
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
14680×
    };
14690×
    let rail = ui::dim(ui::glyph("│", "|"));
14700×
    let (mut i, mut shown) = (0, 0);
14710×
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
14720×
        let (r, op) = &ops[i];
14730×
        let bullet = if i == 0 {
14740×
            ui::ok(ui::glyph("@", "@"))
1475
        } else {
14760×
            ui::dim(ui::glyph("○", "o"))
1477
        };
1478
        // A run of snapshots folds into one entry.
14790×
        let mut run = 1;
14800×
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
14810×
            run += 1;
14820×
        }
14830×
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
14840×
        if op.is_snapshot() {
14850×
            let span = if run > 1 {
14860×
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1487
            } else {
14880×
                String::new()
1489
            };
14900×
            println!(
1491
                "{bullet}  {}{} {when}",
14920×
                id(r),
14930×
                if span.is_empty() {
14940×
                    String::new()
1495
                } else {
14960×
                    format!(" {span}")
1497
                }
1498
            );
14990×
            println!(
1500
                "{rail}  {}",
15010×
                ui::dim(if run == 1 {
15020×
                    "working-copy snapshot".to_string()
1503
                } else {
15040×
                    format!("{run} working-copy snapshots")
1505
                })
1506
            );
1507
        } else {
15080×
            println!("{bullet}  {} {when}", id(r));
15090×
            let words: Vec<String> = changes_of(i)?
15100×
                .iter()
15110×
                .map(|c| change_words(&repo, c))
15120×
                .collect();
15130×
            let summary = if words.is_empty() {
15140×
                if i + 1 == ops.len() {
15150×
                    "created the repository".to_string()
1516
                } else {
15170×
                    "no bookmark or working-copy change".to_string()
1518
                }
1519
            } else {
15200×
                words.join("; ")
1521
            };
15220×
            println!(
1523
                "{rail}  {}",
15240×
                if i == 0 {
15250×
                    ui::subject(&summary)
1526
                } else {
15270×
                    summary
1528
                }
1529
            );
15300×
            let cmd = op.command.lines().next().unwrap_or("");
15310×
            let cmd: String = cmd.chars().take(100).collect();
15320×
            println!("{rail}  {}", ui::dim(cmd));
1533
        }
15340×
        i += run;
15350×
        shown += 1;
1536
    }
15370×
    if i < ops.len() {
15380×
        println!(
15390×
            "{}",
15400×
            ui::dim(format!(
15410×
                "{} {} older; pass -n to see more",
15420×
                ui::glyph("…", "..."),
15430×
                plural(ops.len() - i, "operation")
15440×
            ))
15450×
        );
15460×
    }
15470×
    Ok(0)
15481×
}
1549
1550
/// One change an operation made, in words.
155111×
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1552
    use oxy_core::repo::ViewChange::*;
15532×
    match c {
15540×
        BookmarkCreated { name, heads } => {
15550×
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1556
        }
15570×
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
15582×
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
15591×
        BookmarkMoved { name, from, to } => format!(
1560
            "{name}: {from} {} {}",
15611×
            ui::glyph("→", "->"),
15621×
            plural(*to, "head")
1563
        ),
15641×
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
15650×
        TagCreated { name } => format!("tagged {name}"),
15660×
        TagDeleted { name } => format!("removed tag {name}"),
15670×
        Policy => "trust policy changed".to_string(),
15688×
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
15698×
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
15700×
            Err(_) => "working copy moved".to_string(),
1571
        },
1572
    }
157311×
}
1574
15750×
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
15760×
    let repo = open()?;
15770×
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
15780×
    let r = repo.op_restore(op, discard)?;
15790×
    sp.done(&format!(
15800×
        "{} to operation {} {}",
15810×
        ui::done("Restored"),
15820×
        ui::hash(r.op.short(12)),
15830×
        ui::dim(r.command.lines().next().unwrap_or(""))
15840×
    ));
15850×
    println!(
1586
        "  {} {}",
15870×
        ui::note(),
15880×
        ui::dim(format!(
1589
            "{} written, {} removed; oxy undo goes back again",
15900×
            plural(r.checkout.written, "file"),
1591
            r.checkout.removed
1592
        ))
1593
    );
15940×
    where_now(&repo);
15950×
    Ok(0)
15960×
}
1597
15980×
pub fn op_revert(op: &str) -> Result<i32> {
15990×
    let repo = open()?;
16000×
    let r = repo.op_revert(op)?;
16010×
    let view = repo.view()?;
16020×
    let names: Vec<String> = r
16030×
        .reverted
16040×
        .iter()
16050×
        .map(|n| {
16060×
            if view.bookmarks.contains_key(n) {
16070×
                ui::bookmark(n)
1608
            } else {
16090×
                format!("{} (removed)", ui::bookmark(n))
1610
            }
16110×
        })
16120×
        .collect();
16130×
    println!(
1614
        "{} operation {} {}",
16150×
        ui::done("Reverted"),
16160×
        ui::hash(r.op.short(12)),
16170×
        ui::dim(r.command.lines().next().unwrap_or(""))
1618
    );
16190×
    println!(
1620
        "  {} {}",
16210×
        ui::note(),
16220×
        ui::dim(format!("as before it: {}", names.join(", ")))
1623
    );
16240×
    if !r.kept.is_empty() {
16250×
        println!(
16260×
            "  {} {}",
16270×
            ui::caution(),
16280×
            ui::warn(format!(
16290×
                "left as they are, having moved again since: {}",
16300×
                r.kept.join(", ")
16310×
            ))
16320×
        );
16330×
    }
16340×
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
16350×
        println!(
16360×
            "  {} {}",
16370×
            ui::note(),
16380×
            ui::dim("the working copy has work of its own: oxy checkout to move it")
16390×
        );
16400×
    }
16410×
    where_now(&repo);
16420×
    Ok(0)
16430×
}
1644
1645
/// Where the working copy and bookmark are now, after a command moved
1646
/// them (as jj says "Working copy now at").
164731×
pub fn where_now(repo: &Repo) {
164831×
    let Ok((_, wc)) = repo.working_copy() else {
16490×
        return;
1650
    };
165131×
    let heads = repo.bookmark_heads().unwrap_or_default();
165231×
    let newest = heads
165331×
        .iter()
165443×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
165531×
        .max_by_key(|(m, _)| m.hlc);
165631×
    println!(
1657
        "  {} {}",
165831×
        ui::dim(format!("{:<13}", "Working copy")),
165931×
        ui::id(wc.change_id.short(8))
1660
    );
166131×
    let tail = match newest {
166231×
        Some((m, _)) => format!(
1663
            ", newest {} {}",
166431×
            ui::id(m.change_id.short(8)),
166531×
            subject_of(&m.message)
1666
        ),
16670×
        None => String::new(),
1668
    };
166931×
    println!(
1670
        "  {} {}: {}{tail}",
167131×
        ui::dim(format!("{:<13}", "Bookmark")),
167231×
        ui::bookmark(&repo.config.bookmark),
167331×
        plural(heads.len(), "head")
1674
    );
167531×
}
1676
16770×
pub fn gc(now: bool, expire_snapshots: bool) -> Result<i32> {
16780×
    let mut repo = open()?;
16790×
    if expire_snapshots {
16800×
        repo.config.snapshot_retention_days = 0;
16810×
    }
16820×
    let sp = ui::spinner("Packing and pruning…");
16830×
    let r = repo.gc_with(now, &mut |phase| sp.set(&format!("{phase}…")))?;
16840×
    sp.clear();
16850×
    if r.packed.objects > 0 {
16860×
        println!(
16870×
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
16880×
            plural(r.packed.objects, "object"),
16890×
            r.packed.raw_bytes,
16900×
            r.packed.packed_bytes,
16910×
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
16920×
        );
16930×
    }
16940×
    println!(
1695
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
16960×
        plural(r.reachable, "object"),
16970×
        plural(r.pruned.objects, "unreachable object"),
1698
        r.pruned.bytes,
16990×
        if r.pruned.deferred > 0 {
17000×
            format!(
1701
                "; {} deferred by the grace period (use --now)",
17020×
                plural(r.pruned.deferred, "object")
1703
            )
1704
        } else {
17050×
            String::new()
1706
        },
17070×
        if r.merged_packs > 0 {
17080×
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1709
        } else {
17100×
            String::new()
1711
        },
17120×
        plural(repo.store().pack_count(), "pack")
1713
    );
17140×
    Ok(0)
17150×
}
1716
1717
/// `oxy gc --remote NAME`: fold a store remote's bundles into one.
17182×
pub fn gc_remote(name: &str, now: bool) -> Result<i32> {
17192×
    let repo = open()?;
17202×
    let sp = ui::spinner(&format!("Folding {name}'s bundles…"));
17212×
    let r = repo.gc_remote(name, now)?;
17221×
    sp.clear();
17231×
    if r.merged > 0 {
17241×
        println!(
17251×
            "{} {} into one of {} bytes ({})",
17261×
            ui::done("Folded"),
17271×
            plural(r.merged, "bundle"),
17281×
            r.bundle_bytes,
17291×
            plural(r.changes, "change")
17301×
        );
17311×
    } else {
17320×
        println!(
17330×
            "{} {}",
17340×
            ui::note(),
17350×
            ui::dim("nothing to fold: one bundle holds everything")
17360×
        );
17370×
    }
17381×
    println!(
1739
        "  {} {}",
17401×
        ui::note(),
17411×
        ui::dim(format!(
1742
            "removed {}{}",
17431×
            plural(r.deleted, "superseded bundle"),
17441×
            if r.deferred > 0 {
17450×
                format!(
1746
                    "; {} kept for readers that may still fetch them (use --now)",
17470×
                    plural(r.deferred, "bundle")
1748
                )
1749
            } else {
17501×
                String::new()
1751
            }
1752
        ))
1753
    );
17541×
    Ok(0)
17552×
}
1756
1757
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
17580×
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1759
    use oxy_core::repo::Health;
17600×
    let repo = open()?;
17610×
    let sp = ui::spinner(if offline {
17620×
        "Checking…"
1763
    } else {
17640×
        "Checking, and contacting remotes…"
1765
    });
17660×
    let r = repo.doctor(!offline);
17670×
    sp.clear();
17680×
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
17690×
    let word = |h: Health| match h {
17700×
        Health::Ok => "ok",
17710×
        Health::Warn => "warning",
17720×
        Health::Fail => "fail",
17730×
    };
17740×
    if as_json {
17750×
        let checks: Vec<String> = r
17760×
            .checks
17770×
            .iter()
17780×
            .map(|c| {
17790×
                json::obj([
17800×
                    ("area", json::s(&c.area)),
17810×
                    ("health", json::s(word(c.health))),
17820×
                    ("message", json::s(&c.message)),
17830×
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
17840×
                ])
17850×
            })
17860×
            .collect();
17870×
        println!(
1788
            "{}",
17890×
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1790
        );
17910×
        return Ok(code);
17920×
    }
17930×
    let mut last = "";
17940×
    for c in &r.checks {
17950×
        if c.area != last {
17960×
            println!("{}", ui::section(&c.area));
17970×
            last = &c.area;
17980×
        }
17990×
        let mark = match c.health {
18000×
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
18010×
            Health::Warn => ui::caution(),
18020×
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1803
        };
18040×
        println!("  {mark} {}", c.message);
18050×
        if let Some(h) = &c.hint {
18060×
            println!("    {} {}", ui::dim("→"), ui::dim(h));
18070×
        }
1808
    }
18090×
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
18100×
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
18110×
    if fails + warns == 0 {
18120×
        println!("{}", ui::done("Everything looks right."));
18130×
    } else {
18140×
        println!(
1815
            "{} {}, {}.",
18160×
            if fails > 0 {
18170×
                ui::err(ui::glyph("✖", "x"))
1818
            } else {
18190×
                ui::caution()
1820
            },
18210×
            plural(fails, "problem"),
18220×
            plural(warns, "warning")
1823
        );
1824
    }
18250×
    Ok(code)
18260×
}
1827
1828
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
18290×
pub fn fsck(as_json: bool) -> Result<i32> {
1830
    use oxy_core::repo::Severity;
18310×
    let repo = open()?;
18320×
    let sp = ui::spinner("Checking every object…");
18330×
    let r = repo.fsck()?;
18340×
    sp.clear();
18350×
    let code = if r.errors() > 0 { 1 } else { 0 };
18360×
    if as_json {
18370×
        let problems: Vec<String> = r
18380×
            .problems
18390×
            .iter()
18400×
            .map(|p| {
18410×
                json::obj([
1842
                    (
1843
                        "severity",
18440×
                        json::s(match p.severity {
18450×
                            Severity::Error => "error",
18460×
                            Severity::Warning => "warning",
1847
                        }),
1848
                    ),
1849
                    (
18500×
                        "object",
18510×
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1852
                    ),
18530×
                    ("what", json::s(&p.what)),
1854
                ])
18550×
            })
18560×
            .collect();
18570×
        println!(
1858
            "{}",
18590×
            json::obj([
18600×
                ("ok", json::b(code == 0)),
18610×
                ("objects", json::n(r.objects)),
18620×
                ("ops", json::n(r.ops)),
18630×
                ("changes", json::n(r.changes)),
18640×
                ("signed", json::n(r.signed)),
18650×
                ("unsigned", json::n(r.unsigned)),
18660×
                ("checkpoints", json::n(r.checkpoints)),
18670×
                ("attestations", json::n(r.attestations)),
18680×
                ("errors", json::n(r.errors())),
18690×
                ("warnings", json::n(r.warnings())),
18700×
                ("problems", json::arr(problems)),
18710×
            ])
1872
        );
18730×
        return Ok(code);
18740×
    }
18750×
    println!(
1876
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
18770×
        plural(r.objects, "object"),
18780×
        plural(r.ops, "operation"),
18790×
        plural(r.changes, "change"),
1880
        r.signed,
1881
        r.unsigned,
18820×
        plural(r.checkpoints, "checkpoint"),
18830×
        plural(r.attestations, "attestation"),
1884
    );
18850×
    for p in &r.problems {
18860×
        let obj = p
18870×
            .object
18880×
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
18890×
            .unwrap_or_default();
18900×
        match p.severity {
18910×
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
18920×
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1893
        }
1894
    }
18950×
    if r.problems.is_empty() {
18960×
        println!("{}", ui::done("No problems found."));
18970×
    } else if code == 0 {
18980×
        println!(
18990×
            "{}",
19000×
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
19010×
        );
19020×
    } else {
19030×
        println!(
19040×
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
19050×
            ui::err(ui::glyph("✖", "x")),
19060×
            plural(r.errors(), "error"),
19070×
            plural(r.warnings(), "warning")
19080×
        );
19090×
    }
19100×
    Ok(code)
19110×
}
1912
1913
/// The head the working copy sits on, for commands that default to it. With
1914
/// several heads beneath the working copy, the most recently made one is
1915
/// chosen and announced.
19160×
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
19170×
    let snap = repo.snapshot_status("oxy")?;
19180×
    let base = snap.base.maximal(&snap.wc.deps);
19190×
    match base.as_slice() {
19200×
        [] => anyhow::bail!("the working copy sits on no change yet"),
19210×
        [h] => Ok(*h),
19220×
        many => {
19230×
            let latest = many
19240×
                .iter()
19250×
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
19260×
                .copied()
19270×
                .unwrap();
19280×
            let c = repo.store().get_change(&latest)?;
19290×
            println!(
1930
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
19310×
                short_id(&c),
19320×
                latest.short(12),
19330×
                many.len()
1934
            );
19350×
            Ok(latest)
1936
        }
1937
    }
19380×
}
1939
1940
/// `oxy describe` without -m: the working copy's name for a build.
19414×
pub fn describe_name(as_json: bool) -> Result<i32> {
19424×
    let repo = open()?;
19434×
    let d = repo.describe_working_copy()?;
19444×
    if as_json {
19453×
        println!(
1946
            "{}",
19473×
            json::obj([
19483×
                ("describe", json::s(&d.line())),
19493×
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
19503×
                ("distance", json::n(d.distance)),
19513×
                ("bookmark", json::s(&d.bookmark)),
19523×
                ("change", json::s(&d.change.to_hex())),
19533×
                ("hash", json::s(&d.hash.to_hex())),
19543×
                ("dirty", json::b(d.dirty)),
1955
            ])
1956
        );
19571×
    } else {
19581×
        println!("{}", d.line());
19591×
    }
19604×
    Ok(0)
19614×
}
1962
19630×
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
19640×
    let repo = open()?;
19650×
    let h = match change {
19660×
        Some(c) => repo.resolve_change(c)?,
19670×
        None => current_head(&repo)?,
1968
    };
19690×
    let new = repo.describe(&h, message)?;
19700×
    let c = repo.store().get_change_meta(&new)?;
19710×
    println!(
1972
        "{} {} {}  {}",
19730×
        ui::done("Described"),
19740×
        ui::id(c.change_id.short(8)),
19750×
        ui::hash(format!("#{}", new.short(12))),
19760×
        ui::subject(subject_of(message))
1977
    );
19780×
    Ok(0)
19790×
}
1980
19810×
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
19820×
    let repo = open()?;
19830×
    let before = repo.view()?;
19840×
    let new = match into {
19850×
        Some(spec) => {
19860×
            let target = repo.resolve_change(spec)?;
19870×
            repo.amend_into(&target, message)?
1988
        }
19890×
        None => repo.amend(message)?,
1990
    };
19910×
    let c = repo.store().get_change_meta(&new)?;
19920×
    println!(
1993
        "{} {} {}  {}",
19940×
        ui::done("Amended"),
19950×
        ui::id(c.change_id.short(8)),
19960×
        ui::hash(format!("#{}", new.short(12))),
19970×
        ui::subject(subject_of(&c.message))
1998
    );
1999
    // Rewriting what a remote already has means the next push replaces it
2000
    // there (oxygen#99): say so now, not when the push is refused.
20010×
    let bookmark = repo.config.bookmark.clone();
20020×
    let (had, has) = (
20030×
        repo.heads_of(&before, &bookmark)?,
20040×
        repo.heads_of(&repo.view()?, &bookmark)?,
2005
    );
20060×
    for (remote, bookmarks) in &before.remotes {
20070×
        let Some(st) = bookmarks.get(&bookmark) else {
20080×
            continue;
2009
        };
20100×
        let theirs = repo.store().get_state(st)?.heads;
20110×
        if theirs.iter().any(|h| had.contains(h) && !has.contains(h)) {
20120×
            println!(
20130×
                "  {} {}",
20140×
                ui::caution(),
20150×
                ui::warn(format!(
20160×
                    "{remote}/{bookmark} has the change as it was: the next push of {bookmark} needs --force to replace it"
20170×
                ))
20180×
            );
20190×
        }
2020
    }
20210×
    where_now(&repo);
20220×
    Ok(0)
20230×
}
2024
20250×
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
20260×
    let repo = open()?;
20270×
    let Some(r) = revset else {
20280×
        let h = repo.resolve_change(change.unwrap_or_default())?;
20290×
        abandon_one(&repo, h)?;
20300×
        where_now(&repo);
20310×
        return Ok(0);
2032
    };
2033
    // A revset: say what it selects, refuse an empty set, ask above a few.
20340×
    let selected = repo.revset(r)?;
20350×
    let wc = repo.working_copy().ok().map(|(h, _)| h);
20360×
    let hashes: Vec<ChangeHash> = selected
20370×
        .hashes
20380×
        .iter()
20390×
        .copied()
20400×
        .filter(|h| Some(*h) != wc)
20410×
        .collect();
20420×
    if hashes.is_empty() {
20430×
        anyhow::bail!("{r:?} selects no change to abandon");
20440×
    }
20450×
    println!(
2046
        "{} {} selects {}:",
20470×
        ui::section("abandon"),
20480×
        ui::id(r),
20490×
        plural(hashes.len(), "change")
2050
    );
20510×
    for h in &hashes {
20520×
        if let Some(m) = selected.metas.get(h) {
20530×
            println!(
20540×
                "  {} {}  {}",
20550×
                ui::id(m.change_id.short(8)),
20560×
                ui::hash(format!("#{}", h.short(12))),
20570×
                subject_of(&m.message)
20580×
            );
20590×
        }
2060
    }
2061
    const ASK_ABOVE: usize = 5;
20620×
    if hashes.len() > ASK_ABOVE && !yes {
20630×
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
20640×
    }
2065
    // Newest first: abandoning a change rewrites what depends on it, so a
2066
    // later member is found again by its ChangeId.
20670×
    let mut done = 0;
20680×
    for h in &hashes {
20690×
        let Some(m) = selected.metas.get(h) else {
20700×
            continue;
2071
        };
20720×
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
20730×
            Ok(h) => h,
20740×
            Err(_) => continue,
2075
        };
20760×
        abandon_one(&repo, now)?;
20770×
        done += 1;
2078
    }
20790×
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
20800×
    where_now(&repo);
20810×
    Ok(0)
20820×
}
2083
20840×
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
20850×
    let c = repo.store().get_change_meta(&h)?;
20860×
    let notes = repo.abandon(&h)?;
20870×
    println!(
2088
        "{} {} {}  {}",
20890×
        ui::done("Abandoned"),
20900×
        ui::id(c.change_id.short(8)),
20910×
        ui::hash(format!("#{}", h.short(12))),
20920×
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
2093
    );
20940×
    for n in notes {
20950×
        println!("  {} {n}", ui::note());
20960×
    }
20970×
    Ok(())
20980×
}
2099
21000×
pub fn checkpoint() -> Result<i32> {
21010×
    let repo = open()?;
21020×
    let sp = ui::spinner("Writing checkpoint…");
21030×
    let (r, changes, bytes) = repo.checkpoint()?;
21040×
    sp.done(&format!(
21050×
        "{} {} of {} ({} bytes) for {}",
21060×
        ui::done("Checkpoint"),
21070×
        ui::hash(format!("#{}", r.short(12))),
21080×
        plural(changes, "change"),
21090×
        bytes,
21100×
        ui::id(&repo.config.bookmark)
21110×
    ));
21120×
    Ok(0)
21130×
}
2114
2115
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
21160×
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
21170×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
21180×
        return Ok(1);
2119
    };
21200×
    let info = repo.quick_status()?;
21210×
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
21220×
        oxy_core::repo::GLYPH_PROMPT_FORMAT
2123
    } else {
21240×
        format
2125
    };
21260×
    let line = match color {
21270×
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
21280×
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
21290×
        Some(_) => info.format_colored(fmt, ("", "")),
21300×
        None => info.format(fmt),
2131
    };
21320×
    println!("{line}");
21330×
    Ok(0)
21340×
}
2135
21360×
pub fn sparse(paths: &[String]) -> Result<i32> {
21370×
    let mut repo = open()?;
21380×
    if paths.is_empty() {
21390×
        if repo.config.sparse_paths.is_empty() {
21400×
            println!("No sparse filter: the whole tree is materialized.");
21410×
        } else {
21420×
            println!("{}", ui::heading("Sparse filter"));
21430×
            for p in &repo.config.sparse_paths {
21440×
                println!("  {}", ui::path(p));
21450×
            }
2146
        }
21470×
        return Ok(0);
21480×
    }
21490×
    let snap = repo.snapshot("oxy sparse")?;
21500×
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
21510×
        anyhow::bail!(
2152
            "the working copy has changes; commit them before changing the sparse filter"
2153
        );
21540×
    }
21550×
    repo.config.set("filter.paths", &paths.join(","))?;
21560×
    repo.save_config()?;
21570×
    let heads = repo.bookmark_heads()?;
21580×
    let sp = ui::spinner("Re-checking out with the new filter…");
21590×
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
21600×
    sp.done(&format!(
21610×
        "{} {}: {} written, {} removed",
21620×
        ui::done("Sparse filter set to"),
21630×
        ui::path(paths.join(",")),
21640×
        plural(r.written, "file"),
21650×
        r.removed
21660×
    ));
21670×
    Ok(0)
21680×
}
2169
21702×
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
21712×
    let repo = open()?;
21722×
    repo.snapshot_status("oxy tag")?;
21732×
    let heads = if changes.is_empty() {
21742×
        repo.bookmark_heads()?
2175
    } else {
21760×
        let mut heads = Vec::new();
21770×
        for c in changes {
21780×
            heads.extend(repo.resolve_heads(c)?);
2179
        }
21800×
        heads
2181
    };
21822×
    let t = repo.tag_create(name, &heads, message)?;
21832×
    println!(
2184
        "{} {} {} {} ({}){}",
21852×
        ui::done("Tagged"),
21862×
        ui::bookmark(&t.name),
21872×
        ui::dim(ui::glyph("→", "->")),
21882×
        ui::hash(format!("#{}", t.state.short(12))),
21892×
        plural(t.heads.len(), "head"),
21902×
        t.signer
21912×
            .map(|s| format!(", signed by {s}"))
21922×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2193
    );
21942×
    Ok(0)
21952×
}
2196
21971×
pub fn tag_list(as_json: bool) -> Result<i32> {
21981×
    let repo = open()?;
21991×
    let tags = repo.tags()?;
22001×
    if as_json {
22011×
        println!(
2202
            "{}",
22031×
            json::arr(tags.iter().map(|t| {
22041×
                json::obj([
22051×
                    ("name", json::s(&t.name)),
22061×
                    ("state", json::s(&t.state.to_hex())),
22071×
                    ("heads", json::hashes(&t.heads)),
22081×
                    ("message", json::s(&t.message)),
2209
                    (
22101×
                        "signer",
22111×
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2212
                    ),
2213
                ])
22141×
            }))
2215
        );
22161×
        return Ok(0);
22170×
    }
22180×
    if tags.is_empty() {
22190×
        println!("{}", ui::dim("No tags."));
22200×
    }
22210×
    for t in tags {
22220×
        println!(
2223
            "{} {} {}{}{}{}",
22240×
            ui::ok(ui::glyph("⚑", "#")),
22250×
            ui::bookmark(&t.name),
2226
            // The heads, as `oxy log` shows changes, not the state hash.
22270×
            ui::hash(
22280×
                t.heads
22290×
                    .iter()
22300×
                    .map(|h| format!("#{}", h.short(12)))
22310×
                    .collect::<Vec<_>>()
22320×
                    .join(" ")
2233
            ),
22340×
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
22350×
            if t.message.is_empty() {
22360×
                String::new()
2237
            } else {
22380×
                format!("  {}", ui::subject(subject_of(&t.message)))
2239
            },
22400×
            t.signer
22410×
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
22420×
                .unwrap_or_default()
2243
        );
2244
    }
22450×
    Ok(0)
22461×
}
2247
2248
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2249
/// and workspace add take as "be on this bookmark" (oxygen#60).
22500×
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
22510×
    Ok(repo.view()?.bookmarks.contains_key(name)
22520×
        || repo
22530×
            .remote_only_bookmarks()?
22540×
            .iter()
22550×
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
22560×
}
2257
22580×
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
22590×
    let repo = open()?;
2260
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2261
    // this workspace's bookmark with that one's files.
22620×
    if let [name] = changes {
22630×
        if names_bookmark(&repo, name)? {
22640×
            let (local, _) = repo.local_bookmark_for(name)?;
22650×
            let heads = repo.resolve_heads(&local)?;
22660×
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
22670×
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
22680×
            sp.done(&format!(
22690×
                "{} {} (workspace {}) on {}",
22700×
                ui::done("Workspace created at"),
22710×
                ui::path(ws.root().display()),
22720×
                ui::id(ws.workspace().short(8)),
22730×
                ui::bookmark(&local)
22740×
            ));
22750×
            return Ok(0);
22760×
        }
22770×
    }
22780×
    let heads = if changes.is_empty() {
22790×
        None
2280
    } else {
22810×
        let mut heads = Vec::new();
22820×
        for c in changes {
22830×
            heads.extend(repo.resolve_heads(c)?);
2284
        }
22850×
        Some(heads)
2286
    };
22870×
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
22880×
    let ws = repo.workspace_add(path, heads.as_deref())?;
22890×
    sp.done(&format!(
22900×
        "{} {} (workspace {})",
22910×
        ui::done("Workspace created at"),
22920×
        ui::path(ws.root().display()),
22930×
        ui::id(ws.workspace().short(8))
22940×
    ));
22950×
    Ok(0)
22960×
}
2297
22981×
pub fn workspace_list(as_json: bool) -> Result<i32> {
22991×
    let repo = open()?;
23001×
    if as_json {
23011×
        println!(
2302
            "{}",
23031×
            json::arr(repo.workspaces()?.iter().map(|w| {
23041×
                json::obj([
23051×
                    ("id", json::s(&w.id.to_hex())),
23061×
                    ("path", json::s(&w.path.to_string_lossy())),
23071×
                    ("current", json::b(w.current)),
2308
                    (
23091×
                        "working_copy",
23101×
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2311
                    ),
2312
                ])
23131×
            }))
2314
        );
23151×
        return Ok(0);
23160×
    }
23170×
    for w in repo.workspaces()? {
23180×
        println!(
2319
            "{} {} {}{}",
23200×
            if w.current {
23210×
                ui::ok(ui::glyph("●", "*"))
2322
            } else {
23230×
                ui::dim(ui::glyph("○", "o"))
2324
            },
23250×
            ui::id(w.id.short(8)),
23260×
            ui::path(w.path.display()),
23270×
            w.working_copy
23280×
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
23290×
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2330
        );
2331
    }
23320×
    Ok(0)
23331×
}
2334
23350×
pub fn workspace_forget(spec: &str) -> Result<i32> {
23360×
    let repo = open()?;
23370×
    let all = repo.workspaces()?;
23380×
    let target = std::fs::canonicalize(spec).ok();
23390×
    let matches: Vec<_> = all
23400×
        .iter()
23410×
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
23420×
        .collect();
23430×
    let w = match matches.as_slice() {
23440×
        [w] => *w,
23450×
        [] => anyhow::bail!("no workspace matches {spec:?}"),
23460×
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2347
    };
23480×
    repo.workspace_forget(&w.id)?;
23490×
    println!(
2350
        "{} workspace {} at {}; its files were left in place.",
23510×
        ui::done("Forgot"),
23520×
        ui::id(w.id.short(8)),
23530×
        ui::path(w.path.display())
2354
    );
23550×
    Ok(0)
23560×
}
2357
23580×
pub fn lock(path: &str) -> Result<i32> {
23590×
    let repo = open()?;
23600×
    repo.lock_path(path)?;
23610×
    println!(
2362
        "{} {} {}",
23630×
        ui::done("Locked"),
23640×
        ui::path(path),
23650×
        ui::dim("(advisory, local)")
2366
    );
23670×
    Ok(0)
23680×
}
2369
23700×
pub fn unlock(path: &str) -> Result<i32> {
23710×
    let repo = open()?;
23720×
    repo.unlock_path(path)?;
23730×
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
23740×
    Ok(0)
23750×
}
2376
23770×
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
23780×
    let repo = open()?;
23790×
    let h = repo.resolve_change(change)?;
23800×
    let (h1, h2) = repo.split(&h, paths)?;
23810×
    let c1 = repo.store().get_change_meta(&h1)?;
23820×
    let c2 = repo.store().get_change_meta(&h2)?;
23830×
    println!(
2384
        "{} into {} {} and {} {}",
23850×
        ui::done("Split"),
23860×
        ui::id(c1.change_id.short(8)),
23870×
        ui::hash(format!("#{}", h1.short(12))),
23880×
        ui::id(c2.change_id.short(8)),
23890×
        ui::hash(format!("#{}", h2.short(12)))
2390
    );
23910×
    Ok(0)
23920×
}
2393
23946×
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
23956×
    let mut heads = Vec::new();
23966×
    for c in changes {
23976×
        heads.extend(repo.resolve_heads(c)?);
2398
    }
23996×
    Ok(heads)
24006×
}
2401
24026×
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
24036×
    let repo = open()?;
24046×
    repo.snapshot_status("oxy bookmark create")?;
24056×
    let heads = if changes.is_empty() {
24063×
        None
2407
    } else {
24083×
        let named = heads_from(&repo, changes)?;
24093×
        let (_, wc) = repo.working_copy()?;
24103×
        let gap = repo.state_gap(&wc.deps, &named)?;
24113×
        if upto {
24121×
            Some(gap.upto)
24132×
        } else if only || gap.earlier.is_empty() {
24141×
            Some(named)
2415
        } else {
24161×
            anyhow::bail!(
2417
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2418
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2419
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2420
                 or --only for just {0} and what it depends on.",
24211×
                changes.join(" "),
24221×
                plural(gap.earlier.len(), "change"),
24231×
                listed_changes(&repo, &gap.earlier)
2424
            );
2425
        }
2426
    };
24275×
    let heads = repo.bookmark_create(name, heads.as_deref())?;
24285×
    println!(
2429
        "{} bookmark {} {} {}",
24305×
        ui::done("Created"),
24315×
        ui::bookmark(name),
24325×
        ui::dim(ui::glyph("→", "->")),
24335×
        ui::dim(plural(heads.len(), "head"))
2434
    );
24355×
    println!(
2436
        "  {} {}",
24375×
        ui::note(),
24385×
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2439
    );
24405×
    Ok(0)
24416×
}
2442
2443
/// Up to five changes, newest last, as `  #hash subject` lines.
24442×
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
24452×
    let shown = changes.len().min(5);
24462×
    let mut lines: Vec<String> = changes[changes.len() - shown..]
24472×
        .iter()
24482×
        .map(|h| {
24492×
            let subject = repo
24502×
                .store()
24512×
                .get_change(h)
24522×
                .map(|c| subject_of(&c.message).to_string())
24532×
                .unwrap_or_default();
24542×
            format!("  #{} {subject}", h.short(12))
24552×
        })
24562×
        .collect();
24572×
    if changes.len() > shown {
24580×
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
24592×
    }
24602×
    lines.join("\n")
24612×
}
2462
24633×
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
24643×
    let repo = open()?;
24653×
    repo.snapshot_status("oxy bookmark set")?;
24663×
    let named = heads_from(&repo, changes)?;
2467
    // What the bookmark holds now and the new heads would leave out.
24683×
    let current = repo
24693×
        .bookmarks()?
24703×
        .into_iter()
24716×
        .find(|b| b.name == name)
24723×
        .map(|b| b.heads)
24733×
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
24743×
    let gap = repo.state_gap(&current, &named)?;
2475
    // A fast-forward: the new heads hold the bookmark's newest head, so
2476
    // what they leave out is older work nothing since has built on, such
2477
    // as an early change no later one depends on (oxygen#78). Keep it, as
2478
    // --upto does, and say so.
24793×
    let newest = current
24803×
        .iter()
24818×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m.hlc, *h)))
24823×
        .max()
24833×
        .map(|(_, h)| h);
2484
    // Ahead, too: a head the bookmark holds already (it would only drop
2485
    // the others) is not a move forward.
24863×
    let ahead = repo
24873×
        .load_state_history(&current)
24883×
        .is_ok_and(|st| named.iter().any(|h| !st.contains(h)));
24893×
    let forward = !only
24903×
        && ahead
24911×
        && !gap.earlier.is_empty()
24921×
        && newest.is_some_and(|n| {
24931×
            repo.load_state_history(&named)
24941×
                .is_ok_and(|st| st.contains(&n))
24951×
        });
24963×
    let heads = if upto {
24971×
        gap.upto
24982×
    } else if forward {
24991×
        println!(
2500
            "  {} {}",
25011×
            ui::note(),
25021×
            ui::dim(format!(
2503
                "{} builds on {name}'s newest head; keeping {} it holds that {0} does not depend on",
25041×
                changes.join(" "),
25051×
                plural(gap.earlier.len(), "change")
2506
            ))
2507
        );
25081×
        gap.upto
25091×
    } else if only || gap.earlier.is_empty() {
25100×
        named
2511
    } else {
25121×
        anyhow::bail!(
2513
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2514
             A state is its heads and what they depend on, not everything recorded before them.\n\
2515
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2516
             or --only for just {0} and what it depends on.",
25171×
            changes.join(" "),
25181×
            plural(gap.earlier.len(), "change"),
25191×
            listed_changes(&repo, &gap.earlier)
2520
        );
2521
    };
25222×
    let heads = repo.bookmark_set(name, &heads)?;
25232×
    println!(
2524
        "{} bookmark {} {} {}",
25252×
        ui::done("Moved"),
25262×
        ui::bookmark(name),
25272×
        ui::dim(ui::glyph("→", "->")),
25282×
        ui::dim(plural(heads.len(), "head"))
2529
    );
25302×
    Ok(0)
25313×
}
2532
25330×
pub fn bookmark_delete(name: &str) -> Result<i32> {
25340×
    let repo = open()?;
25350×
    repo.bookmark_delete(name)?;
25360×
    println!(
2537
        "{} bookmark {} {}",
25380×
        ui::done("Deleted"),
25390×
        ui::bookmark(name),
25400×
        ui::dim("(its changes stay until unreachable)")
2541
    );
25420×
    Ok(0)
25430×
}
2544
2545
/// Heads with their metadata, newest first.
25460×
fn heads_newest_first(
25470×
    repo: &Repo,
25480×
    heads: &[oxy_core::hash::ChangeHash],
25490×
) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> {
25500×
    let mut out: Vec<_> = heads
25510×
        .iter()
25520×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m)))
25530×
        .collect();
25540×
    out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc));
25550×
    out
25560×
}
2557
2558
/// One head as a line: id, hash, author, when, subject.
25590×
fn print_head(
25600×
    repo: &Repo,
25610×
    indent: &str,
25620×
    h: &oxy_core::hash::ChangeHash,
25630×
    m: &oxy_core::state::ChangeMeta,
25640×
) {
25650×
    println!(
2566
        "{indent}{} {} {}{}{}{}{}",
25670×
        ui::id(m.change_id.short(8)),
25680×
        ui::dim(format!("#{}", &h.to_hex()[..8])),
25690×
        author_name(repo, m),
25700×
        ui::sep(),
25710×
        ui::dim(ui::ago(m.hlc.wall_ms)),
25720×
        ui::sep(),
25730×
        ui::subject(subject_of(&m.message))
2574
    );
25750×
}
2576
25770×
pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result<i32> {
25780×
    let repo = open()?;
25790×
    let name = name.unwrap_or(&repo.config.bookmark).to_string();
25800×
    let view = repo.view()?;
25810×
    let st = match view.bookmarks.get(&name) {
25820×
        Some(st) => *st,
25830×
        None => match oxy_core::repo::remote_bookmark(&view, &name) {
25840×
            Some((_, _, st)) => st,
25850×
            None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"),
2586
        },
2587
    };
25880×
    let heads = repo.store().get_state(&st)?.heads;
25890×
    let shown = heads_newest_first(&repo, &heads);
25900×
    if as_json {
25910×
        println!(
2592
            "{}",
25930×
            json::obj([
25940×
                ("name", json::s(&name)),
25950×
                ("current", json::b(name == repo.config.bookmark)),
2596
                (
25970×
                    "heads",
25980×
                    json::arr(shown.iter().map(|(h, m)| {
25990×
                        json::obj([
26000×
                            ("hash", json::s(&h.to_hex())),
26010×
                            ("id", json::s(&m.change_id.to_string())),
26020×
                            ("author", json::s(&author_name(&repo, m))),
26030×
                            ("time_ms", json::n(m.hlc.wall_ms)),
26040×
                            ("subject", json::s(subject_of(&m.message))),
26050×
                        ])
26060×
                    }))
2607
                ),
2608
            ])
2609
        );
26100×
        return Ok(0);
26110×
    }
26120×
    println!(
2613
        "{} {}{}{}",
26140×
        ui::ok(ui::glyph("●", "*")),
26150×
        ui::bookmark(&name),
26160×
        ui::sep(),
26170×
        ui::dim(plural(heads.len(), "head"))
2618
    );
26190×
    for (h, m) in &shown {
26200×
        print_head(&repo, "  ", h, m);
26210×
    }
26220×
    if heads.len() > 1 {
26230×
        println!(
26240×
            "  {}",
26250×
            ui::dim("None depends on another: the bookmark is all of them and their dependencies.")
26260×
        );
26270×
    }
26280×
    Ok(0)
26290×
}
2630
26315×
pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result<i32> {
26325×
    let repo = open()?;
26335×
    let remote_only = repo.remote_only_bookmarks()?;
26345×
    if as_json {
26355×
        let mut items: Vec<String> = repo
26365×
            .bookmarks()?
26375×
            .into_iter()
263813×
            .map(|b| {
263913×
                json::obj([
264013×
                    ("name", json::s(&b.name)),
264113×
                    ("heads", json::hashes(&b.heads)),
264213×
                    ("current", json::b(b.current)),
264313×
                    ("ahead", json::opt(b.ahead, json::n)),
264413×
                    ("behind", json::opt(b.behind, json::n)),
264513×
                    ("remote", json::opt(b.remote.as_deref(), json::s)),
264613×
                ])
264713×
            })
26485×
            .collect();
26495×
        if all {
26500×
            items.extend(remote_only.iter().map(|b| {
26510×
                json::obj([
26520×
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
26530×
                    ("heads", json::hashes(&b.heads)),
26540×
                    ("current", json::b(false)),
26550×
                    ("ahead", "null".into()),
26560×
                    ("behind", "null".into()),
26570×
                    ("remote", json::s(&b.remote)),
26580×
                ])
26590×
            }));
26605×
        }
26615×
        println!("{}", json::arr(items));
26625×
        return Ok(0);
26630×
    }
26640×
    for b in repo.bookmarks()? {
26650×
        let mark = if b.current {
26660×
            ui::ok(ui::glyph("●", "*"))
2667
        } else {
26680×
            ui::dim(ui::glyph("○", "o"))
2669
        };
26700×
        let mut tail = String::new();
26710×
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
26720×
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
26730×
        }
26740×
        if let Some(n) = b.behind.filter(|n| *n > 0) {
26750×
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
26760×
        }
2677
        // Which remote, when there is a choice (oxygen#83).
26780×
        if !tail.is_empty() && repo.config.remotes.len() > 1 {
26790×
            if let Some(r) = &b.remote {
26800×
                tail += &ui::dim(format!(" {r}"));
26810×
            }
26820×
        }
26830×
        let shown = heads_newest_first(&repo, &b.heads);
2684
        // The newest head's subject, so a busy bookmark shows its latest work.
26850×
        let head = match shown.first() {
26860×
            Some(_) if verbose => String::new(),
26870×
            Some((_, m)) if b.heads.len() > 1 => format!(
2688
                "{} {}",
26890×
                ui::dim("newest"),
26900×
                ui::subject(subject_of(&m.message))
2691
            ),
26920×
            Some((_, m)) => ui::subject(subject_of(&m.message)),
26930×
            None => ui::dim("(empty)"),
2694
        };
26950×
        let head = if head.is_empty() {
26960×
            head
2697
        } else {
26980×
            format!("  {head}")
2699
        };
27000×
        println!(
2701
            "{mark} {}{}{}{tail}{head}",
27020×
            ui::bookmark(&b.name),
27030×
            ui::sep(),
27040×
            ui::dim(plural(b.heads.len(), "head"))
2705
        );
27060×
        if verbose {
27070×
            for (h, m) in &shown {
27080×
                print_head(&repo, "    ", h, m);
27090×
            }
27100×
        }
2711
    }
27120×
    if remote_only.is_empty() {
27130×
        return Ok(0);
27140×
    }
27150×
    if !all {
27160×
        println!(
2717
            "{}",
27180×
            ui::dim(format!(
2719
                "  and {} only on a remote: oxy bookmark list --all",
27200×
                plural(remote_only.len(), "bookmark")
2721
            ))
2722
        );
27230×
        return Ok(0);
27240×
    }
27250×
    for b in &remote_only {
27260×
        println!(
27270×
            "{} {}{}{}",
27280×
            ui::dim(ui::glyph("◌", ".")),
27290×
            ui::dim(format!("{}/{}", b.remote, b.name)),
27300×
            ui::sep(),
27310×
            ui::dim(plural(b.heads.len(), "head"))
27320×
        );
27330×
    }
27340×
    println!(
2735
        "  {} {}",
27360×
        ui::note(),
27370×
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2738
    );
27390×
    Ok(0)
27405×
}
2741
27423×
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
27433×
    let mut repo = open()?;
27443×
    let from = repo.config.bookmark.clone();
27453×
    let (local, created_from) = repo.local_bookmark_for(name)?;
27463×
    if let Some(remote) = created_from {
27470×
        println!(
27480×
            "{} {} from {}",
27490×
            ui::done("Created"),
27500×
            ui::bookmark(&local),
27510×
            ui::dim(format!("{remote}/{local}"))
27520×
        );
27533×
    }
27543×
    let name = local.as_str();
2755
    // Only behind its remote: take the remote's state, so the switch does
2756
    // not check out a stale one (oxygen#74).
27573×
    if let Some(n) = repo.catch_up_bookmark(name)? {
27580×
        println!(
27590×
            "{} {} with {}: {} it lacked",
27600×
            ui::done("Caught up"),
27610×
            ui::bookmark(name),
27620×
            ui::dim(format!("{}/{name}", repo.default_remote())),
27630×
            plural(n, "change")
27640×
        );
27653×
    }
27663×
    let sp = ui::spinner(&format!("Switching to {name}…"));
27673×
    let (r, carried) = if carry {
27680×
        repo.bookmark_switch_carry(name)?
2769
    } else {
27703×
        (repo.bookmark_switch(name, discard)?, vec![])
2771
    };
27723×
    sp.done(&format!(
2773
        "{} to {}: {} written, {} removed{}",
27743×
        ui::done("Switched"),
27753×
        ui::bookmark(name),
27763×
        plural(r.written, "file"),
2777
        r.removed,
27783×
        if carried.is_empty() {
27793×
            String::new()
2780
        } else {
27810×
            format!("; carried {}", plural(carried.len(), "changed path"))
2782
        }
2783
    ));
27843×
    if r.conflicted {
27850×
        println!(
27860×
            "  {} {}",
27870×
            ui::caution(),
27880×
            ui::warn("this state has conflicts; see oxy status")
27890×
        );
27903×
    }
2791
    // Say when the new state leaves out work the old one had: a state is
2792
    // its heads and what they depend on, which can be far less than a Git
2793
    // user expects.
27943×
    if r.lacks > 0 {
27951×
        println!(
27961×
            "  {} {}",
27971×
            ui::note(),
27981×
            ui::dim(format!(
27991×
                "{name} lacks {} that {from} has",
28001×
                plural(r.lacks, "change")
28011×
            ))
28021×
        );
28032×
    }
28043×
    super::sync::subrepos_behind(&repo);
28053×
    where_now(&repo);
28063×
    Ok(0)
28073×
}
2808
28090×
pub fn merge(bookmark: &str) -> Result<i32> {
28100×
    let repo = open()?;
28110×
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
28120×
    let r = repo.merge(bookmark)?;
28130×
    if !r.changed {
28140×
        sp.done(&format!(
28150×
            "{} {}",
28160×
            ui::ok(ui::glyph("✔", "*")),
28170×
            ui::dim(format!(
28180×
                "{} already contains {bookmark}",
28190×
                repo.config.bookmark
28200×
            ))
28210×
        ));
28220×
        return Ok(0);
28230×
    }
28240×
    sp.done(&format!(
2825
        "{} {} into {}: now {}{}",
28260×
        ui::done("Merged"),
28270×
        ui::bookmark(bookmark),
28280×
        ui::bookmark(&repo.config.bookmark),
28290×
        plural(r.heads.len(), "head"),
28300×
        ui::dim(if r.checked_out {
28310×
            "; working copy updated"
2832
        } else {
28330×
            "; run oxy checkout to update the working copy"
2834
        })
2835
    ));
28360×
    let snap = repo.snapshot("oxy merge")?;
28370×
    if snap.base_snapshot.is_conflicted() {
28380×
        println!(
28390×
            "  {} {}",
28400×
            ui::caution(),
28410×
            ui::warn("the result has conflicts; see oxy status")
28420×
        );
28430×
    }
28440×
    where_now(&repo);
28450×
    Ok(0)
28460×
}
2847
28480×
pub fn squash(change: &str, into: &str) -> Result<i32> {
28490×
    let repo = open()?;
28500×
    let c = repo.resolve_change(change)?;
28510×
    let d = repo.resolve_change(into)?;
28520×
    let sp = ui::spinner("Squashing…");
28530×
    let h = repo.squash(&c, &d)?;
28540×
    let new = repo.store().get_change_meta(&h)?;
28550×
    sp.done(&format!(
28560×
        "{} into {} {}  {}",
28570×
        ui::done("Squashed"),
28580×
        ui::id(new.change_id.short(8)),
28590×
        ui::hash(format!("#{}", h.short(12))),
28600×
        ui::subject(subject_of(&new.message))
28610×
    ));
28620×
    Ok(0)
28630×
}
2864
28650×
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
28660×
    let repo = open()?;
28670×
    let c = repo.resolve_change(change)?;
28680×
    let mut heads = Vec::new();
28690×
    for o in onto {
28700×
        heads.extend(repo.resolve_heads(o)?);
2871
    }
28720×
    let sp = ui::spinner("Rebasing…");
28730×
    let h = match repo.rebase(&c, &heads) {
28740×
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
28750×
            let r = repo.rebase_into_working_copy(&c, &heads)?;
28760×
            sp.done(&format!(
28770×
                "{} {} into {}: now {}",
28780×
                ui::done("Merged"),
28790×
                onto.join(" "),
28800×
                ui::bookmark(&repo.config.bookmark),
28810×
                plural(r.heads.len(), "head"),
28820×
            ));
28830×
            if r.checked_out {
28840×
                println!(
28850×
                    "  {} {}",
28860×
                    ui::caution(),
28870×
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
28880×
                );
28890×
            } else {
28900×
                println!(
28910×
                    "  {} {}",
28920×
                    ui::caution(),
28930×
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
28940×
                );
28950×
            }
28960×
            where_now(&repo);
28970×
            return Ok(0);
2898
        }
28990×
        other => other?,
2900
    };
29010×
    let new = repo.store().get_change_meta(&h)?;
29020×
    sp.done(&format!(
29030×
        "{} {} {}  {}",
29040×
        ui::done("Rebased"),
29050×
        ui::id(new.change_id.short(8)),
29060×
        ui::hash(format!("#{}", h.short(12))),
29070×
        ui::dim(format!(
29080×
            "now depends on {}",
29090×
            plural(new.deps.len(), "change")
29100×
        ))
29110×
    ));
29120×
    where_now(&repo);
29130×
    Ok(0)
29140×
}
2915
2916
#[cfg(test)]
2917
mod tests {
2918
    use super::*;
2919
2920
    #[test]
29211×
    fn id_prefixes_agree_with_the_whole_list() {
2922
        // Ids that share long prefixes, and some that differ only in a
2923
        // half byte, from a fixed sequence.
29241×
        let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
29257999×
        let mut next = || {
29267999×
            x ^= x << 13;
29277999×
            x ^= x >> 7;
29287999×
            x ^= x << 17;
29297999×
            x
29307999×
        };
29311×
        let mut ids: Vec<[u8; 16]> = Vec::new();
29321×
        for _ in 0..2000 {
29332000×
            let mut id = [0u8; 16];
29342000×
            id[..8].copy_from_slice(&next().to_le_bytes());
29352000×
            id[8..].copy_from_slice(&next().to_le_bytes());
29362000×
            let share = (next() % 4) as usize;
29372000×
            if let Some(prev) = ids.last() {
29381999×
                id[..share].copy_from_slice(&prev[..share]);
29391999×
                if next() % 2 == 0 {
2940973×
                    id[share] = (prev[share] & 0xf0) | (id[share] & 0x0f);
29411026×
                }
29421×
            }
29432000×
            ids.push(id);
2944
        }
29454000×
        let hex = |id: &[u8; 16]| oxy_core::ids::ChangeId(*id).to_hex();
29461×
        let whole = unique_prefixes(ids.iter().map(hex));
29471×
        let some = id_prefixes(ids.clone(), ids.iter().copied());
29482000×
        for id in &ids {
29492000×
            assert_eq!(some[id], whole[&hex(id)], "{}", hex(id));
2950
        }
29511×
    }
2952
}