OXYGENHUB

Coverage / src/cli/workspace.rs 38.8%

905 of 2331 lines run, 88 of 325 functions · run #269 on main · run missed

1
//! Commands that act on the local repository and working copy.
2
3
use super::format::{
4
    author_name, deps_line, deps_of, plural, short_id, signature_line, signature_mark_of,
5
    subject_of, via, when,
6
};
7
use super::json;
8
use super::open;
9
use super::ui;
10
use anyhow::Result;
11
use oxy_core::objects::ChangeKind;
12
use oxy_core::repo::SignatureStatus;
13
use oxy_core::repo::{render_change, ChangeStatus, Repo};
14
use std::io::Write;
15
use std::path::PathBuf;
16
1712×
pub fn init(path: Option<PathBuf>, bare: bool, store: Option<&str>) -> Result<i32> {
1812×
    let path = path.unwrap_or(std::env::current_dir()?);
1912×
    let repo = Repo::init_new(&path, bare, store)?;
2012×
    println!(
21
        "{} {}oxy repository in {}",
2212×
        ui::done("Initialized"),
2312×
        if bare { "bare " } else { "" },
2412×
        ui::path(repo.root().display())
25
    );
2612×
    println!(
27
        "{}",
2812×
        ui::kv("bookmark", ui::bookmark(&repo.config.bookmark))
29
    );
3012×
    if let Some(url) = &repo.config.storage_url {
310×
        println!(
320×
            "{}",
330×
            ui::kv(
340×
                "store",
350×
                format!(
360×
                    "{url} (cache in {}, up to {} MiB)",
370×
                    ui::path(repo.root().join(".oxy/cache").display()),
380×
                    repo.config.storage_cache >> 20
390×
                )
400×
            )
410×
        );
4212×
    }
4312×
    println!(
44
        "{}",
4512×
        ui::kv(
4612×
            "author",
4712×
            format!(
48
                "{} <{}>",
4912×
                ui::author(&repo.config.author_name),
50
                repo.config.author_email
51
            )
52
        )
53
    );
5412×
    Ok(0)
5512×
}
56
572×
fn status_tag(s: ChangeStatus) -> &'static str {
582×
    match s {
591×
        ChangeStatus::Added => "A",
600×
        ChangeStatus::Modified => "M",
610×
        ChangeStatus::Removed => "D",
620×
        ChangeStatus::Renamed => "R",
631×
        ChangeStatus::ModeChanged => "X",
640×
        ChangeStatus::ConflictEdited => "C!",
650×
        ChangeStatus::Resolved => "V",
66
    }
672×
}
68
69
/// Folders holding a repository of their own, which oxy leaves out (oxygen#43):
70
/// named, with how to track them.
7131×
fn print_untracked_nested(repo: &Repo, nested: &[String]) {
7231×
    if nested.is_empty() {
7329×
        return;
742×
    }
752×
    println!();
762×
    println!(
77
        "{} {}",
782×
        ui::section(ui::warn("Not tracked")),
792×
        ui::dim("folders holding a repository of their own")
80
    );
812×
    for p in nested {
822×
        let kind = if repo.root().join(p).join(".git").exists() {
832×
            "Git"
84
        } else {
850×
            "Oxygen"
86
        };
872×
        println!(
88
            "  {} {}  {}",
892×
            ui::caution(),
902×
            ui::path(format!("{p}/")),
912×
            ui::dim(format!("a nested {kind} repository"))
92
        );
93
    }
942×
    println!(
95
        "  {} {}",
962×
        ui::note(),
972×
        ui::dim(
98
            "to track one's files, remove its .git (or .oxy); to keep it a repository of its own, \
99
             oxy submodule add URL PATH; to leave it out quietly, list it in .oxyignore"
100
        )
101
    );
10231×
}
103
104
/// The working copy's changed paths, or that it is clean.
1055×
fn print_statuses(statuses: &[oxy_core::repo::PathStatus]) {
1065×
    if statuses.is_empty() {
1073×
        println!(
108
            "  {} {}",
1093×
            ui::ok(ui::glyph("✔", "*")),
1103×
            ui::dim("nothing to commit, working copy clean")
111
        );
1123×
        return;
1132×
    }
1142×
    println!();
1152×
    for s in statuses {
1162×
        println!(
1172×
            "  {} {}",
1182×
            ui::status_mark(status_tag(s.status)),
1192×
            ui::path(&s.path)
1202×
        );
1212×
    }
1225×
}
123
124
/// Say when the working copy has fallen behind its own bookmark: a
125
/// "clean" status there hid a pull that left it on old code (oxygen#89).
1265×
fn print_behind(repo: &Repo) {
1275×
    if let Ok(Some(n)) = repo.working_copy_behind() {
1280×
        println!(
1290×
            "  {} {}",
1300×
            ui::caution(),
1310×
            ui::warn(format!(
1320×
                "the working copy is behind {}: it lacks {} the bookmark has; oxy checkout brings it up",
1330×
                repo.config.bookmark,
1340×
                plural(n, "change")
1350×
            ))
1360×
        );
1375×
    }
1385×
}
139
1408×
pub fn status(json: bool) -> Result<i32> {
1418×
    let repo = open()?;
142
    // Answered by the manifest alone, with no history to load (oxygen#35,
143
    // #41): a clean working copy, or one as the last snapshot left it.
1448×
    let known = if json {
1453×
        None
146
    } else {
1475×
        repo.status_by_manifest()?
148
    };
1498×
    if let Some(statuses) = known {
1503×
        let (_, wc) = repo.working_copy()?;
1513×
        let heads = repo.bookmark_heads()?;
1523×
        println!(
153
            "{} {}{}working copy {}{}{}",
1543×
            ui::dim("On"),
1553×
            ui::bookmark(&repo.config.bookmark),
1563×
            ui::sep(),
1573×
            ui::id(wc.change_id.short(8)),
1583×
            ui::sep(),
1593×
            ui::dim(plural(heads.len(), "head"))
160
        );
1613×
        print_behind(&repo);
1623×
        print_statuses(&statuses);
1633×
        print_untracked_nested(&repo, &repo.untracked_nested());
1643×
        return Ok(0);
1655×
    }
1665×
    let sp = ui::spinner("Snapshotting the working copy…");
1675×
    let snap = repo.snapshot_status("oxy status")?;
1685×
    let heads = {
1695×
        let _t = oxy_core::timing::phase("status: heads");
1705×
        repo.bookmark_heads()?
171
    };
1725×
    let _drop = oxy_core::timing::phase("status: print and drop");
1735×
    sp.clear();
1745×
    if json {
1753×
        println!("{}", repo.status_json(&snap)?);
1763×
        return Ok(if snap.base_snapshot.is_conflicted() {
1770×
            2
178
        } else {
1793×
            0
180
        });
1812×
    }
1822×
    println!(
183
        "{} {}{}working copy {}{}{}",
1842×
        ui::dim("On"),
1852×
        ui::bookmark(&repo.config.bookmark),
1862×
        ui::sep(),
1872×
        ui::id(snap.wc.change_id.short(8)),
1882×
        ui::sep(),
1892×
        ui::dim(plural(heads.len(), "head"))
190
    );
1912×
    print_behind(&repo);
1922×
    print_statuses(&snap.statuses);
1932×
    print_untracked_nested(&repo, &snap.untracked_nested);
1942×
    if !snap.base_snapshot.is_conflicted() {
1952×
        return Ok(0);
1960×
    }
1970×
    println!();
1980×
    println!(
199
        "{} {}",
2000×
        ui::section(ui::err("Conflicts")),
2010×
        ui::dim("edit the marked files, or the .oxy-conflict-N candidates, then commit")
202
    );
2030×
    for c in &snap.base_snapshot.tree.conflicts {
2040×
        println!("  {} tree: {c:?}", ui::err(ui::glyph("✱", "!")));
2050×
    }
2060×
    for (p, f) in &snap.base_snapshot.files {
2070×
        if f.is_conflicted() {
2080×
            let state = match snap
2090×
                .statuses
2100×
                .iter()
2110×
                .find(|s| s.path == *p)
2120×
                .map(|s| s.status)
213
            {
214
                Some(ChangeStatus::Resolved) => {
2150×
                    ui::ok(format!("{} resolved in working copy", ui::glyph("✔", "*")))
216
                }
217
                Some(ChangeStatus::ConflictEdited) => {
2180×
                    ui::warn(format!("{} markers remain", ui::glyph("‼", "!")))
219
                }
2200×
                _ => ui::err(format!("{} unresolved", ui::glyph("✱", "!"))),
221
            };
2220×
            println!("  {}  {state}", ui::path(p));
2230×
        }
224
    }
2250×
    Ok(2)
2268×
}
227
22826×
pub fn commit(
22926×
    message: &str,
23026×
    depends_on: &[String],
23126×
    paths: &[String],
23226×
    interactive: bool,
23326×
    hunks: &[usize],
23426×
) -> Result<i32> {
23526×
    let repo = open()?;
23626×
    let mut deps = Vec::new();
23726×
    for d in depends_on {
2380×
        deps.push(repo.resolve_change(d)?);
239
    }
24026×
    let selection = if !hunks.is_empty() {
2411×
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
24225×
    } else if interactive {
2430×
        let (_, hunks) = repo.hunks()?;
2440×
        if hunks.is_empty() {
2450×
            anyhow::bail!("nothing to commit: the working copy matches its base");
2460×
        }
2470×
        let hunks: Vec<_> = hunks
2480×
            .into_iter()
2490×
            .filter(|h| {
2500×
                paths.is_empty()
2510×
                    || paths.iter().any(|p| {
2520×
                        h.path == *p || h.path.starts_with(&format!("{}/", p.trim_end_matches('/')))
2530×
                    })
2540×
            })
2550×
            .collect();
2560×
        let mut chosen = Vec::new();
2570×
        let stdin = std::io::stdin();
2580×
        let mut take_rest = false;
2590×
        for (n, h) in hunks.iter().enumerate() {
2600×
            if take_rest {
2610×
                chosen.push(h.index);
2620×
                continue;
2630×
            }
2640×
            println!(
265
                "{} {} {}",
2660×
                ui::section(format!("hunk {} of {}", n + 1, hunks.len())),
2670×
                ui::path(&h.path),
2680×
                ui::dim(format!("(#{})", h.index))
269
            );
2700×
            for line in h.text.lines() {
2710×
                let styled = if line.starts_with('+') {
2720×
                    ui::ok(line)
2730×
                } else if line.starts_with('-') {
2740×
                    ui::err(line)
275
                } else {
2760×
                    ui::dim(line)
277
                };
2780×
                println!("  {styled}");
279
            }
280
            loop {
2810×
                print!(
282
                    "{} ",
2830×
                    ui::warn("Commit this hunk? [y]es [n]o [a]ll remaining [q]uit:")
284
                );
285
                use std::io::Write as _;
2860×
                std::io::stdout().flush()?;
2870×
                let mut answer = String::new();
2880×
                if stdin.read_line(&mut answer)? == 0 {
2890×
                    anyhow::bail!("aborted");
2900×
                }
2910×
                match answer.trim() {
2920×
                    "y" | "Y" => {
2930×
                        chosen.push(h.index);
2940×
                        break;
295
                    }
2960×
                    "n" | "N" | "" => break,
2970×
                    "a" | "A" => {
2980×
                        chosen.push(h.index);
2990×
                        take_rest = true;
3000×
                        break;
301
                    }
3020×
                    "q" | "Q" => anyhow::bail!("aborted; nothing committed"),
3030×
                    _ => continue,
304
                }
305
            }
306
        }
3070×
        if chosen.is_empty() {
3080×
            anyhow::bail!("no hunks chosen; nothing committed");
3090×
        }
3100×
        oxy_core::repo::Selection::Hunks(chosen)
31125×
    } else if paths.is_empty() {
31223×
        oxy_core::repo::Selection::All
313
    } else {
3142×
        oxy_core::repo::Selection::Paths(paths.to_vec())
315
    };
31626×
    let sp = ui::spinner("Committing…");
31726×
    let (h, partial) = repo.commit_selection_partial(message, &deps, &selection)?;
318
    // The metadata only: a first commit's change holds the whole tree.
31926×
    let meta = repo.store().get_change_meta(&h)?;
32026×
    sp.done(&format!(
32126×
        "{} {} {}  {}",
32226×
        ui::done("Committed"),
32326×
        ui::id(meta.change_id.short(8)),
32426×
        ui::hash(format!("#{}", h.short(12))),
32526×
        ui::subject(subject_of(message))
32626×
    ));
32726×
    print_untracked_nested(&repo, &repo.untracked_nested());
328
    // Only a commit that took part of the working copy leaves anything.
32926×
    if partial {
3302×
        let rest = repo.snapshot_status("oxy commit")?;
3312×
        if !rest.statuses.is_empty() {
3322×
            println!(
3332×
                "  {} {}",
3342×
                ui::note(),
3352×
                ui::dim(format!(
3362×
                    "{} left uncommitted",
3372×
                    plural(rest.statuses.len(), "path")
3382×
                ))
3392×
            );
3402×
        }
34124×
    }
34226×
    where_now(&repo);
34326×
    Ok(0)
34426×
}
345
3460×
pub fn blame(path: &str, json: bool) -> Result<i32> {
3470×
    let repo = open()?;
3480×
    let lines = repo.blame(path)?;
3490×
    if json {
3500×
        let items = lines.iter().map(|l| {
3510×
            format!(
352
                "{{\"line\":{},\"change_id\":{},\"hash\":{},\"index\":{},\"author\":{},\"when_ms\":{}}}",
353
                l.line,
3540×
                oxy_core::repo::json_str(&l.change_id.to_hex()),
3550×
                oxy_core::repo::json_str(&l.hash.to_hex()),
356
                l.index,
3570×
                oxy_core::repo::json_str(&l.author),
358
                l.when_ms
359
            )
3600×
        });
3610×
        println!("{}", oxy_core::repo::json_array(items));
3620×
        return Ok(0);
3630×
    }
3640×
    let width = lines
3650×
        .iter()
3660×
        .map(|l| l.author.chars().count())
3670×
        .max()
3680×
        .unwrap_or(0)
3690×
        .min(20);
3700×
    let digits = lines.len().to_string().len();
3710×
    let _t = oxy_core::timing::phase("blame: print");
372
    // Most lines share their change with many others: each change's id,
373
    // author and age are formatted once, and the lines go out through one
374
    // buffered lock on stdout.
3750×
    let mut prefix: std::collections::HashMap<oxy_core::hash::ChangeHash, String> =
3760×
        std::collections::HashMap::new();
3770×
    let bar = ui::dim(ui::glyph("│", "|"));
3780×
    let mut out = std::io::BufWriter::with_capacity(1 << 16, std::io::stdout().lock());
3790×
    for l in &lines {
3800×
        let p = prefix.entry(l.hash).or_insert_with(|| {
3810×
            let author: String = l.author.chars().take(20).collect();
3820×
            format!(
383
                "{} {} {}",
3840×
                ui::id(l.change_id.short(8)),
3850×
                ui::author(format!("{author:<width$}")),
3860×
                ui::dim(ui::ago(l.when_ms))
387
            )
3880×
        });
3890×
        let text = String::from_utf8_lossy(&l.text);
3900×
        if writeln!(
3910×
            out,
392
            "{p} {:>digits$}{bar} {}",
393
            l.line,
3940×
            text.trim_end_matches('\n')
395
        )
3960×
        .is_err()
397
        {
398
            // A closed pipe (blame | head): stop quietly.
3990×
            return Ok(0);
4000×
        }
401
    }
4020×
    let _ = out.flush();
4030×
    Ok(0)
4040×
}
405
4060×
fn bisect_report(repo: &Repo, step: &oxy_core::repo::BisectStep) -> Result<i32> {
407
    use oxy_core::repo::BisectStep::*;
4080×
    match step {
4090×
        NeedMarks { good, bad } => {
4100×
            println!(
411
                "{} {} {}",
4120×
                ui::note(),
4130×
                ui::dim(format!("{good} good, {bad} bad;")),
4140×
                ui::dim(if *good == 0 {
4150×
                    "mark a known-good change or bookmark: oxy bisect good CHANGE"
416
                } else {
4170×
                    "mark a known-bad change or bookmark: oxy bisect bad CHANGE"
418
                })
419
            );
4200×
            Ok(0)
421
        }
422
        Testing {
4230×
            heads,
4240×
            remaining,
4250×
            steps_left,
426
        } => {
4270×
            println!(
428
                "{} {} {}",
4290×
                ui::done("Testing"),
4300×
                ui::dim(format!(
431
                    "{} in the state under test;",
4320×
                    plural(heads.len(), "head")
433
                )),
4340×
                ui::dim(format!(
435
                    "{remaining} candidates left, about {steps_left} more steps"
436
                ))
437
            );
4380×
            println!(
439
                "  {} {}",
4400×
                ui::note(),
4410×
                ui::dim("run your test, then oxy bisect good | bad | skip")
442
            );
4430×
            Ok(0)
444
        }
4450×
        Found { culprit } => {
4460×
            let c = repo.store().get_change(culprit)?;
4470×
            println!(
448
                "{} {} {}  {}",
4490×
                ui::done("Found"),
4500×
                ui::id(short_id(&c)),
4510×
                ui::hash(format!("#{}", culprit.short(12))),
4520×
                ui::subject(subject_of(&c.message))
453
            );
4540×
            println!("  {} {}", ui::note(), ui::dim("the first change whose inclusion makes the state bad; oxy bisect reset to return"));
4550×
            Ok(0)
456
        }
4570×
        Inconclusive { candidates } => {
4580×
            println!(
459
                "{} {}",
4600×
                ui::caution(),
4610×
                ui::warn(format!(
462
                    "every remaining candidate was skipped ({}); oxy bisect reset to return",
4630×
                    plural(candidates.len(), "change")
464
                ))
465
            );
4660×
            Ok(1)
467
        }
468
    }
4690×
}
470
4710×
pub fn bisect_start() -> Result<i32> {
4720×
    let repo = open()?;
4730×
    repo.bisect_start()?;
4740×
    println!(
475
        "{} bisect; {}",
4760×
        ui::done("Started"),
4770×
        ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE")
478
    );
4790×
    Ok(0)
4800×
}
481
4820×
pub fn bisect_mark(good: Option<bool>, changes: &[String]) -> Result<i32> {
4830×
    let repo = open()?;
4840×
    let mut heads = Vec::new();
4850×
    for c in changes {
4860×
        heads.extend(repo.resolve_heads(c)?);
487
    }
4880×
    let step = repo.bisect_mark(good, &heads)?;
4890×
    bisect_report(&repo, &step)
4900×
}
491
4920×
pub fn bisect_run(command: &[String]) -> Result<i32> {
4930×
    let repo = open()?;
4940×
    let step = repo.bisect_run(command)?;
4950×
    bisect_report(&repo, &step)
4960×
}
497
4981×
pub fn bisect_status(as_json: bool) -> Result<i32> {
4991×
    let repo = open()?;
5001×
    if as_json {
501
        use oxy_core::repo::BisectStep::*;
5021×
        let v = match repo.bisect_status()? {
5031×
            None => "null".to_string(),
5040×
            Some(NeedMarks { good, bad }) => json::obj([
5050×
                ("state", json::s("need-marks")),
5060×
                ("good", json::n(good)),
5070×
                ("bad", json::n(bad)),
5080×
            ]),
509
            Some(Testing {
5100×
                heads,
5110×
                remaining,
5120×
                steps_left,
5130×
            }) => json::obj([
5140×
                ("state", json::s("testing")),
5150×
                ("heads", json::hashes(&heads)),
5160×
                ("remaining", json::n(remaining)),
5170×
                ("steps_left", json::n(steps_left)),
5180×
            ]),
5190×
            Some(Found { culprit }) => json::obj([
5200×
                ("state", json::s("found")),
5210×
                ("culprit", json::s(&culprit.to_hex())),
5220×
            ]),
5230×
            Some(Inconclusive { candidates }) => json::obj([
5240×
                ("state", json::s("inconclusive")),
5250×
                ("candidates", json::hashes(&candidates)),
5260×
            ]),
527
        };
5281×
        println!("{v}");
5291×
        return Ok(0);
5300×
    }
5310×
    match repo.bisect_status()? {
532
        None => {
5330×
            println!("{}", ui::dim("No bisect in progress."));
5340×
            Ok(0)
535
        }
5360×
        Some(step) => bisect_report(&repo, &step),
537
    }
5381×
}
539
5400×
pub fn bisect_reset() -> Result<i32> {
5410×
    let repo = open()?;
5420×
    repo.bisect_reset()?;
5430×
    println!("{} bisect; working copy restored", ui::done("Reset"));
5440×
    Ok(0)
5450×
}
546
547
/// The log: one entry per change, newest first, joined by a rail. The
548
/// default view is the subject and a metadata line; `verbose` adds the full
549
/// message, dependencies, and the authenticating key.
55014×
fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
55114×
    Ok(match repo.authenticate_change(h)? {
5529×
        SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]),
553
        SignatureStatus::Valid {
5545×
            key,
5555×
            name,
5565×
            email,
5575×
            sealed,
5585×
            revoked,
5595×
        } => json::obj([
5605×
            ("status", json::s(if sealed { "sealed" } else { "signed" })),
5615×
            ("key", json::s(&key.to_hex())),
5625×
            ("name", json::s(&name)),
5635×
            ("email", json::s(&email)),
5645×
            ("revoked", json::b(revoked)),
565
        ]),
5660×
        SignatureStatus::Invalid(why) => {
5670×
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
568
        }
569
    })
57014×
}
571
57218×
fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result<String> {
57318×
    let c = &e.change;
57418×
    Ok(json::obj([
57518×
        ("hash", json::s(&e.hash.to_hex())),
57618×
        ("change_id", json::s(&c.change_id.to_hex())),
57718×
        ("author", json::s(&author_name(repo, c))),
57818×
        ("author_key", json::s(&c.author.to_hex())),
579
        (
58018×
            "via",
58118×
            match via(
58218×
                repo,
58318×
                &repo.authenticate_change_known(&e.hash, Some(c))?,
58418×
                &c.author,
585
            ) {
5860×
                Some(v) => json::obj([
5870×
                    ("name", json::s(&v.name)),
5880×
                    ("email", json::s(&v.email)),
5890×
                    ("key", json::s(&v.key.to_hex())),
5900×
                    ("scope", json::opt(v.scope.as_deref(), json::s)),
5910×
                    ("expires_ms", json::opt(v.expires, json::n)),
5920×
                    ("revoked", json::b(v.revoked)),
5930×
                ]),
59418×
                None => "null".to_string(),
595
            },
596
        ),
59718×
        ("when_ms", json::n(c.hlc.wall_ms)),
59818×
        ("message", json::s(&c.message)),
59918×
        ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())),
60018×
        ("deps", json::hashes(&c.deps)),
60118×
        ("head", json::b(e.is_head)),
60218×
        ("working_copy", json::b(e.is_working_copy)),
603
        (
60418×
            "signature",
60518×
            if e.is_working_copy {
6064×
                "null".into()
607
            } else {
60814×
                signature_json(repo, &e.hash)?
609
            },
610
        ),
611
    ]))
61218×
}
613
614
/// `START,END:PATH` for `oxy log -L`.
6152×
fn parse_line_range(spec: &str) -> Result<(usize, usize, &str)> {
6162×
    let bad = || anyhow::anyhow!("-L {spec}: expected START,END:PATH, as 10,24:src/lib.rs");
6172×
    let (range, path) = spec.split_once(':').ok_or_else(bad)?;
6182×
    let (a, b) = range.split_once(',').ok_or_else(bad)?;
619
    Ok((
6201×
        a.trim().parse().map_err(|_| bad())?,
6211×
        b.trim().parse().map_err(|_| bad())?,
6221×
        path,
623
    ))
6242×
}
625
6268×
pub fn log(
6278×
    revset: Option<&str>,
6288×
    limit: Option<usize>,
6298×
    verbose: bool,
6308×
    path: Option<&str>,
6318×
    lines: Option<&str>,
6328×
    as_json: bool,
6338×
) -> Result<i32> {
6348×
    let repo = open()?;
635
    // Whether the working copy is clean and conflicted: from the manifest
636
    // when it proves the working copy clean, else from a snapshot.
637
    // The working copy as last recorded, without looking at the files (as
638
    // Git's log does not): whether its change holds edits, and whether its
639
    // base was conflicted. `oxy status` is what checks the disk.
6408×
    let conflicted = !repo.is_at_op() && repo.recorded_conflicted()?;
6418×
    let listing = oxy_core::timing::phase("log: entries");
6428×
    let entries = match (path, lines) {
6438×
        _ if revset.is_some() => repo.log_revset(revset.unwrap_or_default())?,
6442×
        (_, Some(spec)) => {
6452×
            let (first, last, p) = parse_line_range(spec)?;
6461×
            let (_, wc) = repo.working_copy()?;
6471×
            let base = repo.load_state_history(&wc.deps)?.maximal(&wc.deps);
6481×
            repo.line_history(&base, p, first, last)?
649
        }
6501×
        (Some(p), None) => repo.log_for_path(p)?,
6515×
        (None, None) => repo.log()?,
652
    };
6537×
    drop(listing);
6547×
    let _print = oxy_core::timing::phase("log: print");
6557×
    if as_json {
6566×
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
6576×
        let mut items = Vec::new();
65817×
        for e in entries.iter().take(shown) {
65917×
            items.push(log_entry_json(&repo, e)?);
660
        }
6616×
        println!(
662
            "{}",
6636×
            json::obj([
6646×
                ("bookmark", json::s(&repo.config.bookmark)),
6656×
                ("total", json::n(entries.len())),
6666×
                ("changes", json::arr(items))
6676×
            ])
668
        );
6696×
        return Ok(0);
6701×
    }
6711×
    let total = entries.len();
6721×
    let shown = limit.unwrap_or(total).min(total);
673
    // Lay out a little past what is shown, so edges into the cut are drawn.
6741×
    let window: Vec<(ChangeHash, Vec<ChangeHash>)> = entries
6751×
        .iter()
6761×
        .take((shown + MAX_EDGE).min(total))
6774×
        .map(|e| (e.hash, e.change.deps.clone()))
6781×
        .collect();
6791×
    let rows = oxy_core::lanes::graph(&window, MAX_EDGE);
680
    // Highlight the shortest prefix that names each change: against the
681
    // whole log, which is what `resolve_change` searches.
682
    let everything;
6831×
    let all = if path.is_some() || lines.is_some() || revset.is_some() {
6840×
        everything = repo.log()?;
6850×
        &everything
686
    } else {
6871×
        &entries
688
    };
6891×
    let prefixes = oxy_core::timing::phase("log: id prefixes");
6901×
    let id_prefix = id_prefixes(
6911×
        all.iter().map(|e| e.change.change_id.0).collect(),
6921×
        entries.iter().take(shown).map(|e| e.change.change_id.0),
693
    );
6941×
    drop(prefixes);
6951×
    let labels = reference_labels(&repo)?;
6964×
    for (e, row) in entries.iter().take(shown).zip(&rows) {
6974×
        let c = &e.change;
6984×
        let bullet = ui::log_bullet(
6994×
            e.is_working_copy,
7004×
            e.is_head,
7014×
            e.is_working_copy && conflicted,
702
        );
7034×
        let id = c.change_id.to_hex();
7044×
        let n = id_prefix.get(&c.change_id.0).copied().unwrap_or(8).min(8);
7054×
        let mut head = vec![format!("{}{}", ui::id(&id[..n]), ui::dim(&id[n..8]))];
7064×
        head.push(ui::author(author_name(&repo, c)));
7074×
        head.push(ui::dim(ui::ago(c.hlc.wall_ms)));
7084×
        if let Some(names) = labels.get(&e.hash) {
7092×
            head.push(names.join(" "));
7102×
        }
7114×
        if c.kind == ChangeKind::Resolution {
7120×
            head.push(ui::warn("resolution"));
7134×
        }
7144×
        if !e.is_working_copy {
7153×
            head.push(ui::hash(format!("#{}", e.hash.short(8))));
7163×
            let status = repo.authenticate_change_known(&e.hash, Some(c))?;
7173×
            if let Some(agent) = via(&repo, &status, &c.author) {
7180×
                head.push(ui::dim(format!("via {}", agent.name)));
7193×
            }
7203×
            head.push(signature_mark_of(&status));
7211×
        }
7224×
        println!("{}{}", node_line(row, &bullet), head.join(" "));
7234×
        let subject = if e.is_working_copy && c.message.is_empty() {
7241×
            let edited = repo
7251×
                .store()
7261×
                .get_change(&e.hash)
7271×
                .is_ok_and(|w| !w.tree_ops.is_empty() || !w.edits.is_empty());
7281×
            ui::dim(if edited {
7290×
                "(working copy, uncommitted changes)"
730
            } else {
7311×
                "(working copy)"
732
            })
7333×
        } else if c.message.trim().is_empty() {
7340×
            ui::dim("(no description)")
735
        } else {
7363×
            subject_of(&c.message).to_string()
737
        };
7384×
        println!("{}{subject}", below_line(row));
7394×
        if verbose {
7400×
            let rail = continuation(row);
7410×
            if !e.is_working_copy {
7420×
                println!(
743
                    "{rail}{}",
7440×
                    ui::dim(format!(
745
                        "{} {}",
7460×
                        when(c.hlc.wall_ms),
7470×
                        signature_line(&repo, &e.hash)?
748
                    ))
749
                );
7500×
            }
7510×
            if !c.deps.is_empty() {
7520×
                println!(
7530×
                    "{rail}{} {}",
7540×
                    ui::dim(ui::glyph("↳", "->")),
7550×
                    ui::dim(deps_of(&c.deps))
7560×
                );
7570×
            }
7580×
            let body: Vec<&str> = c
7590×
                .message
7600×
                .lines()
7610×
                .skip(1)
7620×
                .skip_while(|l| l.trim().is_empty())
7630×
                .collect();
7640×
            for line in body {
7650×
                println!("{rail}  {line}");
7660×
            }
7674×
        }
768
    }
7691×
    if shown < total {
7700×
        if let Some(last) = rows.get(shown.saturating_sub(1)) {
7710×
            let cut: String = last
7720×
                .below
7730×
                .iter()
7740×
                .map(|c| match c {
7750×
                    Cell::Blank | Cell::Elided | Cell::JoinRight => "  ",
7760×
                    _ => "~ ",
7770×
                })
7780×
                .collect();
7790×
            if cut.trim().is_empty() {
7800×
                println!("{}", ui::dim("~"));
7810×
            } else {
7820×
                println!("{}", ui::dim(cut.trim_end()));
7830×
            }
7840×
        }
7850×
        println!(
786
            "{}",
7870×
            ui::dim(format!(
788
                "{} {} more; pass -n to see them",
7890×
                ui::glyph("…", "..."),
7900×
                total - shown
791
            ))
792
        );
7931×
    }
7941×
    Ok(0)
7958×
}
796
797
/// Rows a drawn edge may span in `oxy log`; a longer one is elided (`~`).
798
const MAX_EDGE: usize = 12;
799
800
use oxy_core::hash::ChangeHash;
801
use oxy_core::lanes::{Cell, GraphRow};
802
803
/// A graph cell, two columns wide.
8046×
fn cell(c: Cell) -> &'static str {
8056×
    match c {
8061×
        Cell::Blank => "  ",
8073×
        Cell::Line => ui::glyph("│ ", "| "),
8080×
        Cell::Elided => "~ ",
8091×
        Cell::JoinLeft => ui::glyph("├─", "|-"),
8100×
        Cell::JoinPass => ui::glyph("──", "--"),
8110×
        Cell::JoinCross => ui::glyph("┼─", "+-"),
8121×
        Cell::JoinRight => ui::glyph("╯ ", "' "),
813
    }
8146×
}
815
816
/// The graph part of a change's own line, its bullet in its column.
8174×
fn node_line(row: &GraphRow, bullet: &str) -> String {
8184×
    let width = row
8194×
        .passing
8204×
        .iter()
8214×
        .copied()
8224×
        .max()
8234×
        .unwrap_or(0)
8244×
        .max(row.column)
8254×
        + 1;
8264×
    let mut out = String::new();
8275×
    for c in 0..width {
8285×
        if c == row.column {
8294×
            out.push_str(bullet);
8304×
            out.push(' ');
8314×
        } else if row.passing.contains(&c) {
8321×
            out.push_str(&ui::dim(cell(Cell::Line)));
8331×
        } else {
8340×
            out.push_str("  ");
8350×
        }
836
    }
8374×
    out.push(' ');
8384×
    out
8394×
}
840
841
/// The graph part of the line under a change: lanes carrying on, a join,
842
/// or `~` for an elided edge.
8434×
fn below_line(row: &GraphRow) -> String {
8445×
    let g: String = row.below.iter().map(|c| cell(*c)).collect();
8454×
    format!("{} ", ui::dim(g))
8464×
}
847
848
/// The graph part of any further line of a change (`-v`).
8490×
fn continuation(row: &GraphRow) -> String {
8500×
    let g: String = row
8510×
        .below
8520×
        .iter()
8530×
        .map(|c| match c {
8540×
            Cell::Line | Cell::JoinLeft | Cell::JoinCross => cell(Cell::Line),
8550×
            _ => "  ",
8560×
        })
8570×
        .collect();
8580×
    format!("{} ", ui::dim(g))
8590×
}
860
861
/// For each hex ID, the length of its shortest prefix no other ID shares.
862
/// The shortest prefix, in hex digits, that names each of `wanted` among
863
/// `all`: worked out for the few shown rather than for the whole history.
8642×
fn id_prefixes(
8652×
    mut all: Vec<[u8; 16]>,
8662×
    wanted: impl Iterator<Item = [u8; 16]>,
8672×
) -> std::collections::HashMap<[u8; 16], usize> {
8682×
    all.sort_unstable();
8692×
    all.dedup();
870
    // Hex digits two ids share at the start.
8714004×
    let common = |a: &[u8; 16], b: &[u8; 16]| {
87210720×
        let bytes = a.iter().zip(b).take_while(|(x, y)| x == y).count();
8734004×
        match (a.get(bytes), b.get(bytes)) {
8744004×
            (Some(x), Some(y)) if x >> 4 == y >> 4 => 2 * bytes + 1,
8751858×
            _ => 2 * bytes,
876
        }
8774004×
    };
8782×
    let mut out = std::collections::HashMap::new();
8792004×
    for id in wanted {
8802004×
        let Ok(i) = all.binary_search(&id) else {
8810×
            continue;
882
        };
8832004×
        let before = i.checked_sub(1).map_or(0, |j| common(&all[j], &id));
8842004×
        let after = all.get(i + 1).map_or(0, |n| common(&id, n));
8852004×
        out.insert(id, before.max(after) + 1);
886
    }
8872×
    out
8882×
}
889
8901×
fn unique_prefixes(ids: impl Iterator<Item = String>) -> std::collections::HashMap<String, usize> {
8911×
    let mut v: Vec<String> = ids.collect();
8921×
    v.sort();
8931×
    v.dedup();
89419576×
    let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
8951×
    let mut out = std::collections::HashMap::with_capacity(v.len());
8962000×
    for i in 0..v.len() {
8972000×
        let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 };
8982000×
        let after = if i + 1 < v.len() {
8991999×
            common(&v[i], &v[i + 1])
900
        } else {
9011×
            0
902
        };
9032000×
        out.insert(v[i].clone(), before.max(after) + 1);
904
    }
9051×
    out
9061×
}
907
908
/// Bookmark, remote bookmark and tag names to show beside the changes they
909
/// point at. A name is shown on each head of its state; one with more than
910
/// three heads names too much of the log to help, so it is left out (oxy
911
/// bookmark list shows it). A remote bookmark at the same state as the
912
/// local one of that name is not repeated.
9131×
fn reference_labels(repo: &Repo) -> Result<std::collections::HashMap<ChangeHash, Vec<String>>> {
914
    const MAX_HEADS: usize = 3;
9151×
    let view = repo.view()?;
9161×
    let mut out: std::collections::HashMap<ChangeHash, Vec<String>> = Default::default();
9171×
    let mut add = |heads: Vec<ChangeHash>, label: String| {
9181×
        if heads.len() <= MAX_HEADS {
9192×
            for h in heads {
9202×
                out.entry(h).or_default().push(label.clone());
9212×
            }
9220×
        }
9231×
    };
9241×
    for (name, st) in &view.bookmarks {
9251×
        add(repo.store().get_state(st)?.heads, ui::bookmark(name));
926
    }
9271×
    for (remote, bookmarks) in &view.remotes {
9280×
        for (name, st) in bookmarks {
9290×
            if view.bookmarks.get(name) == Some(st) {
9300×
                continue;
9310×
            }
9320×
            add(
9330×
                repo.store().get_state(st)?.heads,
9340×
                ui::dim(format!("{remote}/{name}")),
935
            );
936
        }
937
    }
9381×
    for t in repo.tags()? {
9390×
        add(t.heads.clone(), ui::warn(&t.name));
9400×
    }
9411×
    Ok(out)
9421×
}
943
9441×
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
9451×
    let repo = open()?;
9461×
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
9471×
    if as_json {
9481×
        let files = repo.diff_files(hash.as_ref())?;
9493×
        let items = files.iter().map(|f| {
9503×
            json::obj([
9513×
                ("path", json::s(&f.path)),
9523×
                ("kind", json::s(&f.kind)),
9533×
                ("from", json::opt(f.from.as_deref(), json::s)),
954
                (
9553×
                    "hunks",
9563×
                    json::arr(f.hunks.iter().map(|h| {
9573×
                        json::obj([
9583×
                            ("base_line", json::n(h.base_line)),
959
                            (
9603×
                                "added",
9613×
                                json::arr(
9623×
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
963
                                ),
964
                            ),
965
                            (
9663×
                                "removed",
9673×
                                json::arr(h.removed.iter().map(|(n, l)| {
9680×
                                    json::obj([
9690×
                                        ("line", json::n(*n)),
9700×
                                        ("text", json::s(&String::from_utf8_lossy(l))),
9710×
                                    ])
9720×
                                })),
973
                            ),
974
                        ])
9753×
                    })),
976
                ),
977
            ])
9783×
        });
9791×
        println!(
980
            "{}",
9811×
            json::obj([
9821×
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
9831×
                ("files", json::arr(items))
984
            ])
985
        );
9861×
        return Ok(0);
9870×
    }
9880×
    match hash {
9890×
        Some(h) => {
9900×
            let c = repo.store().get_change(&h)?;
9910×
            let (base, snapshot) = repo.change_base(&c)?;
9920×
            print!("{}", render_change(&c, &base, &snapshot));
993
        }
994
        None => {
9950×
            let (wc, base, snapshot) = repo.working_copy_with_base()?;
9960×
            let text = {
9970×
                let _t = oxy_core::timing::phase("diff: render the change");
9980×
                render_change(&wc, &base, &snapshot)
999
            };
10000×
            print!("{text}");
1001
            // The process ends here: freeing the base's tree and graphs
1002
            // one by one would only cost time (about 27 ms on Linux).
10030×
            std::mem::forget((wc, base, snapshot));
1004
        }
1005
    }
10060×
    Ok(0)
10071×
}
1008
10092×
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
10102×
    let repo = open()?;
10112×
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
10122×
    let bytes = match repo.file_at(path, heads.as_deref()) {
10132×
        Ok(b) => b,
1014
        // -r CHANGE reads that change's dependency closure, not the
1015
        // bookmark it is on: say so when the bookmark has the file
1016
        // (oxygen#76).
10170×
        Err(e) => match change {
10180×
            Some(c)
10190×
                if !repo.view()?.bookmarks.contains_key(c)
10200×
                    && repo.tag_heads(c)?.is_none()
10210×
                    && repo.file_at(path, None).is_ok() =>
1022
            {
10230×
                anyhow::bail!(
1024
                    "{path} is not in {c}'s dependency closure (the change and what it \
1025
                     depends on); it is on the bookmark: try -r {}, or --at-op OP for the \
1026
                     state at an operation",
1027
                    repo.config.bookmark
1028
                )
1029
            }
10300×
            _ => return Err(e.into()),
1031
        },
1032
    };
1033
    use std::io::Write as _;
10342×
    std::io::stdout().write_all(&bytes)?;
10352×
    Ok(0)
10362×
}
1037
10381×
pub fn root(as_json: bool) -> Result<i32> {
10391×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
10400×
        if as_json {
10410×
            println!("null");
10420×
        }
10430×
        return Ok(1);
1044
    };
10451×
    if as_json {
10461×
        println!(
10471×
            "{}",
10481×
            json::obj([
10491×
                ("root", json::s(&repo.root().to_string_lossy())),
10501×
                ("workspace", json::s(&repo.workspace().to_hex())),
10511×
                ("bookmark", json::s(&repo.config.bookmark))
10521×
            ])
10531×
        );
10541×
    } else {
10550×
        println!("{}", repo.root().display());
10560×
    }
10571×
    Ok(0)
10581×
}
1059
10601×
pub fn version(as_json: bool) -> Result<i32> {
10611×
    if as_json {
10621×
        println!(
10631×
            "{}",
10641×
            json::obj([
10651×
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
10661×
                // What was built: a release's or install's `oxy describe`,
10671×
                // a Flow build's heads, or "local build".
10681×
                ("build", json::s(env!("OXY_BUILD_ID"))),
10691×
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
10701×
                ("format", json::n(2))
10711×
            ])
10721×
        );
10731×
    } else {
10740×
        println!(
10750×
            "oxy {} (repository format 2, protocol {})",
10760×
            env!("OXY_VERSION_LONG"),
10770×
            oxy_core::protocol::PROTOCOL_VERSION
10780×
        );
10790×
    }
10801×
    Ok(0)
10811×
}
1082
10832×
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
10842×
    let repo = open()?;
10852×
    if paths.is_empty() && hunks.is_empty() {
10860×
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
10872×
    }
10882×
    let mut n = 0;
10892×
    if !hunks.is_empty() {
10901×
        n += repo.discard_hunks(hunks)?;
10911×
    }
10922×
    if !paths.is_empty() {
10931×
        n += repo.discard(paths)?;
10941×
    }
10952×
    println!(
1096
        "{} {} restored to the working copy's base",
10972×
        ui::done("Discarded"),
10982×
        plural(n, "path")
1099
    );
11002×
    Ok(0)
11012×
}
1102
11032×
pub fn hunks(as_json: bool) -> Result<i32> {
11042×
    let repo = open()?;
11052×
    let (_, hunks) = repo.hunks()?;
11062×
    if as_json {
11072×
        println!(
1108
            "{}",
11095×
            json::arr(hunks.iter().map(|h| json::obj([
11105×
                ("index", json::n(h.index)),
11115×
                ("path", json::s(&h.path)),
11125×
                ("text", json::s(&h.text))
11135×
            ])))
1114
        );
11152×
        return Ok(0);
11160×
    }
11170×
    if hunks.is_empty() {
11180×
        println!(
11190×
            "{}",
11200×
            ui::dim("No hunks: the working copy matches its base.")
11210×
        );
11220×
    }
11230×
    for h in &hunks {
11240×
        println!(
1125
            "{} {}",
11260×
            ui::section(format!("hunk {}", h.index)),
11270×
            ui::path(&h.path)
1128
        );
11290×
        for line in h.text.lines() {
11300×
            let styled = if line.starts_with('+') {
11310×
                ui::ok(line)
11320×
            } else if line.starts_with('-') {
11330×
                ui::err(line)
1134
            } else {
11350×
                ui::dim(line)
1136
            };
11370×
            println!("  {styled}");
1138
        }
1139
    }
11400×
    Ok(0)
11412×
}
1142
11432×
pub fn show(change: Option<&str>, revset: Option<&str>, as_json: bool) -> Result<i32> {
11442×
    let repo = open()?;
11452×
    repo.snapshot_status("oxy show")?;
11462×
    let Some(r) = revset else {
11472×
        let h = repo.resolve_change(change.unwrap_or("@"))?;
11482×
        return show_one(&repo, h, as_json, false);
1149
    };
1150
    // Several changes: a JSON array, or the changes one after another.
11510×
    let hashes = repo.revset(r)?.hashes;
11520×
    if as_json {
11530×
        print!("[");
11540×
        for (i, h) in hashes.iter().enumerate() {
11550×
            if i > 0 {
11560×
                print!(",");
11570×
            }
11580×
            show_one(&repo, *h, true, true)?;
1159
        }
11600×
        println!("]");
11610×
        return Ok(0);
11620×
    }
11630×
    if hashes.is_empty() {
11640×
        println!("{}", ui::dim(format!("No change matches {r:?}.")));
11650×
        return Ok(0);
11660×
    }
11670×
    for (i, h) in hashes.iter().enumerate() {
11680×
        if i > 0 {
11690×
            println!();
11700×
        }
11710×
        show_one(&repo, *h, false, false)?;
1172
    }
11730×
    Ok(0)
11742×
}
1175
1176
/// One change, as `oxy show` prints it; `inline` JSON goes without its
1177
/// newline, for an array.
11782×
fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool) -> Result<i32> {
11792×
    let c = repo.store().get_change(&h)?;
11802×
    if as_json {
11811×
        let files = repo.diff_files(Some(&h))?;
11821×
        let heads = repo.bookmark_heads()?;
11831×
        let entry = oxy_core::repo::LogEntry {
11841×
            hash: h,
11851×
            change: oxy_core::state::ChangeMeta::of(&c),
11861×
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
11871×
            is_head: heads.contains(&h),
11881×
        };
11891×
        let mut body = log_entry_json(repo, &entry)?;
11901×
        body.pop();
11911×
        body.push_str(&format!(
1192
            ",{}:{}}}",
11931×
            json::s("files"),
11941×
            json::arr(files.iter().map(|f| json::obj([
11951×
                ("path", json::s(&f.path)),
11961×
                ("kind", json::s(&f.kind)),
11971×
                ("from", json::opt(f.from.as_deref(), json::s))
11981×
            ])))
1199
        ));
12001×
        if inline {
12010×
            print!("{body}");
12021×
        } else {
12031×
            println!("{body}");
12041×
        }
12051×
        return Ok(0);
12061×
    }
12071×
    println!(
1208
        "{} {} {}",
12091×
        ui::section("change"),
12101×
        ui::id(short_id(&c)),
12111×
        ui::hash(format!("#{h}"))
1212
    );
12131×
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1214
    // Fetched but not pulled (oxygen#56): say where it is.
12151×
    if let Some(at) = repo.remote_only_location(&h)? {
12160×
        println!(
12170×
            "{}",
12180×
            ui::kv(
12190×
                "only in",
12200×
                ui::warn(format!(
12210×
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
12220×
                ))
12230×
            )
12240×
        );
12251×
    }
12261×
    let meta = oxy_core::state::ChangeMeta::of(&c);
12271×
    let status = repo.authenticate_change_known(&h, Some(&meta))?;
12281×
    println!("{}", ui::kv("author", ui::author(author_name(repo, &meta))));
12291×
    if let Some(agent) = via(repo, &status, &meta.author) {
12300×
        println!("{}", ui::kv("via", agent.line()));
12311×
    }
12321×
    println!(
1233
        "{}",
12341×
        ui::kv(
12351×
            "date",
12361×
            format!(
1237
                "{} {}",
12381×
                when(c.hlc.wall_ms),
12391×
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1240
            )
1241
        )
1242
    );
12431×
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
12441×
    println!("{}", ui::kv("sig", signature_line(repo, &h)?));
12451×
    println!();
12464×
    for line in (if c.message.is_empty() {
12470×
        "(no description)"
1248
    } else {
12491×
        &c.message
1250
    })
12511×
    .lines()
12524×
    {
12534×
        println!("    {line}");
12544×
    }
12551×
    println!();
12561×
    print!("{}", repo.describe_change(&h)?);
12571×
    Ok(0)
12582×
}
1259
12600×
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
12610×
    let repo = open()?;
1262
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1263
    // BRANCH` is: checking its files out under another bookmark's name
1264
    // made the next commit move the wrong bookmark (oxygen#60).
12650×
    if let [name] = changes {
12660×
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
12670×
            drop(repo);
12680×
            return bookmark_switch(name, discard, carry);
12690×
        }
12700×
    }
12710×
    let heads = if changes.is_empty() {
12720×
        repo.bookmark_heads()?
1273
    } else {
12740×
        let mut heads = Vec::new();
12750×
        for c in changes {
12760×
            heads.extend(repo.resolve_heads(c)?);
1277
        }
12780×
        heads
1279
    };
12800×
    let spec = if changes.is_empty() {
12810×
        repo.config.bookmark.clone()
1282
    } else {
12830×
        changes.join(" ")
1284
    };
12850×
    let sp = ui::spinner(&format!("Checking out {spec}…"));
12860×
    let command = format!("oxy checkout {spec}");
12870×
    let (r, carried) = if carry {
12880×
        repo.checkout_carry(&heads, &spec, &command)?
1289
    } else {
12900×
        (repo.checkout(&heads, discard, &command)?, vec![])
1291
    };
12920×
    sp.done(&format!(
1293
        "{} on {}: {} written, {} removed{}",
12940×
        ui::done("Working copy"),
12950×
        ui::bookmark(&spec),
12960×
        plural(r.written, "file"),
1297
        r.removed,
12980×
        if carried.is_empty() {
12990×
            String::new()
1300
        } else {
13010×
            format!("; carried {}", plural(carried.len(), "changed path"))
1302
        }
1303
    ));
13040×
    for n in &r.notes {
13050×
        println!("  {} {n}", ui::note());
13060×
    }
13070×
    if r.conflicted {
13080×
        println!(
13090×
            "  {} {}",
13100×
            ui::caution(),
13110×
            ui::warn("this state has conflicts; see oxy status")
13120×
        );
13130×
    }
13140×
    where_now(&repo);
13150×
    Ok(0)
13160×
}
1317
13181×
pub fn resolve(as_json: bool) -> Result<i32> {
13191×
    let repo = open()?;
13201×
    let snap = repo.snapshot("oxy resolve")?;
13211×
    if as_json {
13221×
        println!("{}", repo.status_json(&snap)?);
13231×
        return Ok(if snap.base_snapshot.is_conflicted() {
13240×
            2
1325
        } else {
13261×
            0
1327
        });
13280×
    }
13290×
    if !snap.base_snapshot.is_conflicted() {
13300×
        println!("The working copy's base has no conflicts.");
13310×
        return Ok(0);
13320×
    }
13330×
    let mut remaining = 0;
13340×
    for (p, f) in &snap.base_snapshot.files {
13350×
        if !f.is_conflicted() {
13360×
            continue;
13370×
        }
13380×
        match snap
13390×
            .statuses
13400×
            .iter()
13410×
            .find(|s| s.path == *p)
13420×
            .map(|s| s.status)
1343
        {
13440×
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
13450×
            Some(ChangeStatus::ConflictEdited) => {
13460×
                remaining += 1;
13470×
                println!("markers    {p}");
13480×
            }
13490×
            _ => {
13500×
                remaining += 1;
13510×
                println!("unresolved {p}");
13520×
            }
1353
        }
1354
    }
13550×
    for c in &snap.base_snapshot.tree.conflicts {
13560×
        remaining += 1;
13570×
        println!("tree       {c:?}");
13580×
    }
13590×
    if remaining == 0 {
13600×
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
13610×
        Ok(0)
1362
    } else {
13630×
        Ok(2)
1364
    }
13651×
}
1366
13670×
pub fn undo() -> Result<i32> {
13680×
    let repo = open()?;
13690×
    let u = repo.undo()?;
13700×
    println!("{} {}", ui::done("Undone:"), u.command);
13710×
    for c in &u.changes {
13720×
        println!("  {} {}", ui::note(), change_words(&repo, c));
13730×
    }
13740×
    if u.others_kept > 0 {
13750×
        let s = if u.others_kept == 1 { "" } else { "s" };
13760×
        println!(
1377
            "  {} {}",
13780×
            ui::note(),
13790×
            ui::dim(format!(
1380
                "{} newer operation{s} from other workspaces left as they are",
1381
                u.others_kept
1382
            ))
1383
        );
13840×
    }
13850×
    for (bookmark, remote) in &u.pushed {
13860×
        println!(
13870×
            "  {} {}",
13880×
            ui::caution(),
13890×
            ui::warn(format!(
13900×
                "{remote}/{bookmark} already has what this undid: undone here only; the next push of {bookmark} needs --force to take it back there"
13910×
            ))
13920×
        );
13930×
    }
13940×
    where_now(&repo);
13950×
    Ok(0)
13960×
}
1397
13981×
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
13991×
    let repo = open()?;
14001×
    let ops = repo.op_log()?;
1401
    // What each operation changed, against the one before it.
140211×
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
140311×
        match ops.get(i + 1) {
140410×
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
14051×
            None => Ok(vec![]),
1406
        }
140711×
    };
14081×
    if as_json {
14091×
        let mut items = Vec::new();
141011×
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
141111×
            let summary: Vec<String> = changes_of(i)?
141211×
                .iter()
141311×
                .map(|c| change_words(&repo, c))
141411×
                .collect();
141511×
            items.push(json::obj([
141611×
                ("id", json::s(&r.to_hex())),
141711×
                ("when_ms", json::n(op.hlc.wall_ms)),
141811×
                ("command", json::s(&op.command)),
141911×
                ("snapshot", json::b(op.is_snapshot())),
142011×
                ("current", json::b(i == 0)),
142111×
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1422
            ]));
1423
        }
14241×
        println!("{}", json::arr(items));
14251×
        return Ok(0);
14260×
    }
14270×
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
14280×
    let id = |r: &oxy_core::hash::ObjectRef| {
14290×
        let hex = r.to_hex();
14300×
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
14310×
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
14320×
    };
14330×
    let rail = ui::dim(ui::glyph("│", "|"));
14340×
    let (mut i, mut shown) = (0, 0);
14350×
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
14360×
        let (r, op) = &ops[i];
14370×
        let bullet = if i == 0 {
14380×
            ui::ok(ui::glyph("@", "@"))
1439
        } else {
14400×
            ui::dim(ui::glyph("○", "o"))
1441
        };
1442
        // A run of snapshots folds into one entry.
14430×
        let mut run = 1;
14440×
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
14450×
            run += 1;
14460×
        }
14470×
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
14480×
        if op.is_snapshot() {
14490×
            let span = if run > 1 {
14500×
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1451
            } else {
14520×
                String::new()
1453
            };
14540×
            println!(
1455
                "{bullet}  {}{} {when}",
14560×
                id(r),
14570×
                if span.is_empty() {
14580×
                    String::new()
1459
                } else {
14600×
                    format!(" {span}")
1461
                }
1462
            );
14630×
            println!(
1464
                "{rail}  {}",
14650×
                ui::dim(if run == 1 {
14660×
                    "working-copy snapshot".to_string()
1467
                } else {
14680×
                    format!("{run} working-copy snapshots")
1469
                })
1470
            );
1471
        } else {
14720×
            println!("{bullet}  {} {when}", id(r));
14730×
            let words: Vec<String> = changes_of(i)?
14740×
                .iter()
14750×
                .map(|c| change_words(&repo, c))
14760×
                .collect();
14770×
            let summary = if words.is_empty() {
14780×
                if i + 1 == ops.len() {
14790×
                    "created the repository".to_string()
1480
                } else {
14810×
                    "no bookmark or working-copy change".to_string()
1482
                }
1483
            } else {
14840×
                words.join("; ")
1485
            };
14860×
            println!(
1487
                "{rail}  {}",
14880×
                if i == 0 {
14890×
                    ui::subject(&summary)
1490
                } else {
14910×
                    summary
1492
                }
1493
            );
14940×
            let cmd = op.command.lines().next().unwrap_or("");
14950×
            let cmd: String = cmd.chars().take(100).collect();
14960×
            println!("{rail}  {}", ui::dim(cmd));
1497
        }
14980×
        i += run;
14990×
        shown += 1;
1500
    }
15010×
    if i < ops.len() {
15020×
        println!(
15030×
            "{}",
15040×
            ui::dim(format!(
15050×
                "{} {} older; pass -n to see more",
15060×
                ui::glyph("…", "..."),
15070×
                plural(ops.len() - i, "operation")
15080×
            ))
15090×
        );
15100×
    }
15110×
    Ok(0)
15121×
}
1513
1514
/// One change an operation made, in words.
151511×
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1516
    use oxy_core::repo::ViewChange::*;
15172×
    match c {
15180×
        BookmarkCreated { name, heads } => {
15190×
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1520
        }
15210×
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
15222×
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
15231×
        BookmarkMoved { name, from, to } => format!(
1524
            "{name}: {from} {} {}",
15251×
            ui::glyph("→", "->"),
15261×
            plural(*to, "head")
1527
        ),
15281×
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
15290×
        TagCreated { name } => format!("tagged {name}"),
15300×
        TagDeleted { name } => format!("removed tag {name}"),
15310×
        Policy => "trust policy changed".to_string(),
15328×
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
15338×
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
15340×
            Err(_) => "working copy moved".to_string(),
1535
        },
1536
    }
153711×
}
1538
15390×
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
15400×
    let repo = open()?;
15410×
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
15420×
    let r = repo.op_restore(op, discard)?;
15430×
    sp.done(&format!(
15440×
        "{} to operation {} {}",
15450×
        ui::done("Restored"),
15460×
        ui::hash(r.op.short(12)),
15470×
        ui::dim(r.command.lines().next().unwrap_or(""))
15480×
    ));
15490×
    println!(
1550
        "  {} {}",
15510×
        ui::note(),
15520×
        ui::dim(format!(
1553
            "{} written, {} removed; oxy undo goes back again",
15540×
            plural(r.checkout.written, "file"),
1555
            r.checkout.removed
1556
        ))
1557
    );
15580×
    where_now(&repo);
15590×
    Ok(0)
15600×
}
1561
15620×
pub fn op_revert(op: &str) -> Result<i32> {
15630×
    let repo = open()?;
15640×
    let r = repo.op_revert(op)?;
15650×
    let view = repo.view()?;
15660×
    let names: Vec<String> = r
15670×
        .reverted
15680×
        .iter()
15690×
        .map(|n| {
15700×
            if view.bookmarks.contains_key(n) {
15710×
                ui::bookmark(n)
1572
            } else {
15730×
                format!("{} (removed)", ui::bookmark(n))
1574
            }
15750×
        })
15760×
        .collect();
15770×
    println!(
1578
        "{} operation {} {}",
15790×
        ui::done("Reverted"),
15800×
        ui::hash(r.op.short(12)),
15810×
        ui::dim(r.command.lines().next().unwrap_or(""))
1582
    );
15830×
    println!(
1584
        "  {} {}",
15850×
        ui::note(),
15860×
        ui::dim(format!("as before it: {}", names.join(", ")))
1587
    );
15880×
    if !r.kept.is_empty() {
15890×
        println!(
15900×
            "  {} {}",
15910×
            ui::caution(),
15920×
            ui::warn(format!(
15930×
                "left as they are, having moved again since: {}",
15940×
                r.kept.join(", ")
15950×
            ))
15960×
        );
15970×
    }
15980×
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
15990×
        println!(
16000×
            "  {} {}",
16010×
            ui::note(),
16020×
            ui::dim("the working copy has work of its own: oxy checkout to move it")
16030×
        );
16040×
    }
16050×
    where_now(&repo);
16060×
    Ok(0)
16070×
}
1608
1609
/// Where the working copy and bookmark are now, after a command moved
1610
/// them (as jj says "Working copy now at").
161131×
pub fn where_now(repo: &Repo) {
161231×
    let Ok((_, wc)) = repo.working_copy() else {
16130×
        return;
1614
    };
161531×
    let heads = repo.bookmark_heads().unwrap_or_default();
161631×
    let newest = heads
161731×
        .iter()
161843×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
161931×
        .max_by_key(|(m, _)| m.hlc);
162031×
    println!(
1621
        "  {} {}",
162231×
        ui::dim(format!("{:<13}", "Working copy")),
162331×
        ui::id(wc.change_id.short(8))
1624
    );
162531×
    let tail = match newest {
162631×
        Some((m, _)) => format!(
1627
            ", newest {} {}",
162831×
            ui::id(m.change_id.short(8)),
162931×
            subject_of(&m.message)
1630
        ),
16310×
        None => String::new(),
1632
    };
163331×
    println!(
1634
        "  {} {}: {}{tail}",
163531×
        ui::dim(format!("{:<13}", "Bookmark")),
163631×
        ui::bookmark(&repo.config.bookmark),
163731×
        plural(heads.len(), "head")
1638
    );
163931×
}
1640
16410×
pub fn gc(now: bool) -> Result<i32> {
16420×
    let repo = open()?;
16430×
    let sp = ui::spinner("Packing and pruning…");
16440×
    let r = repo.gc_with(now, &mut |phase| sp.set(&format!("{phase}…")))?;
16450×
    sp.clear();
16460×
    if r.packed.objects > 0 {
16470×
        println!(
16480×
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
16490×
            plural(r.packed.objects, "object"),
16500×
            r.packed.raw_bytes,
16510×
            r.packed.packed_bytes,
16520×
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
16530×
        );
16540×
    }
16550×
    println!(
1656
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
16570×
        plural(r.reachable, "object"),
16580×
        plural(r.pruned.objects, "unreachable object"),
1659
        r.pruned.bytes,
16600×
        if r.pruned.deferred > 0 {
16610×
            format!(
1662
                "; {} deferred by the grace period (use --now)",
16630×
                plural(r.pruned.deferred, "object")
1664
            )
1665
        } else {
16660×
            String::new()
1667
        },
16680×
        if r.merged_packs > 0 {
16690×
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1670
        } else {
16710×
            String::new()
1672
        },
16730×
        plural(repo.store().pack_count(), "pack")
1674
    );
16750×
    Ok(0)
16760×
}
1677
1678
/// `oxy gc --remote NAME`: fold a store remote's bundles into one.
16792×
pub fn gc_remote(name: &str, now: bool) -> Result<i32> {
16802×
    let repo = open()?;
16812×
    let sp = ui::spinner(&format!("Folding {name}'s bundles…"));
16822×
    let r = repo.gc_remote(name, now)?;
16831×
    sp.clear();
16841×
    if r.merged > 0 {
16851×
        println!(
16861×
            "{} {} into one of {} bytes ({})",
16871×
            ui::done("Folded"),
16881×
            plural(r.merged, "bundle"),
16891×
            r.bundle_bytes,
16901×
            plural(r.changes, "change")
16911×
        );
16921×
    } else {
16930×
        println!(
16940×
            "{} {}",
16950×
            ui::note(),
16960×
            ui::dim("nothing to fold: one bundle holds everything")
16970×
        );
16980×
    }
16991×
    println!(
1700
        "  {} {}",
17011×
        ui::note(),
17021×
        ui::dim(format!(
1703
            "removed {}{}",
17041×
            plural(r.deleted, "superseded bundle"),
17051×
            if r.deferred > 0 {
17060×
                format!(
1707
                    "; {} kept for readers that may still fetch them (use --now)",
17080×
                    plural(r.deferred, "bundle")
1709
                )
1710
            } else {
17111×
                String::new()
1712
            }
1713
        ))
1714
    );
17151×
    Ok(0)
17162×
}
1717
1718
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
17190×
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1720
    use oxy_core::repo::Health;
17210×
    let repo = open()?;
17220×
    let sp = ui::spinner(if offline {
17230×
        "Checking…"
1724
    } else {
17250×
        "Checking, and contacting remotes…"
1726
    });
17270×
    let r = repo.doctor(!offline);
17280×
    sp.clear();
17290×
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
17300×
    let word = |h: Health| match h {
17310×
        Health::Ok => "ok",
17320×
        Health::Warn => "warning",
17330×
        Health::Fail => "fail",
17340×
    };
17350×
    if as_json {
17360×
        let checks: Vec<String> = r
17370×
            .checks
17380×
            .iter()
17390×
            .map(|c| {
17400×
                json::obj([
17410×
                    ("area", json::s(&c.area)),
17420×
                    ("health", json::s(word(c.health))),
17430×
                    ("message", json::s(&c.message)),
17440×
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
17450×
                ])
17460×
            })
17470×
            .collect();
17480×
        println!(
1749
            "{}",
17500×
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1751
        );
17520×
        return Ok(code);
17530×
    }
17540×
    let mut last = "";
17550×
    for c in &r.checks {
17560×
        if c.area != last {
17570×
            println!("{}", ui::section(&c.area));
17580×
            last = &c.area;
17590×
        }
17600×
        let mark = match c.health {
17610×
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
17620×
            Health::Warn => ui::caution(),
17630×
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1764
        };
17650×
        println!("  {mark} {}", c.message);
17660×
        if let Some(h) = &c.hint {
17670×
            println!("    {} {}", ui::dim("→"), ui::dim(h));
17680×
        }
1769
    }
17700×
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
17710×
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
17720×
    if fails + warns == 0 {
17730×
        println!("{}", ui::done("Everything looks right."));
17740×
    } else {
17750×
        println!(
1776
            "{} {}, {}.",
17770×
            if fails > 0 {
17780×
                ui::err(ui::glyph("✖", "x"))
1779
            } else {
17800×
                ui::caution()
1781
            },
17820×
            plural(fails, "problem"),
17830×
            plural(warns, "warning")
1784
        );
1785
    }
17860×
    Ok(code)
17870×
}
1788
1789
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
17900×
pub fn fsck(as_json: bool) -> Result<i32> {
1791
    use oxy_core::repo::Severity;
17920×
    let repo = open()?;
17930×
    let sp = ui::spinner("Checking every object…");
17940×
    let r = repo.fsck()?;
17950×
    sp.clear();
17960×
    let code = if r.errors() > 0 { 1 } else { 0 };
17970×
    if as_json {
17980×
        let problems: Vec<String> = r
17990×
            .problems
18000×
            .iter()
18010×
            .map(|p| {
18020×
                json::obj([
1803
                    (
1804
                        "severity",
18050×
                        json::s(match p.severity {
18060×
                            Severity::Error => "error",
18070×
                            Severity::Warning => "warning",
1808
                        }),
1809
                    ),
1810
                    (
18110×
                        "object",
18120×
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1813
                    ),
18140×
                    ("what", json::s(&p.what)),
1815
                ])
18160×
            })
18170×
            .collect();
18180×
        println!(
1819
            "{}",
18200×
            json::obj([
18210×
                ("ok", json::b(code == 0)),
18220×
                ("objects", json::n(r.objects)),
18230×
                ("ops", json::n(r.ops)),
18240×
                ("changes", json::n(r.changes)),
18250×
                ("signed", json::n(r.signed)),
18260×
                ("unsigned", json::n(r.unsigned)),
18270×
                ("checkpoints", json::n(r.checkpoints)),
18280×
                ("attestations", json::n(r.attestations)),
18290×
                ("errors", json::n(r.errors())),
18300×
                ("warnings", json::n(r.warnings())),
18310×
                ("problems", json::arr(problems)),
18320×
            ])
1833
        );
18340×
        return Ok(code);
18350×
    }
18360×
    println!(
1837
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
18380×
        plural(r.objects, "object"),
18390×
        plural(r.ops, "operation"),
18400×
        plural(r.changes, "change"),
1841
        r.signed,
1842
        r.unsigned,
18430×
        plural(r.checkpoints, "checkpoint"),
18440×
        plural(r.attestations, "attestation"),
1845
    );
18460×
    for p in &r.problems {
18470×
        let obj = p
18480×
            .object
18490×
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
18500×
            .unwrap_or_default();
18510×
        match p.severity {
18520×
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
18530×
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1854
        }
1855
    }
18560×
    if r.problems.is_empty() {
18570×
        println!("{}", ui::done("No problems found."));
18580×
    } else if code == 0 {
18590×
        println!(
18600×
            "{}",
18610×
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
18620×
        );
18630×
    } else {
18640×
        println!(
18650×
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
18660×
            ui::err(ui::glyph("✖", "x")),
18670×
            plural(r.errors(), "error"),
18680×
            plural(r.warnings(), "warning")
18690×
        );
18700×
    }
18710×
    Ok(code)
18720×
}
1873
1874
/// The head the working copy sits on, for commands that default to it. With
1875
/// several heads beneath the working copy, the most recently made one is
1876
/// chosen and announced.
18770×
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
18780×
    let snap = repo.snapshot_status("oxy")?;
18790×
    let base = snap.base.maximal(&snap.wc.deps);
18800×
    match base.as_slice() {
18810×
        [] => anyhow::bail!("the working copy sits on no change yet"),
18820×
        [h] => Ok(*h),
18830×
        many => {
18840×
            let latest = many
18850×
                .iter()
18860×
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
18870×
                .copied()
18880×
                .unwrap();
18890×
            let c = repo.store().get_change(&latest)?;
18900×
            println!(
1891
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
18920×
                short_id(&c),
18930×
                latest.short(12),
18940×
                many.len()
1895
            );
18960×
            Ok(latest)
1897
        }
1898
    }
18990×
}
1900
1901
/// `oxy describe` without -m: the working copy's name for a build.
19024×
pub fn describe_name(as_json: bool) -> Result<i32> {
19034×
    let repo = open()?;
19044×
    let d = repo.describe_working_copy()?;
19054×
    if as_json {
19063×
        println!(
1907
            "{}",
19083×
            json::obj([
19093×
                ("describe", json::s(&d.line())),
19103×
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
19113×
                ("distance", json::n(d.distance)),
19123×
                ("bookmark", json::s(&d.bookmark)),
19133×
                ("change", json::s(&d.change.to_hex())),
19143×
                ("hash", json::s(&d.hash.to_hex())),
19153×
                ("dirty", json::b(d.dirty)),
1916
            ])
1917
        );
19181×
    } else {
19191×
        println!("{}", d.line());
19201×
    }
19214×
    Ok(0)
19224×
}
1923
19240×
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
19250×
    let repo = open()?;
19260×
    let h = match change {
19270×
        Some(c) => repo.resolve_change(c)?,
19280×
        None => current_head(&repo)?,
1929
    };
19300×
    let new = repo.describe(&h, message)?;
19310×
    let c = repo.store().get_change_meta(&new)?;
19320×
    println!(
1933
        "{} {} {}  {}",
19340×
        ui::done("Described"),
19350×
        ui::id(c.change_id.short(8)),
19360×
        ui::hash(format!("#{}", new.short(12))),
19370×
        ui::subject(subject_of(message))
1938
    );
19390×
    Ok(0)
19400×
}
1941
19420×
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
19430×
    let repo = open()?;
19440×
    let before = repo.view()?;
19450×
    let new = match into {
19460×
        Some(spec) => {
19470×
            let target = repo.resolve_change(spec)?;
19480×
            repo.amend_into(&target, message)?
1949
        }
19500×
        None => repo.amend(message)?,
1951
    };
19520×
    let c = repo.store().get_change_meta(&new)?;
19530×
    println!(
1954
        "{} {} {}  {}",
19550×
        ui::done("Amended"),
19560×
        ui::id(c.change_id.short(8)),
19570×
        ui::hash(format!("#{}", new.short(12))),
19580×
        ui::subject(subject_of(&c.message))
1959
    );
1960
    // Rewriting what a remote already has means the next push replaces it
1961
    // there (oxygen#99): say so now, not when the push is refused.
19620×
    let bookmark = repo.config.bookmark.clone();
19630×
    let (had, has) = (
19640×
        repo.heads_of(&before, &bookmark)?,
19650×
        repo.heads_of(&repo.view()?, &bookmark)?,
1966
    );
19670×
    for (remote, bookmarks) in &before.remotes {
19680×
        let Some(st) = bookmarks.get(&bookmark) else {
19690×
            continue;
1970
        };
19710×
        let theirs = repo.store().get_state(st)?.heads;
19720×
        if theirs.iter().any(|h| had.contains(h) && !has.contains(h)) {
19730×
            println!(
19740×
                "  {} {}",
19750×
                ui::caution(),
19760×
                ui::warn(format!(
19770×
                    "{remote}/{bookmark} has the change as it was: the next push of {bookmark} needs --force to replace it"
19780×
                ))
19790×
            );
19800×
        }
1981
    }
19820×
    where_now(&repo);
19830×
    Ok(0)
19840×
}
1985
19860×
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
19870×
    let repo = open()?;
19880×
    let Some(r) = revset else {
19890×
        let h = repo.resolve_change(change.unwrap_or_default())?;
19900×
        abandon_one(&repo, h)?;
19910×
        where_now(&repo);
19920×
        return Ok(0);
1993
    };
1994
    // A revset: say what it selects, refuse an empty set, ask above a few.
19950×
    let selected = repo.revset(r)?;
19960×
    let wc = repo.working_copy().ok().map(|(h, _)| h);
19970×
    let hashes: Vec<ChangeHash> = selected
19980×
        .hashes
19990×
        .iter()
20000×
        .copied()
20010×
        .filter(|h| Some(*h) != wc)
20020×
        .collect();
20030×
    if hashes.is_empty() {
20040×
        anyhow::bail!("{r:?} selects no change to abandon");
20050×
    }
20060×
    println!(
2007
        "{} {} selects {}:",
20080×
        ui::section("abandon"),
20090×
        ui::id(r),
20100×
        plural(hashes.len(), "change")
2011
    );
20120×
    for h in &hashes {
20130×
        if let Some(m) = selected.metas.get(h) {
20140×
            println!(
20150×
                "  {} {}  {}",
20160×
                ui::id(m.change_id.short(8)),
20170×
                ui::hash(format!("#{}", h.short(12))),
20180×
                subject_of(&m.message)
20190×
            );
20200×
        }
2021
    }
2022
    const ASK_ABOVE: usize = 5;
20230×
    if hashes.len() > ASK_ABOVE && !yes {
20240×
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
20250×
    }
2026
    // Newest first: abandoning a change rewrites what depends on it, so a
2027
    // later member is found again by its ChangeId.
20280×
    let mut done = 0;
20290×
    for h in &hashes {
20300×
        let Some(m) = selected.metas.get(h) else {
20310×
            continue;
2032
        };
20330×
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
20340×
            Ok(h) => h,
20350×
            Err(_) => continue,
2036
        };
20370×
        abandon_one(&repo, now)?;
20380×
        done += 1;
2039
    }
20400×
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
20410×
    where_now(&repo);
20420×
    Ok(0)
20430×
}
2044
20450×
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
20460×
    let c = repo.store().get_change_meta(&h)?;
20470×
    let notes = repo.abandon(&h)?;
20480×
    println!(
2049
        "{} {} {}  {}",
20500×
        ui::done("Abandoned"),
20510×
        ui::id(c.change_id.short(8)),
20520×
        ui::hash(format!("#{}", h.short(12))),
20530×
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
2054
    );
20550×
    for n in notes {
20560×
        println!("  {} {n}", ui::note());
20570×
    }
20580×
    Ok(())
20590×
}
2060
20610×
pub fn checkpoint() -> Result<i32> {
20620×
    let repo = open()?;
20630×
    let sp = ui::spinner("Writing checkpoint…");
20640×
    let (r, changes, bytes) = repo.checkpoint()?;
20650×
    sp.done(&format!(
20660×
        "{} {} of {} ({} bytes) for {}",
20670×
        ui::done("Checkpoint"),
20680×
        ui::hash(format!("#{}", r.short(12))),
20690×
        plural(changes, "change"),
20700×
        bytes,
20710×
        ui::id(&repo.config.bookmark)
20720×
    ));
20730×
    Ok(0)
20740×
}
2075
2076
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
20770×
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
20780×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
20790×
        return Ok(1);
2080
    };
20810×
    let info = repo.quick_status()?;
20820×
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
20830×
        oxy_core::repo::GLYPH_PROMPT_FORMAT
2084
    } else {
20850×
        format
2086
    };
20870×
    let line = match color {
20880×
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
20890×
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
20900×
        Some(_) => info.format_colored(fmt, ("", "")),
20910×
        None => info.format(fmt),
2092
    };
20930×
    println!("{line}");
20940×
    Ok(0)
20950×
}
2096
20970×
pub fn sparse(paths: &[String]) -> Result<i32> {
20980×
    let mut repo = open()?;
20990×
    if paths.is_empty() {
21000×
        if repo.config.sparse_paths.is_empty() {
21010×
            println!("No sparse filter: the whole tree is materialized.");
21020×
        } else {
21030×
            println!("{}", ui::heading("Sparse filter"));
21040×
            for p in &repo.config.sparse_paths {
21050×
                println!("  {}", ui::path(p));
21060×
            }
2107
        }
21080×
        return Ok(0);
21090×
    }
21100×
    let snap = repo.snapshot("oxy sparse")?;
21110×
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
21120×
        anyhow::bail!(
2113
            "the working copy has changes; commit them before changing the sparse filter"
2114
        );
21150×
    }
21160×
    repo.config.set("filter.paths", &paths.join(","))?;
21170×
    repo.save_config()?;
21180×
    let heads = repo.bookmark_heads()?;
21190×
    let sp = ui::spinner("Re-checking out with the new filter…");
21200×
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
21210×
    sp.done(&format!(
21220×
        "{} {}: {} written, {} removed",
21230×
        ui::done("Sparse filter set to"),
21240×
        ui::path(paths.join(",")),
21250×
        plural(r.written, "file"),
21260×
        r.removed
21270×
    ));
21280×
    Ok(0)
21290×
}
2130
21312×
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
21322×
    let repo = open()?;
21332×
    repo.snapshot_status("oxy tag")?;
21342×
    let heads = if changes.is_empty() {
21352×
        repo.bookmark_heads()?
2136
    } else {
21370×
        let mut heads = Vec::new();
21380×
        for c in changes {
21390×
            heads.extend(repo.resolve_heads(c)?);
2140
        }
21410×
        heads
2142
    };
21432×
    let t = repo.tag_create(name, &heads, message)?;
21442×
    println!(
2145
        "{} {} {} {} ({}){}",
21462×
        ui::done("Tagged"),
21472×
        ui::bookmark(&t.name),
21482×
        ui::dim(ui::glyph("→", "->")),
21492×
        ui::hash(format!("#{}", t.state.short(12))),
21502×
        plural(t.heads.len(), "head"),
21512×
        t.signer
21522×
            .map(|s| format!(", signed by {s}"))
21532×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2154
    );
21552×
    Ok(0)
21562×
}
2157
21581×
pub fn tag_list(as_json: bool) -> Result<i32> {
21591×
    let repo = open()?;
21601×
    let tags = repo.tags()?;
21611×
    if as_json {
21621×
        println!(
2163
            "{}",
21641×
            json::arr(tags.iter().map(|t| {
21651×
                json::obj([
21661×
                    ("name", json::s(&t.name)),
21671×
                    ("state", json::s(&t.state.to_hex())),
21681×
                    ("heads", json::hashes(&t.heads)),
21691×
                    ("message", json::s(&t.message)),
2170
                    (
21711×
                        "signer",
21721×
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2173
                    ),
2174
                ])
21751×
            }))
2176
        );
21771×
        return Ok(0);
21780×
    }
21790×
    if tags.is_empty() {
21800×
        println!("{}", ui::dim("No tags."));
21810×
    }
21820×
    for t in tags {
21830×
        println!(
2184
            "{} {} {}{}{}{}",
21850×
            ui::ok(ui::glyph("⚑", "#")),
21860×
            ui::bookmark(&t.name),
2187
            // The heads, as `oxy log` shows changes, not the state hash.
21880×
            ui::hash(
21890×
                t.heads
21900×
                    .iter()
21910×
                    .map(|h| format!("#{}", h.short(12)))
21920×
                    .collect::<Vec<_>>()
21930×
                    .join(" ")
2194
            ),
21950×
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
21960×
            if t.message.is_empty() {
21970×
                String::new()
2198
            } else {
21990×
                format!("  {}", ui::subject(subject_of(&t.message)))
2200
            },
22010×
            t.signer
22020×
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
22030×
                .unwrap_or_default()
2204
        );
2205
    }
22060×
    Ok(0)
22071×
}
2208
2209
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2210
/// and workspace add take as "be on this bookmark" (oxygen#60).
22110×
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
22120×
    Ok(repo.view()?.bookmarks.contains_key(name)
22130×
        || repo
22140×
            .remote_only_bookmarks()?
22150×
            .iter()
22160×
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
22170×
}
2218
22190×
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
22200×
    let repo = open()?;
2221
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2222
    // this workspace's bookmark with that one's files.
22230×
    if let [name] = changes {
22240×
        if names_bookmark(&repo, name)? {
22250×
            let (local, _) = repo.local_bookmark_for(name)?;
22260×
            let heads = repo.resolve_heads(&local)?;
22270×
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
22280×
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
22290×
            sp.done(&format!(
22300×
                "{} {} (workspace {}) on {}",
22310×
                ui::done("Workspace created at"),
22320×
                ui::path(ws.root().display()),
22330×
                ui::id(ws.workspace().short(8)),
22340×
                ui::bookmark(&local)
22350×
            ));
22360×
            return Ok(0);
22370×
        }
22380×
    }
22390×
    let heads = if changes.is_empty() {
22400×
        None
2241
    } else {
22420×
        let mut heads = Vec::new();
22430×
        for c in changes {
22440×
            heads.extend(repo.resolve_heads(c)?);
2245
        }
22460×
        Some(heads)
2247
    };
22480×
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
22490×
    let ws = repo.workspace_add(path, heads.as_deref())?;
22500×
    sp.done(&format!(
22510×
        "{} {} (workspace {})",
22520×
        ui::done("Workspace created at"),
22530×
        ui::path(ws.root().display()),
22540×
        ui::id(ws.workspace().short(8))
22550×
    ));
22560×
    Ok(0)
22570×
}
2258
22591×
pub fn workspace_list(as_json: bool) -> Result<i32> {
22601×
    let repo = open()?;
22611×
    if as_json {
22621×
        println!(
2263
            "{}",
22641×
            json::arr(repo.workspaces()?.iter().map(|w| {
22651×
                json::obj([
22661×
                    ("id", json::s(&w.id.to_hex())),
22671×
                    ("path", json::s(&w.path.to_string_lossy())),
22681×
                    ("current", json::b(w.current)),
2269
                    (
22701×
                        "working_copy",
22711×
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2272
                    ),
2273
                ])
22741×
            }))
2275
        );
22761×
        return Ok(0);
22770×
    }
22780×
    for w in repo.workspaces()? {
22790×
        println!(
2280
            "{} {} {}{}",
22810×
            if w.current {
22820×
                ui::ok(ui::glyph("●", "*"))
2283
            } else {
22840×
                ui::dim(ui::glyph("○", "o"))
2285
            },
22860×
            ui::id(w.id.short(8)),
22870×
            ui::path(w.path.display()),
22880×
            w.working_copy
22890×
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
22900×
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2291
        );
2292
    }
22930×
    Ok(0)
22941×
}
2295
22960×
pub fn workspace_forget(spec: &str) -> Result<i32> {
22970×
    let repo = open()?;
22980×
    let all = repo.workspaces()?;
22990×
    let target = std::fs::canonicalize(spec).ok();
23000×
    let matches: Vec<_> = all
23010×
        .iter()
23020×
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
23030×
        .collect();
23040×
    let w = match matches.as_slice() {
23050×
        [w] => *w,
23060×
        [] => anyhow::bail!("no workspace matches {spec:?}"),
23070×
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2308
    };
23090×
    repo.workspace_forget(&w.id)?;
23100×
    println!(
2311
        "{} workspace {} at {}; its files were left in place.",
23120×
        ui::done("Forgot"),
23130×
        ui::id(w.id.short(8)),
23140×
        ui::path(w.path.display())
2315
    );
23160×
    Ok(0)
23170×
}
2318
23190×
pub fn lock(path: &str) -> Result<i32> {
23200×
    let repo = open()?;
23210×
    repo.lock_path(path)?;
23220×
    println!(
2323
        "{} {} {}",
23240×
        ui::done("Locked"),
23250×
        ui::path(path),
23260×
        ui::dim("(advisory, local)")
2327
    );
23280×
    Ok(0)
23290×
}
2330
23310×
pub fn unlock(path: &str) -> Result<i32> {
23320×
    let repo = open()?;
23330×
    repo.unlock_path(path)?;
23340×
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
23350×
    Ok(0)
23360×
}
2337
23380×
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
23390×
    let repo = open()?;
23400×
    let h = repo.resolve_change(change)?;
23410×
    let (h1, h2) = repo.split(&h, paths)?;
23420×
    let c1 = repo.store().get_change_meta(&h1)?;
23430×
    let c2 = repo.store().get_change_meta(&h2)?;
23440×
    println!(
2345
        "{} into {} {} and {} {}",
23460×
        ui::done("Split"),
23470×
        ui::id(c1.change_id.short(8)),
23480×
        ui::hash(format!("#{}", h1.short(12))),
23490×
        ui::id(c2.change_id.short(8)),
23500×
        ui::hash(format!("#{}", h2.short(12)))
2351
    );
23520×
    Ok(0)
23530×
}
2354
23556×
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
23566×
    let mut heads = Vec::new();
23576×
    for c in changes {
23586×
        heads.extend(repo.resolve_heads(c)?);
2359
    }
23606×
    Ok(heads)
23616×
}
2362
23636×
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
23646×
    let repo = open()?;
23656×
    repo.snapshot_status("oxy bookmark create")?;
23666×
    let heads = if changes.is_empty() {
23673×
        None
2368
    } else {
23693×
        let named = heads_from(&repo, changes)?;
23703×
        let (_, wc) = repo.working_copy()?;
23713×
        let gap = repo.state_gap(&wc.deps, &named)?;
23723×
        if upto {
23731×
            Some(gap.upto)
23742×
        } else if only || gap.earlier.is_empty() {
23751×
            Some(named)
2376
        } else {
23771×
            anyhow::bail!(
2378
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2379
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2380
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2381
                 or --only for just {0} and what it depends on.",
23821×
                changes.join(" "),
23831×
                plural(gap.earlier.len(), "change"),
23841×
                listed_changes(&repo, &gap.earlier)
2385
            );
2386
        }
2387
    };
23885×
    let heads = repo.bookmark_create(name, heads.as_deref())?;
23895×
    println!(
2390
        "{} bookmark {} {} {}",
23915×
        ui::done("Created"),
23925×
        ui::bookmark(name),
23935×
        ui::dim(ui::glyph("→", "->")),
23945×
        ui::dim(plural(heads.len(), "head"))
2395
    );
23965×
    println!(
2397
        "  {} {}",
23985×
        ui::note(),
23995×
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2400
    );
24015×
    Ok(0)
24026×
}
2403
2404
/// Up to five changes, newest last, as `  #hash subject` lines.
24052×
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
24062×
    let shown = changes.len().min(5);
24072×
    let mut lines: Vec<String> = changes[changes.len() - shown..]
24082×
        .iter()
24092×
        .map(|h| {
24102×
            let subject = repo
24112×
                .store()
24122×
                .get_change(h)
24132×
                .map(|c| subject_of(&c.message).to_string())
24142×
                .unwrap_or_default();
24152×
            format!("  #{} {subject}", h.short(12))
24162×
        })
24172×
        .collect();
24182×
    if changes.len() > shown {
24190×
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
24202×
    }
24212×
    lines.join("\n")
24222×
}
2423
24243×
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
24253×
    let repo = open()?;
24263×
    repo.snapshot_status("oxy bookmark set")?;
24273×
    let named = heads_from(&repo, changes)?;
2428
    // What the bookmark holds now and the new heads would leave out.
24293×
    let current = repo
24303×
        .bookmarks()?
24313×
        .into_iter()
24326×
        .find(|b| b.name == name)
24333×
        .map(|b| b.heads)
24343×
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
24353×
    let gap = repo.state_gap(&current, &named)?;
2436
    // A fast-forward: the new heads hold the bookmark's newest head, so
2437
    // what they leave out is older work nothing since has built on, such
2438
    // as an early change no later one depends on (oxygen#78). Keep it, as
2439
    // --upto does, and say so.
24403×
    let newest = current
24413×
        .iter()
24428×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m.hlc, *h)))
24433×
        .max()
24443×
        .map(|(_, h)| h);
2445
    // Ahead, too: a head the bookmark holds already (it would only drop
2446
    // the others) is not a move forward.
24473×
    let ahead = repo
24483×
        .load_state_history(&current)
24493×
        .is_ok_and(|st| named.iter().any(|h| !st.contains(h)));
24503×
    let forward = !only
24513×
        && ahead
24521×
        && !gap.earlier.is_empty()
24531×
        && newest.is_some_and(|n| {
24541×
            repo.load_state_history(&named)
24551×
                .is_ok_and(|st| st.contains(&n))
24561×
        });
24573×
    let heads = if upto {
24581×
        gap.upto
24592×
    } else if forward {
24601×
        println!(
2461
            "  {} {}",
24621×
            ui::note(),
24631×
            ui::dim(format!(
2464
                "{} builds on {name}'s newest head; keeping {} it holds that {0} does not depend on",
24651×
                changes.join(" "),
24661×
                plural(gap.earlier.len(), "change")
2467
            ))
2468
        );
24691×
        gap.upto
24701×
    } else if only || gap.earlier.is_empty() {
24710×
        named
2472
    } else {
24731×
        anyhow::bail!(
2474
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2475
             A state is its heads and what they depend on, not everything recorded before them.\n\
2476
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2477
             or --only for just {0} and what it depends on.",
24781×
            changes.join(" "),
24791×
            plural(gap.earlier.len(), "change"),
24801×
            listed_changes(&repo, &gap.earlier)
2481
        );
2482
    };
24832×
    let heads = repo.bookmark_set(name, &heads)?;
24842×
    println!(
2485
        "{} bookmark {} {} {}",
24862×
        ui::done("Moved"),
24872×
        ui::bookmark(name),
24882×
        ui::dim(ui::glyph("→", "->")),
24892×
        ui::dim(plural(heads.len(), "head"))
2490
    );
24912×
    Ok(0)
24923×
}
2493
24940×
pub fn bookmark_delete(name: &str) -> Result<i32> {
24950×
    let repo = open()?;
24960×
    repo.bookmark_delete(name)?;
24970×
    println!(
2498
        "{} bookmark {} {}",
24990×
        ui::done("Deleted"),
25000×
        ui::bookmark(name),
25010×
        ui::dim("(its changes stay until unreachable)")
2502
    );
25030×
    Ok(0)
25040×
}
2505
2506
/// Heads with their metadata, newest first.
25070×
fn heads_newest_first(
25080×
    repo: &Repo,
25090×
    heads: &[oxy_core::hash::ChangeHash],
25100×
) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> {
25110×
    let mut out: Vec<_> = heads
25120×
        .iter()
25130×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m)))
25140×
        .collect();
25150×
    out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc));
25160×
    out
25170×
}
2518
2519
/// One head as a line: id, hash, author, when, subject.
25200×
fn print_head(
25210×
    repo: &Repo,
25220×
    indent: &str,
25230×
    h: &oxy_core::hash::ChangeHash,
25240×
    m: &oxy_core::state::ChangeMeta,
25250×
) {
25260×
    println!(
2527
        "{indent}{} {} {}{}{}{}{}",
25280×
        ui::id(m.change_id.short(8)),
25290×
        ui::dim(format!("#{}", &h.to_hex()[..8])),
25300×
        author_name(repo, m),
25310×
        ui::sep(),
25320×
        ui::dim(ui::ago(m.hlc.wall_ms)),
25330×
        ui::sep(),
25340×
        ui::subject(subject_of(&m.message))
2535
    );
25360×
}
2537
25380×
pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result<i32> {
25390×
    let repo = open()?;
25400×
    let name = name.unwrap_or(&repo.config.bookmark).to_string();
25410×
    let view = repo.view()?;
25420×
    let st = match view.bookmarks.get(&name) {
25430×
        Some(st) => *st,
25440×
        None => match oxy_core::repo::remote_bookmark(&view, &name) {
25450×
            Some((_, _, st)) => st,
25460×
            None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"),
2547
        },
2548
    };
25490×
    let heads = repo.store().get_state(&st)?.heads;
25500×
    let shown = heads_newest_first(&repo, &heads);
25510×
    if as_json {
25520×
        println!(
2553
            "{}",
25540×
            json::obj([
25550×
                ("name", json::s(&name)),
25560×
                ("current", json::b(name == repo.config.bookmark)),
2557
                (
25580×
                    "heads",
25590×
                    json::arr(shown.iter().map(|(h, m)| {
25600×
                        json::obj([
25610×
                            ("hash", json::s(&h.to_hex())),
25620×
                            ("id", json::s(&m.change_id.to_string())),
25630×
                            ("author", json::s(&author_name(&repo, m))),
25640×
                            ("time_ms", json::n(m.hlc.wall_ms)),
25650×
                            ("subject", json::s(subject_of(&m.message))),
25660×
                        ])
25670×
                    }))
2568
                ),
2569
            ])
2570
        );
25710×
        return Ok(0);
25720×
    }
25730×
    println!(
2574
        "{} {}{}{}",
25750×
        ui::ok(ui::glyph("●", "*")),
25760×
        ui::bookmark(&name),
25770×
        ui::sep(),
25780×
        ui::dim(plural(heads.len(), "head"))
2579
    );
25800×
    for (h, m) in &shown {
25810×
        print_head(&repo, "  ", h, m);
25820×
    }
25830×
    if heads.len() > 1 {
25840×
        println!(
25850×
            "  {}",
25860×
            ui::dim("None depends on another: the bookmark is all of them and their dependencies.")
25870×
        );
25880×
    }
25890×
    Ok(0)
25900×
}
2591
25925×
pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result<i32> {
25935×
    let repo = open()?;
25945×
    let remote_only = repo.remote_only_bookmarks()?;
25955×
    if as_json {
25965×
        let mut items: Vec<String> = repo
25975×
            .bookmarks()?
25985×
            .into_iter()
259913×
            .map(|b| {
260013×
                json::obj([
260113×
                    ("name", json::s(&b.name)),
260213×
                    ("heads", json::hashes(&b.heads)),
260313×
                    ("current", json::b(b.current)),
260413×
                    ("ahead", json::opt(b.ahead, json::n)),
260513×
                    ("behind", json::opt(b.behind, json::n)),
260613×
                    ("remote", json::opt(b.remote.as_deref(), json::s)),
260713×
                ])
260813×
            })
26095×
            .collect();
26105×
        if all {
26110×
            items.extend(remote_only.iter().map(|b| {
26120×
                json::obj([
26130×
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
26140×
                    ("heads", json::hashes(&b.heads)),
26150×
                    ("current", json::b(false)),
26160×
                    ("ahead", "null".into()),
26170×
                    ("behind", "null".into()),
26180×
                    ("remote", json::s(&b.remote)),
26190×
                ])
26200×
            }));
26215×
        }
26225×
        println!("{}", json::arr(items));
26235×
        return Ok(0);
26240×
    }
26250×
    for b in repo.bookmarks()? {
26260×
        let mark = if b.current {
26270×
            ui::ok(ui::glyph("●", "*"))
2628
        } else {
26290×
            ui::dim(ui::glyph("○", "o"))
2630
        };
26310×
        let mut tail = String::new();
26320×
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
26330×
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
26340×
        }
26350×
        if let Some(n) = b.behind.filter(|n| *n > 0) {
26360×
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
26370×
        }
2638
        // Which remote, when there is a choice (oxygen#83).
26390×
        if !tail.is_empty() && repo.config.remotes.len() > 1 {
26400×
            if let Some(r) = &b.remote {
26410×
                tail += &ui::dim(format!(" {r}"));
26420×
            }
26430×
        }
26440×
        let shown = heads_newest_first(&repo, &b.heads);
2645
        // The newest head's subject, so a busy bookmark shows its latest work.
26460×
        let head = match shown.first() {
26470×
            Some(_) if verbose => String::new(),
26480×
            Some((_, m)) if b.heads.len() > 1 => format!(
2649
                "{} {}",
26500×
                ui::dim("newest"),
26510×
                ui::subject(subject_of(&m.message))
2652
            ),
26530×
            Some((_, m)) => ui::subject(subject_of(&m.message)),
26540×
            None => ui::dim("(empty)"),
2655
        };
26560×
        let head = if head.is_empty() {
26570×
            head
2658
        } else {
26590×
            format!("  {head}")
2660
        };
26610×
        println!(
2662
            "{mark} {}{}{}{tail}{head}",
26630×
            ui::bookmark(&b.name),
26640×
            ui::sep(),
26650×
            ui::dim(plural(b.heads.len(), "head"))
2666
        );
26670×
        if verbose {
26680×
            for (h, m) in &shown {
26690×
                print_head(&repo, "    ", h, m);
26700×
            }
26710×
        }
2672
    }
26730×
    if remote_only.is_empty() {
26740×
        return Ok(0);
26750×
    }
26760×
    if !all {
26770×
        println!(
2678
            "{}",
26790×
            ui::dim(format!(
2680
                "  and {} only on a remote: oxy bookmark list --all",
26810×
                plural(remote_only.len(), "bookmark")
2682
            ))
2683
        );
26840×
        return Ok(0);
26850×
    }
26860×
    for b in &remote_only {
26870×
        println!(
26880×
            "{} {}{}{}",
26890×
            ui::dim(ui::glyph("◌", ".")),
26900×
            ui::dim(format!("{}/{}", b.remote, b.name)),
26910×
            ui::sep(),
26920×
            ui::dim(plural(b.heads.len(), "head"))
26930×
        );
26940×
    }
26950×
    println!(
2696
        "  {} {}",
26970×
        ui::note(),
26980×
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2699
    );
27000×
    Ok(0)
27015×
}
2702
27033×
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
27043×
    let mut repo = open()?;
27053×
    let from = repo.config.bookmark.clone();
27063×
    let (local, created_from) = repo.local_bookmark_for(name)?;
27073×
    if let Some(remote) = created_from {
27080×
        println!(
27090×
            "{} {} from {}",
27100×
            ui::done("Created"),
27110×
            ui::bookmark(&local),
27120×
            ui::dim(format!("{remote}/{local}"))
27130×
        );
27143×
    }
27153×
    let name = local.as_str();
2716
    // Only behind its remote: take the remote's state, so the switch does
2717
    // not check out a stale one (oxygen#74).
27183×
    if let Some(n) = repo.catch_up_bookmark(name)? {
27190×
        println!(
27200×
            "{} {} with {}: {} it lacked",
27210×
            ui::done("Caught up"),
27220×
            ui::bookmark(name),
27230×
            ui::dim(format!("{}/{name}", repo.default_remote())),
27240×
            plural(n, "change")
27250×
        );
27263×
    }
27273×
    let sp = ui::spinner(&format!("Switching to {name}…"));
27283×
    let (r, carried) = if carry {
27290×
        repo.bookmark_switch_carry(name)?
2730
    } else {
27313×
        (repo.bookmark_switch(name, discard)?, vec![])
2732
    };
27333×
    sp.done(&format!(
2734
        "{} to {}: {} written, {} removed{}",
27353×
        ui::done("Switched"),
27363×
        ui::bookmark(name),
27373×
        plural(r.written, "file"),
2738
        r.removed,
27393×
        if carried.is_empty() {
27403×
            String::new()
2741
        } else {
27420×
            format!("; carried {}", plural(carried.len(), "changed path"))
2743
        }
2744
    ));
27453×
    if r.conflicted {
27460×
        println!(
27470×
            "  {} {}",
27480×
            ui::caution(),
27490×
            ui::warn("this state has conflicts; see oxy status")
27500×
        );
27513×
    }
2752
    // Say when the new state leaves out work the old one had: a state is
2753
    // its heads and what they depend on, which can be far less than a Git
2754
    // user expects.
27553×
    if r.lacks > 0 {
27561×
        println!(
27571×
            "  {} {}",
27581×
            ui::note(),
27591×
            ui::dim(format!(
27601×
                "{name} lacks {} that {from} has",
27611×
                plural(r.lacks, "change")
27621×
            ))
27631×
        );
27642×
    }
27653×
    super::sync::subrepos_behind(&repo);
27663×
    where_now(&repo);
27673×
    Ok(0)
27683×
}
2769
27700×
pub fn merge(bookmark: &str) -> Result<i32> {
27710×
    let repo = open()?;
27720×
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
27730×
    let r = repo.merge(bookmark)?;
27740×
    if !r.changed {
27750×
        sp.done(&format!(
27760×
            "{} {}",
27770×
            ui::ok(ui::glyph("✔", "*")),
27780×
            ui::dim(format!(
27790×
                "{} already contains {bookmark}",
27800×
                repo.config.bookmark
27810×
            ))
27820×
        ));
27830×
        return Ok(0);
27840×
    }
27850×
    sp.done(&format!(
2786
        "{} {} into {}: now {}{}",
27870×
        ui::done("Merged"),
27880×
        ui::bookmark(bookmark),
27890×
        ui::bookmark(&repo.config.bookmark),
27900×
        plural(r.heads.len(), "head"),
27910×
        ui::dim(if r.checked_out {
27920×
            "; working copy updated"
2793
        } else {
27940×
            "; run oxy checkout to update the working copy"
2795
        })
2796
    ));
27970×
    let snap = repo.snapshot("oxy merge")?;
27980×
    if snap.base_snapshot.is_conflicted() {
27990×
        println!(
28000×
            "  {} {}",
28010×
            ui::caution(),
28020×
            ui::warn("the result has conflicts; see oxy status")
28030×
        );
28040×
    }
28050×
    where_now(&repo);
28060×
    Ok(0)
28070×
}
2808
28090×
pub fn squash(change: &str, into: &str) -> Result<i32> {
28100×
    let repo = open()?;
28110×
    let c = repo.resolve_change(change)?;
28120×
    let d = repo.resolve_change(into)?;
28130×
    let sp = ui::spinner("Squashing…");
28140×
    let h = repo.squash(&c, &d)?;
28150×
    let new = repo.store().get_change_meta(&h)?;
28160×
    sp.done(&format!(
28170×
        "{} into {} {}  {}",
28180×
        ui::done("Squashed"),
28190×
        ui::id(new.change_id.short(8)),
28200×
        ui::hash(format!("#{}", h.short(12))),
28210×
        ui::subject(subject_of(&new.message))
28220×
    ));
28230×
    Ok(0)
28240×
}
2825
28260×
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
28270×
    let repo = open()?;
28280×
    let c = repo.resolve_change(change)?;
28290×
    let mut heads = Vec::new();
28300×
    for o in onto {
28310×
        heads.extend(repo.resolve_heads(o)?);
2832
    }
28330×
    let sp = ui::spinner("Rebasing…");
28340×
    let h = match repo.rebase(&c, &heads) {
28350×
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
28360×
            let r = repo.rebase_into_working_copy(&c, &heads)?;
28370×
            sp.done(&format!(
28380×
                "{} {} into {}: now {}",
28390×
                ui::done("Merged"),
28400×
                onto.join(" "),
28410×
                ui::bookmark(&repo.config.bookmark),
28420×
                plural(r.heads.len(), "head"),
28430×
            ));
28440×
            if r.checked_out {
28450×
                println!(
28460×
                    "  {} {}",
28470×
                    ui::caution(),
28480×
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
28490×
                );
28500×
            } else {
28510×
                println!(
28520×
                    "  {} {}",
28530×
                    ui::caution(),
28540×
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
28550×
                );
28560×
            }
28570×
            where_now(&repo);
28580×
            return Ok(0);
2859
        }
28600×
        other => other?,
2861
    };
28620×
    let new = repo.store().get_change_meta(&h)?;
28630×
    sp.done(&format!(
28640×
        "{} {} {}  {}",
28650×
        ui::done("Rebased"),
28660×
        ui::id(new.change_id.short(8)),
28670×
        ui::hash(format!("#{}", h.short(12))),
28680×
        ui::dim(format!(
28690×
            "now depends on {}",
28700×
            plural(new.deps.len(), "change")
28710×
        ))
28720×
    ));
28730×
    where_now(&repo);
28740×
    Ok(0)
28750×
}
2876
2877
#[cfg(test)]
2878
mod tests {
2879
    use super::*;
2880
2881
    #[test]
28821×
    fn id_prefixes_agree_with_the_whole_list() {
2883
        // Ids that share long prefixes, and some that differ only in a
2884
        // half byte, from a fixed sequence.
28851×
        let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
28867999×
        let mut next = || {
28877999×
            x ^= x << 13;
28887999×
            x ^= x >> 7;
28897999×
            x ^= x << 17;
28907999×
            x
28917999×
        };
28921×
        let mut ids: Vec<[u8; 16]> = Vec::new();
28931×
        for _ in 0..2000 {
28942000×
            let mut id = [0u8; 16];
28952000×
            id[..8].copy_from_slice(&next().to_le_bytes());
28962000×
            id[8..].copy_from_slice(&next().to_le_bytes());
28972000×
            let share = (next() % 4) as usize;
28982000×
            if let Some(prev) = ids.last() {
28991999×
                id[..share].copy_from_slice(&prev[..share]);
29001999×
                if next() % 2 == 0 {
2901973×
                    id[share] = (prev[share] & 0xf0) | (id[share] & 0x0f);
29021026×
                }
29031×
            }
29042000×
            ids.push(id);
2905
        }
29064000×
        let hex = |id: &[u8; 16]| oxy_core::ids::ChangeId(*id).to_hex();
29071×
        let whole = unique_prefixes(ids.iter().map(hex));
29081×
        let some = id_prefixes(ids.clone(), ids.iter().copied());
29092000×
        for id in &ids {
29102000×
            assert_eq!(some[id], whole[&hex(id)], "{}", hex(id));
2911
        }
29121×
    }
2913
}