OXYGENHUB

Coverage / src/cli/workspace.rs 38.7%

810 of 2094 lines run, 69 of 293 functions · run #250 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
1711×
pub fn init(path: Option<PathBuf>, bare: bool, store: Option<&str>) -> Result<i32> {
1811×
    let path = path.unwrap_or(std::env::current_dir()?);
1911×
    let repo = Repo::init_new(&path, bare, store)?;
2011×
    println!(
21
        "{} {}oxy repository in {}",
2211×
        ui::done("Initialized"),
2311×
        if bare { "bare " } else { "" },
2411×
        ui::path(repo.root().display())
25
    );
2611×
    println!(
27
        "{}",
2811×
        ui::kv("bookmark", ui::bookmark(&repo.config.bookmark))
29
    );
3011×
    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×
        );
4211×
    }
4311×
    println!(
44
        "{}",
4511×
        ui::kv(
4611×
            "author",
4711×
            format!(
48
                "{} <{}>",
4911×
                ui::author(&repo.config.author_name),
50
                repo.config.author_email
51
            )
52
        )
53
    );
5411×
    Ok(0)
5511×
}
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.
7126×
fn print_untracked_nested(repo: &Repo, nested: &[String]) {
7226×
    if nested.is_empty() {
7324×
        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
    );
10226×
}
103
104
/// The working copy's changed paths, or that it is clean.
1054×
fn print_statuses(statuses: &[oxy_core::repo::PathStatus]) {
1064×
    if statuses.is_empty() {
1072×
        println!(
108
            "  {} {}",
1092×
            ui::ok(ui::glyph("✔", "*")),
1102×
            ui::dim("nothing to commit, working copy clean")
111
        );
1122×
        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×
    }
1224×
}
123
1247×
pub fn status(json: bool) -> Result<i32> {
1257×
    let repo = open()?;
126
    // Answered by the manifest alone, with no history to load (oxygen#35,
127
    // #41): a clean working copy, or one as the last snapshot left it.
1287×
    let known = if json {
1293×
        None
130
    } else {
1314×
        repo.status_by_manifest()?
132
    };
1337×
    if let Some(statuses) = known {
1342×
        let (_, wc) = repo.working_copy()?;
1352×
        let heads = repo.bookmark_heads()?;
1362×
        println!(
137
            "{} {}{}working copy {}{}{}",
1382×
            ui::dim("On"),
1392×
            ui::bookmark(&repo.config.bookmark),
1402×
            ui::sep(),
1412×
            ui::id(wc.change_id.short(8)),
1422×
            ui::sep(),
1432×
            ui::dim(plural(heads.len(), "head"))
144
        );
1452×
        print_statuses(&statuses);
1462×
        print_untracked_nested(&repo, &repo.untracked_nested());
1472×
        return Ok(0);
1485×
    }
1495×
    let sp = ui::spinner("Snapshotting the working copy…");
1505×
    let snap = repo.snapshot_status("oxy status")?;
1515×
    let heads = {
1525×
        let _t = oxy_core::timing::phase("status: heads");
1535×
        repo.bookmark_heads()?
154
    };
1555×
    let _drop = oxy_core::timing::phase("status: print and drop");
1565×
    sp.clear();
1575×
    if json {
1583×
        println!("{}", repo.status_json(&snap)?);
1593×
        return Ok(if snap.base_snapshot.is_conflicted() {
1600×
            2
161
        } else {
1623×
            0
163
        });
1642×
    }
1652×
    println!(
166
        "{} {}{}working copy {}{}{}",
1672×
        ui::dim("On"),
1682×
        ui::bookmark(&repo.config.bookmark),
1692×
        ui::sep(),
1702×
        ui::id(snap.wc.change_id.short(8)),
1712×
        ui::sep(),
1722×
        ui::dim(plural(heads.len(), "head"))
173
    );
1742×
    print_statuses(&snap.statuses);
1752×
    print_untracked_nested(&repo, &snap.untracked_nested);
1762×
    if !snap.base_snapshot.is_conflicted() {
1772×
        return Ok(0);
1780×
    }
1790×
    println!();
1800×
    println!(
181
        "{} {}",
1820×
        ui::section(ui::err("Conflicts")),
1830×
        ui::dim("edit the marked files, or the .oxy-conflict-N candidates, then commit")
184
    );
1850×
    for c in &snap.base_snapshot.tree.conflicts {
1860×
        println!("  {} tree: {c:?}", ui::err(ui::glyph("✱", "!")));
1870×
    }
1880×
    for (p, f) in &snap.base_snapshot.files {
1890×
        if f.is_conflicted() {
1900×
            let state = match snap
1910×
                .statuses
1920×
                .iter()
1930×
                .find(|s| s.path == *p)
1940×
                .map(|s| s.status)
195
            {
196
                Some(ChangeStatus::Resolved) => {
1970×
                    ui::ok(format!("{} resolved in working copy", ui::glyph("✔", "*")))
198
                }
199
                Some(ChangeStatus::ConflictEdited) => {
2000×
                    ui::warn(format!("{} markers remain", ui::glyph("‼", "!")))
201
                }
2020×
                _ => ui::err(format!("{} unresolved", ui::glyph("✱", "!"))),
203
            };
2040×
            println!("  {}  {state}", ui::path(p));
2050×
        }
206
    }
2070×
    Ok(2)
2087×
}
209
21022×
pub fn commit(
21122×
    message: &str,
21222×
    depends_on: &[String],
21322×
    paths: &[String],
21422×
    interactive: bool,
21522×
    hunks: &[usize],
21622×
) -> Result<i32> {
21722×
    let repo = open()?;
21822×
    let mut deps = Vec::new();
21922×
    for d in depends_on {
2200×
        deps.push(repo.resolve_change(d)?);
221
    }
22222×
    let selection = if !hunks.is_empty() {
2231×
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
22421×
    } else if interactive {
2250×
        let (_, hunks) = repo.hunks()?;
2260×
        if hunks.is_empty() {
2270×
            anyhow::bail!("nothing to commit: the working copy matches its base");
2280×
        }
2290×
        let hunks: Vec<_> = hunks
2300×
            .into_iter()
2310×
            .filter(|h| {
2320×
                paths.is_empty()
2330×
                    || paths.iter().any(|p| {
2340×
                        h.path == *p || h.path.starts_with(&format!("{}/", p.trim_end_matches('/')))
2350×
                    })
2360×
            })
2370×
            .collect();
2380×
        let mut chosen = Vec::new();
2390×
        let stdin = std::io::stdin();
2400×
        let mut take_rest = false;
2410×
        for (n, h) in hunks.iter().enumerate() {
2420×
            if take_rest {
2430×
                chosen.push(h.index);
2440×
                continue;
2450×
            }
2460×
            println!(
247
                "{} {} {}",
2480×
                ui::section(format!("hunk {} of {}", n + 1, hunks.len())),
2490×
                ui::path(&h.path),
2500×
                ui::dim(format!("(#{})", h.index))
251
            );
2520×
            for line in h.text.lines() {
2530×
                let styled = if line.starts_with('+') {
2540×
                    ui::ok(line)
2550×
                } else if line.starts_with('-') {
2560×
                    ui::err(line)
257
                } else {
2580×
                    ui::dim(line)
259
                };
2600×
                println!("  {styled}");
261
            }
262
            loop {
2630×
                print!(
264
                    "{} ",
2650×
                    ui::warn("Commit this hunk? [y]es [n]o [a]ll remaining [q]uit:")
266
                );
267
                use std::io::Write as _;
2680×
                std::io::stdout().flush()?;
2690×
                let mut answer = String::new();
2700×
                if stdin.read_line(&mut answer)? == 0 {
2710×
                    anyhow::bail!("aborted");
2720×
                }
2730×
                match answer.trim() {
2740×
                    "y" | "Y" => {
2750×
                        chosen.push(h.index);
2760×
                        break;
277
                    }
2780×
                    "n" | "N" | "" => break,
2790×
                    "a" | "A" => {
2800×
                        chosen.push(h.index);
2810×
                        take_rest = true;
2820×
                        break;
283
                    }
2840×
                    "q" | "Q" => anyhow::bail!("aborted; nothing committed"),
2850×
                    _ => continue,
286
                }
287
            }
288
        }
2890×
        if chosen.is_empty() {
2900×
            anyhow::bail!("no hunks chosen; nothing committed");
2910×
        }
2920×
        oxy_core::repo::Selection::Hunks(chosen)
29321×
    } else if paths.is_empty() {
29421×
        oxy_core::repo::Selection::All
295
    } else {
2960×
        oxy_core::repo::Selection::Paths(paths.to_vec())
297
    };
29822×
    let sp = ui::spinner("Committing…");
29922×
    let h = repo.commit_selection(message, &deps, &selection)?;
300
    // The metadata only: a first commit's change holds the whole tree.
30122×
    let meta = repo.store().get_change_meta(&h)?;
30222×
    sp.done(&format!(
30322×
        "{} {} {}  {}",
30422×
        ui::done("Committed"),
30522×
        ui::id(meta.change_id.short(8)),
30622×
        ui::hash(format!("#{}", h.short(12))),
30722×
        ui::subject(subject_of(message))
30822×
    ));
30922×
    print_untracked_nested(&repo, &repo.untracked_nested());
31022×
    if !matches!(selection, oxy_core::repo::Selection::All) {
3111×
        let rest = repo.snapshot_status("oxy commit")?;
3121×
        if !rest.statuses.is_empty() {
3131×
            println!(
3141×
                "  {} {}",
3151×
                ui::note(),
3161×
                ui::dim(format!(
3171×
                    "{} left uncommitted",
3181×
                    plural(rest.statuses.len(), "path")
3191×
                ))
3201×
            );
3211×
        }
32221×
    }
32322×
    where_now(&repo);
32422×
    Ok(0)
32522×
}
326
3270×
pub fn blame(path: &str, json: bool) -> Result<i32> {
3280×
    let repo = open()?;
3290×
    let lines = repo.blame(path)?;
3300×
    if json {
3310×
        let items = lines.iter().map(|l| {
3320×
            format!(
333
                "{{\"line\":{},\"change_id\":{},\"hash\":{},\"index\":{},\"author\":{},\"when_ms\":{}}}",
334
                l.line,
3350×
                oxy_core::repo::json_str(&l.change_id.to_hex()),
3360×
                oxy_core::repo::json_str(&l.hash.to_hex()),
337
                l.index,
3380×
                oxy_core::repo::json_str(&l.author),
339
                l.when_ms
340
            )
3410×
        });
3420×
        println!("{}", oxy_core::repo::json_array(items));
3430×
        return Ok(0);
3440×
    }
3450×
    let width = lines
3460×
        .iter()
3470×
        .map(|l| l.author.chars().count())
3480×
        .max()
3490×
        .unwrap_or(0)
3500×
        .min(20);
3510×
    let digits = lines.len().to_string().len();
3520×
    let _t = oxy_core::timing::phase("blame: print");
353
    // Most lines share their change with many others: each change's id,
354
    // author and age are formatted once, and the lines go out through one
355
    // buffered lock on stdout.
3560×
    let mut prefix: std::collections::HashMap<oxy_core::hash::ChangeHash, String> =
3570×
        std::collections::HashMap::new();
3580×
    let bar = ui::dim(ui::glyph("│", "|"));
3590×
    let mut out = std::io::BufWriter::with_capacity(1 << 16, std::io::stdout().lock());
3600×
    for l in &lines {
3610×
        let p = prefix.entry(l.hash).or_insert_with(|| {
3620×
            let author: String = l.author.chars().take(20).collect();
3630×
            format!(
364
                "{} {} {}",
3650×
                ui::id(l.change_id.short(8)),
3660×
                ui::author(format!("{author:<width$}")),
3670×
                ui::dim(ui::ago(l.when_ms))
368
            )
3690×
        });
3700×
        let text = String::from_utf8_lossy(&l.text);
3710×
        if writeln!(
3720×
            out,
373
            "{p} {:>digits$}{bar} {}",
374
            l.line,
3750×
            text.trim_end_matches('\n')
376
        )
3770×
        .is_err()
378
        {
379
            // A closed pipe (blame | head): stop quietly.
3800×
            return Ok(0);
3810×
        }
382
    }
3830×
    let _ = out.flush();
3840×
    Ok(0)
3850×
}
386
3870×
fn bisect_report(repo: &Repo, step: &oxy_core::repo::BisectStep) -> Result<i32> {
388
    use oxy_core::repo::BisectStep::*;
3890×
    match step {
3900×
        NeedMarks { good, bad } => {
3910×
            println!(
392
                "{} {} {}",
3930×
                ui::note(),
3940×
                ui::dim(format!("{good} good, {bad} bad;")),
3950×
                ui::dim(if *good == 0 {
3960×
                    "mark a known-good change or bookmark: oxy bisect good CHANGE"
397
                } else {
3980×
                    "mark a known-bad change or bookmark: oxy bisect bad CHANGE"
399
                })
400
            );
4010×
            Ok(0)
402
        }
403
        Testing {
4040×
            heads,
4050×
            remaining,
4060×
            steps_left,
407
        } => {
4080×
            println!(
409
                "{} {} {}",
4100×
                ui::done("Testing"),
4110×
                ui::dim(format!(
412
                    "{} in the state under test;",
4130×
                    plural(heads.len(), "head")
414
                )),
4150×
                ui::dim(format!(
416
                    "{remaining} candidates left, about {steps_left} more steps"
417
                ))
418
            );
4190×
            println!(
420
                "  {} {}",
4210×
                ui::note(),
4220×
                ui::dim("run your test, then oxy bisect good | bad | skip")
423
            );
4240×
            Ok(0)
425
        }
4260×
        Found { culprit } => {
4270×
            let c = repo.store().get_change(culprit)?;
4280×
            println!(
429
                "{} {} {}  {}",
4300×
                ui::done("Found"),
4310×
                ui::id(short_id(&c)),
4320×
                ui::hash(format!("#{}", culprit.short(12))),
4330×
                ui::subject(subject_of(&c.message))
434
            );
4350×
            println!("  {} {}", ui::note(), ui::dim("the first change whose inclusion makes the state bad; oxy bisect reset to return"));
4360×
            Ok(0)
437
        }
4380×
        Inconclusive { candidates } => {
4390×
            println!(
440
                "{} {}",
4410×
                ui::caution(),
4420×
                ui::warn(format!(
443
                    "every remaining candidate was skipped ({}); oxy bisect reset to return",
4440×
                    plural(candidates.len(), "change")
445
                ))
446
            );
4470×
            Ok(1)
448
        }
449
    }
4500×
}
451
4520×
pub fn bisect_start() -> Result<i32> {
4530×
    let repo = open()?;
4540×
    repo.bisect_start()?;
4550×
    println!(
456
        "{} bisect; {}",
4570×
        ui::done("Started"),
4580×
        ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE")
459
    );
4600×
    Ok(0)
4610×
}
462
4630×
pub fn bisect_mark(good: Option<bool>, changes: &[String]) -> Result<i32> {
4640×
    let repo = open()?;
4650×
    let mut heads = Vec::new();
4660×
    for c in changes {
4670×
        heads.extend(repo.resolve_heads(c)?);
468
    }
4690×
    let step = repo.bisect_mark(good, &heads)?;
4700×
    bisect_report(&repo, &step)
4710×
}
472
4730×
pub fn bisect_run(command: &[String]) -> Result<i32> {
4740×
    let repo = open()?;
4750×
    let step = repo.bisect_run(command)?;
4760×
    bisect_report(&repo, &step)
4770×
}
478
4791×
pub fn bisect_status(as_json: bool) -> Result<i32> {
4801×
    let repo = open()?;
4811×
    if as_json {
482
        use oxy_core::repo::BisectStep::*;
4831×
        let v = match repo.bisect_status()? {
4841×
            None => "null".to_string(),
4850×
            Some(NeedMarks { good, bad }) => json::obj([
4860×
                ("state", json::s("need-marks")),
4870×
                ("good", json::n(good)),
4880×
                ("bad", json::n(bad)),
4890×
            ]),
490
            Some(Testing {
4910×
                heads,
4920×
                remaining,
4930×
                steps_left,
4940×
            }) => json::obj([
4950×
                ("state", json::s("testing")),
4960×
                ("heads", json::hashes(&heads)),
4970×
                ("remaining", json::n(remaining)),
4980×
                ("steps_left", json::n(steps_left)),
4990×
            ]),
5000×
            Some(Found { culprit }) => json::obj([
5010×
                ("state", json::s("found")),
5020×
                ("culprit", json::s(&culprit.to_hex())),
5030×
            ]),
5040×
            Some(Inconclusive { candidates }) => json::obj([
5050×
                ("state", json::s("inconclusive")),
5060×
                ("candidates", json::hashes(&candidates)),
5070×
            ]),
508
        };
5091×
        println!("{v}");
5101×
        return Ok(0);
5110×
    }
5120×
    match repo.bisect_status()? {
513
        None => {
5140×
            println!("{}", ui::dim("No bisect in progress."));
5150×
            Ok(0)
516
        }
5170×
        Some(step) => bisect_report(&repo, &step),
518
    }
5191×
}
520
5210×
pub fn bisect_reset() -> Result<i32> {
5220×
    let repo = open()?;
5230×
    repo.bisect_reset()?;
5240×
    println!("{} bisect; working copy restored", ui::done("Reset"));
5250×
    Ok(0)
5260×
}
527
528
/// The log: one entry per change, newest first, joined by a rail. The
529
/// default view is the subject and a metadata line; `verbose` adds the full
530
/// message, dependencies, and the authenticating key.
53111×
fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
53211×
    Ok(match repo.authenticate_change(h)? {
5336×
        SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]),
534
        SignatureStatus::Valid {
5355×
            key,
5365×
            name,
5375×
            email,
5385×
            sealed,
5395×
            revoked,
5405×
        } => json::obj([
5415×
            ("status", json::s(if sealed { "sealed" } else { "signed" })),
5425×
            ("key", json::s(&key.to_hex())),
5435×
            ("name", json::s(&name)),
5445×
            ("email", json::s(&email)),
5455×
            ("revoked", json::b(revoked)),
546
        ]),
5470×
        SignatureStatus::Invalid(why) => {
5480×
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
549
        }
550
    })
55111×
}
552
55314×
fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result<String> {
55414×
    let c = &e.change;
55514×
    Ok(json::obj([
55614×
        ("hash", json::s(&e.hash.to_hex())),
55714×
        ("change_id", json::s(&c.change_id.to_hex())),
55814×
        ("author", json::s(&author_name(repo, c))),
55914×
        ("author_key", json::s(&c.author.to_hex())),
560
        (
56114×
            "via",
56214×
            match via(
56314×
                repo,
56414×
                &repo.authenticate_change_known(&e.hash, Some(c))?,
56514×
                &c.author,
566
            ) {
5670×
                Some(v) => json::obj([
5680×
                    ("name", json::s(&v.name)),
5690×
                    ("email", json::s(&v.email)),
5700×
                    ("key", json::s(&v.key.to_hex())),
5710×
                    ("scope", json::opt(v.scope.as_deref(), json::s)),
5720×
                    ("expires_ms", json::opt(v.expires, json::n)),
5730×
                    ("revoked", json::b(v.revoked)),
5740×
                ]),
57514×
                None => "null".to_string(),
576
            },
577
        ),
57814×
        ("when_ms", json::n(c.hlc.wall_ms)),
57914×
        ("message", json::s(&c.message)),
58014×
        ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())),
58114×
        ("deps", json::hashes(&c.deps)),
58214×
        ("head", json::b(e.is_head)),
58314×
        ("working_copy", json::b(e.is_working_copy)),
584
        (
58514×
            "signature",
58614×
            if e.is_working_copy {
5873×
                "null".into()
588
            } else {
58911×
                signature_json(repo, &e.hash)?
590
            },
591
        ),
592
    ]))
59314×
}
594
595
/// `START,END:PATH` for `oxy log -L`.
5962×
fn parse_line_range(spec: &str) -> Result<(usize, usize, &str)> {
5972×
    let bad = || anyhow::anyhow!("-L {spec}: expected START,END:PATH, as 10,24:src/lib.rs");
5982×
    let (range, path) = spec.split_once(':').ok_or_else(bad)?;
5992×
    let (a, b) = range.split_once(',').ok_or_else(bad)?;
600
    Ok((
6011×
        a.trim().parse().map_err(|_| bad())?,
6021×
        b.trim().parse().map_err(|_| bad())?,
6031×
        path,
604
    ))
6052×
}
606
6077×
pub fn log(
6087×
    revset: Option<&str>,
6097×
    limit: Option<usize>,
6107×
    verbose: bool,
6117×
    path: Option<&str>,
6127×
    lines: Option<&str>,
6137×
    as_json: bool,
6147×
) -> Result<i32> {
6157×
    let repo = open()?;
616
    // Whether the working copy is clean and conflicted: from the manifest
617
    // when it proves the working copy clean, else from a snapshot.
618
    // The working copy as last recorded, without looking at the files (as
619
    // Git's log does not): whether its change holds edits, and whether its
620
    // base was conflicted. `oxy status` is what checks the disk.
6217×
    let conflicted = !repo.is_at_op() && repo.recorded_conflicted()?;
6227×
    let listing = oxy_core::timing::phase("log: entries");
6237×
    let entries = match (path, lines) {
6247×
        _ if revset.is_some() => repo.log_revset(revset.unwrap_or_default())?,
6252×
        (_, Some(spec)) => {
6262×
            let (first, last, p) = parse_line_range(spec)?;
6271×
            let (_, wc) = repo.working_copy()?;
6281×
            let base = repo.load_state_history(&wc.deps)?.maximal(&wc.deps);
6291×
            repo.line_history(&base, p, first, last)?
630
        }
6311×
        (Some(p), None) => repo.log_for_path(p)?,
6324×
        (None, None) => repo.log()?,
633
    };
6346×
    drop(listing);
6356×
    let _print = oxy_core::timing::phase("log: print");
6366×
    if as_json {
6375×
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
6385×
        let mut items = Vec::new();
63913×
        for e in entries.iter().take(shown) {
64013×
            items.push(log_entry_json(&repo, e)?);
641
        }
6425×
        println!(
643
            "{}",
6445×
            json::obj([
6455×
                ("bookmark", json::s(&repo.config.bookmark)),
6465×
                ("total", json::n(entries.len())),
6475×
                ("changes", json::arr(items))
6485×
            ])
649
        );
6505×
        return Ok(0);
6511×
    }
6521×
    let total = entries.len();
6531×
    let shown = limit.unwrap_or(total).min(total);
654
    // Lay out a little past what is shown, so edges into the cut are drawn.
6551×
    let window: Vec<(ChangeHash, Vec<ChangeHash>)> = entries
6561×
        .iter()
6571×
        .take((shown + MAX_EDGE).min(total))
6584×
        .map(|e| (e.hash, e.change.deps.clone()))
6591×
        .collect();
6601×
    let rows = oxy_core::lanes::graph(&window, MAX_EDGE);
661
    // Highlight the shortest prefix that names each change: against the
662
    // whole log, which is what `resolve_change` searches.
663
    let everything;
6641×
    let all = if path.is_some() || lines.is_some() || revset.is_some() {
6650×
        everything = repo.log()?;
6660×
        &everything
667
    } else {
6681×
        &entries
669
    };
6704×
    let id_prefix = unique_prefixes(all.iter().map(|e| e.change.change_id.to_hex()));
6711×
    let labels = reference_labels(&repo)?;
6724×
    for (e, row) in entries.iter().take(shown).zip(&rows) {
6734×
        let c = &e.change;
6744×
        let bullet = ui::log_bullet(
6754×
            e.is_working_copy,
6764×
            e.is_head,
6774×
            e.is_working_copy && conflicted,
678
        );
6794×
        let id = c.change_id.to_hex();
6804×
        let n = id_prefix.get(&id).copied().unwrap_or(8).min(8);
6814×
        let mut head = vec![format!("{}{}", ui::id(&id[..n]), ui::dim(&id[n..8]))];
6824×
        head.push(ui::author(author_name(&repo, c)));
6834×
        head.push(ui::dim(ui::ago(c.hlc.wall_ms)));
6844×
        if let Some(names) = labels.get(&e.hash) {
6852×
            head.push(names.join(" "));
6862×
        }
6874×
        if c.kind == ChangeKind::Resolution {
6880×
            head.push(ui::warn("resolution"));
6894×
        }
6904×
        if !e.is_working_copy {
6913×
            head.push(ui::hash(format!("#{}", e.hash.short(8))));
6923×
            let status = repo.authenticate_change_known(&e.hash, Some(c))?;
6933×
            if let Some(agent) = via(&repo, &status, &c.author) {
6940×
                head.push(ui::dim(format!("via {}", agent.name)));
6953×
            }
6963×
            head.push(signature_mark_of(&status));
6971×
        }
6984×
        println!("{}{}", node_line(row, &bullet), head.join(" "));
6994×
        let subject = if e.is_working_copy && c.message.is_empty() {
7001×
            let edited = repo
7011×
                .store()
7021×
                .get_change(&e.hash)
7031×
                .is_ok_and(|w| !w.tree_ops.is_empty() || !w.edits.is_empty());
7041×
            ui::dim(if edited {
7050×
                "(working copy, uncommitted changes)"
706
            } else {
7071×
                "(working copy)"
708
            })
7093×
        } else if c.message.trim().is_empty() {
7100×
            ui::dim("(no description)")
711
        } else {
7123×
            subject_of(&c.message).to_string()
713
        };
7144×
        println!("{}{subject}", below_line(row));
7154×
        if verbose {
7160×
            let rail = continuation(row);
7170×
            if !e.is_working_copy {
7180×
                println!(
719
                    "{rail}{}",
7200×
                    ui::dim(format!(
721
                        "{} {}",
7220×
                        when(c.hlc.wall_ms),
7230×
                        signature_line(&repo, &e.hash)?
724
                    ))
725
                );
7260×
            }
7270×
            if !c.deps.is_empty() {
7280×
                println!(
7290×
                    "{rail}{} {}",
7300×
                    ui::dim(ui::glyph("↳", "->")),
7310×
                    ui::dim(deps_of(&c.deps))
7320×
                );
7330×
            }
7340×
            let body: Vec<&str> = c
7350×
                .message
7360×
                .lines()
7370×
                .skip(1)
7380×
                .skip_while(|l| l.trim().is_empty())
7390×
                .collect();
7400×
            for line in body {
7410×
                println!("{rail}  {line}");
7420×
            }
7434×
        }
744
    }
7451×
    if shown < total {
7460×
        if let Some(last) = rows.get(shown.saturating_sub(1)) {
7470×
            let cut: String = last
7480×
                .below
7490×
                .iter()
7500×
                .map(|c| match c {
7510×
                    Cell::Blank | Cell::Elided | Cell::JoinRight => "  ",
7520×
                    _ => "~ ",
7530×
                })
7540×
                .collect();
7550×
            if cut.trim().is_empty() {
7560×
                println!("{}", ui::dim("~"));
7570×
            } else {
7580×
                println!("{}", ui::dim(cut.trim_end()));
7590×
            }
7600×
        }
7610×
        println!(
762
            "{}",
7630×
            ui::dim(format!(
764
                "{} {} more; pass -n to see them",
7650×
                ui::glyph("…", "..."),
7660×
                total - shown
767
            ))
768
        );
7691×
    }
7701×
    Ok(0)
7717×
}
772
773
/// Rows a drawn edge may span in `oxy log`; a longer one is elided (`~`).
774
const MAX_EDGE: usize = 12;
775
776
use oxy_core::hash::ChangeHash;
777
use oxy_core::lanes::{Cell, GraphRow};
778
779
/// A graph cell, two columns wide.
7806×
fn cell(c: Cell) -> &'static str {
7816×
    match c {
7821×
        Cell::Blank => "  ",
7833×
        Cell::Line => ui::glyph("│ ", "| "),
7840×
        Cell::Elided => "~ ",
7851×
        Cell::JoinLeft => ui::glyph("├─", "|-"),
7860×
        Cell::JoinPass => ui::glyph("──", "--"),
7870×
        Cell::JoinCross => ui::glyph("┼─", "+-"),
7881×
        Cell::JoinRight => ui::glyph("╯ ", "' "),
789
    }
7906×
}
791
792
/// The graph part of a change's own line, its bullet in its column.
7934×
fn node_line(row: &GraphRow, bullet: &str) -> String {
7944×
    let width = row
7954×
        .passing
7964×
        .iter()
7974×
        .copied()
7984×
        .max()
7994×
        .unwrap_or(0)
8004×
        .max(row.column)
8014×
        + 1;
8024×
    let mut out = String::new();
8035×
    for c in 0..width {
8045×
        if c == row.column {
8054×
            out.push_str(bullet);
8064×
            out.push(' ');
8074×
        } else if row.passing.contains(&c) {
8081×
            out.push_str(&ui::dim(cell(Cell::Line)));
8091×
        } else {
8100×
            out.push_str("  ");
8110×
        }
812
    }
8134×
    out.push(' ');
8144×
    out
8154×
}
816
817
/// The graph part of the line under a change: lanes carrying on, a join,
818
/// or `~` for an elided edge.
8194×
fn below_line(row: &GraphRow) -> String {
8205×
    let g: String = row.below.iter().map(|c| cell(*c)).collect();
8214×
    format!("{} ", ui::dim(g))
8224×
}
823
824
/// The graph part of any further line of a change (`-v`).
8250×
fn continuation(row: &GraphRow) -> String {
8260×
    let g: String = row
8270×
        .below
8280×
        .iter()
8290×
        .map(|c| match c {
8300×
            Cell::Line | Cell::JoinLeft | Cell::JoinCross => cell(Cell::Line),
8310×
            _ => "  ",
8320×
        })
8330×
        .collect();
8340×
    format!("{} ", ui::dim(g))
8350×
}
836
837
/// For each hex ID, the length of its shortest prefix no other ID shares.
8381×
fn unique_prefixes(ids: impl Iterator<Item = String>) -> std::collections::HashMap<String, usize> {
8391×
    let mut v: Vec<String> = ids.collect();
8401×
    v.sort();
8411×
    v.dedup();
8426×
    let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
8431×
    let mut out = std::collections::HashMap::with_capacity(v.len());
8444×
    for i in 0..v.len() {
8454×
        let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 };
8464×
        let after = if i + 1 < v.len() {
8473×
            common(&v[i], &v[i + 1])
848
        } else {
8491×
            0
850
        };
8514×
        out.insert(v[i].clone(), before.max(after) + 1);
852
    }
8531×
    out
8541×
}
855
856
/// Bookmark, remote bookmark and tag names to show beside the changes they
857
/// point at. A name is shown on each head of its state; one with more than
858
/// three heads names too much of the log to help, so it is left out (oxy
859
/// bookmark list shows it). A remote bookmark at the same state as the
860
/// local one of that name is not repeated.
8611×
fn reference_labels(repo: &Repo) -> Result<std::collections::HashMap<ChangeHash, Vec<String>>> {
862
    const MAX_HEADS: usize = 3;
8631×
    let view = repo.view()?;
8641×
    let mut out: std::collections::HashMap<ChangeHash, Vec<String>> = Default::default();
8651×
    let mut add = |heads: Vec<ChangeHash>, label: String| {
8661×
        if heads.len() <= MAX_HEADS {
8672×
            for h in heads {
8682×
                out.entry(h).or_default().push(label.clone());
8692×
            }
8700×
        }
8711×
    };
8721×
    for (name, st) in &view.bookmarks {
8731×
        add(repo.store().get_state(st)?.heads, ui::bookmark(name));
874
    }
8751×
    for (remote, bookmarks) in &view.remotes {
8760×
        for (name, st) in bookmarks {
8770×
            if view.bookmarks.get(name) == Some(st) {
8780×
                continue;
8790×
            }
8800×
            add(
8810×
                repo.store().get_state(st)?.heads,
8820×
                ui::dim(format!("{remote}/{name}")),
883
            );
884
        }
885
    }
8861×
    for t in repo.tags()? {
8870×
        add(t.heads.clone(), ui::warn(&t.name));
8880×
    }
8891×
    Ok(out)
8901×
}
891
8921×
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
8931×
    let repo = open()?;
8941×
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
8951×
    if as_json {
8961×
        let files = repo.diff_files(hash.as_ref())?;
8973×
        let items = files.iter().map(|f| {
8983×
            json::obj([
8993×
                ("path", json::s(&f.path)),
9003×
                ("kind", json::s(&f.kind)),
9013×
                ("from", json::opt(f.from.as_deref(), json::s)),
902
                (
9033×
                    "hunks",
9043×
                    json::arr(f.hunks.iter().map(|h| {
9053×
                        json::obj([
9063×
                            ("base_line", json::n(h.base_line)),
907
                            (
9083×
                                "added",
9093×
                                json::arr(
9103×
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
911
                                ),
912
                            ),
913
                            (
9143×
                                "removed",
9153×
                                json::arr(h.removed.iter().map(|(n, l)| {
9160×
                                    json::obj([
9170×
                                        ("line", json::n(*n)),
9180×
                                        ("text", json::s(&String::from_utf8_lossy(l))),
9190×
                                    ])
9200×
                                })),
921
                            ),
922
                        ])
9233×
                    })),
924
                ),
925
            ])
9263×
        });
9271×
        println!(
928
            "{}",
9291×
            json::obj([
9301×
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
9311×
                ("files", json::arr(items))
932
            ])
933
        );
9341×
        return Ok(0);
9350×
    }
9360×
    match hash {
9370×
        Some(h) => {
9380×
            let c = repo.store().get_change(&h)?;
9390×
            let (base, snapshot) = repo.change_base(&c)?;
9400×
            print!("{}", render_change(&c, &base, &snapshot));
941
        }
942
        None => {
9430×
            let (wc, base, snapshot) = repo.working_copy_with_base()?;
9440×
            let text = {
9450×
                let _t = oxy_core::timing::phase("diff: render the change");
9460×
                render_change(&wc, &base, &snapshot)
947
            };
9480×
            print!("{text}");
949
            // The process ends here: freeing the base's tree and graphs
950
            // one by one would only cost time (about 27 ms on Linux).
9510×
            std::mem::forget((wc, base, snapshot));
952
        }
953
    }
9540×
    Ok(0)
9551×
}
956
9572×
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
9582×
    let repo = open()?;
9592×
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
9602×
    let bytes = repo.file_at(path, heads.as_deref())?;
961
    use std::io::Write as _;
9622×
    std::io::stdout().write_all(&bytes)?;
9632×
    Ok(0)
9642×
}
965
9661×
pub fn root(as_json: bool) -> Result<i32> {
9671×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
9680×
        if as_json {
9690×
            println!("null");
9700×
        }
9710×
        return Ok(1);
972
    };
9731×
    if as_json {
9741×
        println!(
9751×
            "{}",
9761×
            json::obj([
9771×
                ("root", json::s(&repo.root().to_string_lossy())),
9781×
                ("workspace", json::s(&repo.workspace().to_hex())),
9791×
                ("bookmark", json::s(&repo.config.bookmark))
9801×
            ])
9811×
        );
9821×
    } else {
9830×
        println!("{}", repo.root().display());
9840×
    }
9851×
    Ok(0)
9861×
}
987
9881×
pub fn version(as_json: bool) -> Result<i32> {
9891×
    if as_json {
9901×
        println!(
9911×
            "{}",
9921×
            json::obj([
9931×
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
9941×
                // What was built: a release's or install's `oxy describe`,
9951×
                // a Flow build's heads, or "local build".
9961×
                ("build", json::s(env!("OXY_BUILD_ID"))),
9971×
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
9981×
                ("format", json::n(2))
9991×
            ])
10001×
        );
10011×
    } else {
10020×
        println!(
10030×
            "oxy {} (repository format 2, protocol {})",
10040×
            env!("OXY_VERSION_LONG"),
10050×
            oxy_core::protocol::PROTOCOL_VERSION
10060×
        );
10070×
    }
10081×
    Ok(0)
10091×
}
1010
10112×
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
10122×
    let repo = open()?;
10132×
    if paths.is_empty() && hunks.is_empty() {
10140×
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
10152×
    }
10162×
    let mut n = 0;
10172×
    if !hunks.is_empty() {
10181×
        n += repo.discard_hunks(hunks)?;
10191×
    }
10202×
    if !paths.is_empty() {
10211×
        n += repo.discard(paths)?;
10221×
    }
10232×
    println!(
1024
        "{} {} restored to the working copy's base",
10252×
        ui::done("Discarded"),
10262×
        plural(n, "path")
1027
    );
10282×
    Ok(0)
10292×
}
1030
10312×
pub fn hunks(as_json: bool) -> Result<i32> {
10322×
    let repo = open()?;
10332×
    let (_, hunks) = repo.hunks()?;
10342×
    if as_json {
10352×
        println!(
1036
            "{}",
10375×
            json::arr(hunks.iter().map(|h| json::obj([
10385×
                ("index", json::n(h.index)),
10395×
                ("path", json::s(&h.path)),
10405×
                ("text", json::s(&h.text))
10415×
            ])))
1042
        );
10432×
        return Ok(0);
10440×
    }
10450×
    if hunks.is_empty() {
10460×
        println!(
10470×
            "{}",
10480×
            ui::dim("No hunks: the working copy matches its base.")
10490×
        );
10500×
    }
10510×
    for h in &hunks {
10520×
        println!(
1053
            "{} {}",
10540×
            ui::section(format!("hunk {}", h.index)),
10550×
            ui::path(&h.path)
1056
        );
10570×
        for line in h.text.lines() {
10580×
            let styled = if line.starts_with('+') {
10590×
                ui::ok(line)
10600×
            } else if line.starts_with('-') {
10610×
                ui::err(line)
1062
            } else {
10630×
                ui::dim(line)
1064
            };
10650×
            println!("  {styled}");
1066
        }
1067
    }
10680×
    Ok(0)
10692×
}
1070
10712×
pub fn show(change: Option<&str>, revset: Option<&str>, as_json: bool) -> Result<i32> {
10722×
    let repo = open()?;
10732×
    repo.snapshot_status("oxy show")?;
10742×
    let Some(r) = revset else {
10752×
        let h = repo.resolve_change(change.unwrap_or("@"))?;
10762×
        return show_one(&repo, h, as_json, false);
1077
    };
1078
    // Several changes: a JSON array, or the changes one after another.
10790×
    let hashes = repo.revset(r)?.hashes;
10800×
    if as_json {
10810×
        print!("[");
10820×
        for (i, h) in hashes.iter().enumerate() {
10830×
            if i > 0 {
10840×
                print!(",");
10850×
            }
10860×
            show_one(&repo, *h, true, true)?;
1087
        }
10880×
        println!("]");
10890×
        return Ok(0);
10900×
    }
10910×
    if hashes.is_empty() {
10920×
        println!("{}", ui::dim(format!("No change matches {r:?}.")));
10930×
        return Ok(0);
10940×
    }
10950×
    for (i, h) in hashes.iter().enumerate() {
10960×
        if i > 0 {
10970×
            println!();
10980×
        }
10990×
        show_one(&repo, *h, false, false)?;
1100
    }
11010×
    Ok(0)
11022×
}
1103
1104
/// One change, as `oxy show` prints it; `inline` JSON goes without its
1105
/// newline, for an array.
11062×
fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool) -> Result<i32> {
11072×
    let c = repo.store().get_change(&h)?;
11082×
    if as_json {
11091×
        let files = repo.diff_files(Some(&h))?;
11101×
        let heads = repo.bookmark_heads()?;
11111×
        let entry = oxy_core::repo::LogEntry {
11121×
            hash: h,
11131×
            change: oxy_core::state::ChangeMeta::of(&c),
11141×
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
11151×
            is_head: heads.contains(&h),
11161×
        };
11171×
        let mut body = log_entry_json(repo, &entry)?;
11181×
        body.pop();
11191×
        body.push_str(&format!(
1120
            ",{}:{}}}",
11211×
            json::s("files"),
11221×
            json::arr(files.iter().map(|f| json::obj([
11231×
                ("path", json::s(&f.path)),
11241×
                ("kind", json::s(&f.kind)),
11251×
                ("from", json::opt(f.from.as_deref(), json::s))
11261×
            ])))
1127
        ));
11281×
        if inline {
11290×
            print!("{body}");
11301×
        } else {
11311×
            println!("{body}");
11321×
        }
11331×
        return Ok(0);
11341×
    }
11351×
    println!(
1136
        "{} {} {}",
11371×
        ui::section("change"),
11381×
        ui::id(short_id(&c)),
11391×
        ui::hash(format!("#{h}"))
1140
    );
11411×
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1142
    // Fetched but not pulled (oxygen#56): say where it is.
11431×
    if let Some(at) = repo.remote_only_location(&h)? {
11440×
        println!(
11450×
            "{}",
11460×
            ui::kv(
11470×
                "only in",
11480×
                ui::warn(format!(
11490×
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
11500×
                ))
11510×
            )
11520×
        );
11531×
    }
11541×
    let meta = oxy_core::state::ChangeMeta::of(&c);
11551×
    let status = repo.authenticate_change_known(&h, Some(&meta))?;
11561×
    println!("{}", ui::kv("author", ui::author(author_name(repo, &meta))));
11571×
    if let Some(agent) = via(repo, &status, &meta.author) {
11580×
        println!("{}", ui::kv("via", agent.line()));
11591×
    }
11601×
    println!(
1161
        "{}",
11621×
        ui::kv(
11631×
            "date",
11641×
            format!(
1165
                "{} {}",
11661×
                when(c.hlc.wall_ms),
11671×
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1168
            )
1169
        )
1170
    );
11711×
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
11721×
    println!("{}", ui::kv("sig", signature_line(repo, &h)?));
11731×
    println!();
11744×
    for line in (if c.message.is_empty() {
11750×
        "(no description)"
1176
    } else {
11771×
        &c.message
1178
    })
11791×
    .lines()
11804×
    {
11814×
        println!("    {line}");
11824×
    }
11831×
    println!();
11841×
    print!("{}", repo.describe_change(&h)?);
11851×
    Ok(0)
11862×
}
1187
11880×
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
11890×
    let repo = open()?;
1190
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1191
    // BRANCH` is: checking its files out under another bookmark's name
1192
    // made the next commit move the wrong bookmark (oxygen#60).
11930×
    if let [name] = changes {
11940×
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
11950×
            drop(repo);
11960×
            return bookmark_switch(name, discard, carry);
11970×
        }
11980×
    }
11990×
    let heads = if changes.is_empty() {
12000×
        repo.bookmark_heads()?
1201
    } else {
12020×
        let mut heads = Vec::new();
12030×
        for c in changes {
12040×
            heads.extend(repo.resolve_heads(c)?);
1205
        }
12060×
        heads
1207
    };
12080×
    let spec = if changes.is_empty() {
12090×
        repo.config.bookmark.clone()
1210
    } else {
12110×
        changes.join(" ")
1212
    };
12130×
    let sp = ui::spinner(&format!("Checking out {spec}…"));
12140×
    let command = format!("oxy checkout {spec}");
12150×
    let (r, carried) = if carry {
12160×
        repo.checkout_carry(&heads, &spec, &command)?
1217
    } else {
12180×
        (repo.checkout(&heads, discard, &command)?, vec![])
1219
    };
12200×
    sp.done(&format!(
1221
        "{} on {}: {} written, {} removed{}",
12220×
        ui::done("Working copy"),
12230×
        ui::bookmark(&spec),
12240×
        plural(r.written, "file"),
1225
        r.removed,
12260×
        if carried.is_empty() {
12270×
            String::new()
1228
        } else {
12290×
            format!("; carried {}", plural(carried.len(), "changed path"))
1230
        }
1231
    ));
12320×
    for n in &r.notes {
12330×
        println!("  {} {n}", ui::note());
12340×
    }
12350×
    if r.conflicted {
12360×
        println!(
12370×
            "  {} {}",
12380×
            ui::caution(),
12390×
            ui::warn("this state has conflicts; see oxy status")
12400×
        );
12410×
    }
12420×
    where_now(&repo);
12430×
    Ok(0)
12440×
}
1245
12461×
pub fn resolve(as_json: bool) -> Result<i32> {
12471×
    let repo = open()?;
12481×
    let snap = repo.snapshot("oxy resolve")?;
12491×
    if as_json {
12501×
        println!("{}", repo.status_json(&snap)?);
12511×
        return Ok(if snap.base_snapshot.is_conflicted() {
12520×
            2
1253
        } else {
12541×
            0
1255
        });
12560×
    }
12570×
    if !snap.base_snapshot.is_conflicted() {
12580×
        println!("The working copy's base has no conflicts.");
12590×
        return Ok(0);
12600×
    }
12610×
    let mut remaining = 0;
12620×
    for (p, f) in &snap.base_snapshot.files {
12630×
        if !f.is_conflicted() {
12640×
            continue;
12650×
        }
12660×
        match snap
12670×
            .statuses
12680×
            .iter()
12690×
            .find(|s| s.path == *p)
12700×
            .map(|s| s.status)
1271
        {
12720×
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
12730×
            Some(ChangeStatus::ConflictEdited) => {
12740×
                remaining += 1;
12750×
                println!("markers    {p}");
12760×
            }
12770×
            _ => {
12780×
                remaining += 1;
12790×
                println!("unresolved {p}");
12800×
            }
1281
        }
1282
    }
12830×
    for c in &snap.base_snapshot.tree.conflicts {
12840×
        remaining += 1;
12850×
        println!("tree       {c:?}");
12860×
    }
12870×
    if remaining == 0 {
12880×
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
12890×
        Ok(0)
1290
    } else {
12910×
        Ok(2)
1292
    }
12931×
}
1294
12950×
pub fn undo() -> Result<i32> {
12960×
    let repo = open()?;
12970×
    let op = repo.undo()?;
12980×
    println!("{} now at: {}", ui::done("Undone;"), ui::dim(&op.command));
12990×
    where_now(&repo);
13000×
    Ok(0)
13010×
}
1302
13031×
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
13041×
    let repo = open()?;
13051×
    let ops = repo.op_log()?;
1306
    // What each operation changed, against the one before it.
130711×
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
130811×
        match ops.get(i + 1) {
130910×
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
13101×
            None => Ok(vec![]),
1311
        }
131211×
    };
13131×
    if as_json {
13141×
        let mut items = Vec::new();
131511×
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
131611×
            let summary: Vec<String> = changes_of(i)?
131711×
                .iter()
131811×
                .map(|c| change_words(&repo, c))
131911×
                .collect();
132011×
            items.push(json::obj([
132111×
                ("id", json::s(&r.to_hex())),
132211×
                ("when_ms", json::n(op.hlc.wall_ms)),
132311×
                ("command", json::s(&op.command)),
132411×
                ("snapshot", json::b(op.is_snapshot())),
132511×
                ("current", json::b(i == 0)),
132611×
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1327
            ]));
1328
        }
13291×
        println!("{}", json::arr(items));
13301×
        return Ok(0);
13310×
    }
13320×
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
13330×
    let id = |r: &oxy_core::hash::ObjectRef| {
13340×
        let hex = r.to_hex();
13350×
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
13360×
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
13370×
    };
13380×
    let rail = ui::dim(ui::glyph("│", "|"));
13390×
    let (mut i, mut shown) = (0, 0);
13400×
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
13410×
        let (r, op) = &ops[i];
13420×
        let bullet = if i == 0 {
13430×
            ui::ok(ui::glyph("@", "@"))
1344
        } else {
13450×
            ui::dim(ui::glyph("○", "o"))
1346
        };
1347
        // A run of snapshots folds into one entry.
13480×
        let mut run = 1;
13490×
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
13500×
            run += 1;
13510×
        }
13520×
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
13530×
        if op.is_snapshot() {
13540×
            let span = if run > 1 {
13550×
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1356
            } else {
13570×
                String::new()
1358
            };
13590×
            println!(
1360
                "{bullet}  {}{} {when}",
13610×
                id(r),
13620×
                if span.is_empty() {
13630×
                    String::new()
1364
                } else {
13650×
                    format!(" {span}")
1366
                }
1367
            );
13680×
            println!(
1369
                "{rail}  {}",
13700×
                ui::dim(if run == 1 {
13710×
                    "working-copy snapshot".to_string()
1372
                } else {
13730×
                    format!("{run} working-copy snapshots")
1374
                })
1375
            );
1376
        } else {
13770×
            println!("{bullet}  {} {when}", id(r));
13780×
            let words: Vec<String> = changes_of(i)?
13790×
                .iter()
13800×
                .map(|c| change_words(&repo, c))
13810×
                .collect();
13820×
            let summary = if words.is_empty() {
13830×
                if i + 1 == ops.len() {
13840×
                    "created the repository".to_string()
1385
                } else {
13860×
                    "no bookmark or working-copy change".to_string()
1387
                }
1388
            } else {
13890×
                words.join("; ")
1390
            };
13910×
            println!(
1392
                "{rail}  {}",
13930×
                if i == 0 {
13940×
                    ui::subject(&summary)
1395
                } else {
13960×
                    summary
1397
                }
1398
            );
13990×
            let cmd = op.command.lines().next().unwrap_or("");
14000×
            let cmd: String = cmd.chars().take(100).collect();
14010×
            println!("{rail}  {}", ui::dim(cmd));
1402
        }
14030×
        i += run;
14040×
        shown += 1;
1405
    }
14060×
    if i < ops.len() {
14070×
        println!(
14080×
            "{}",
14090×
            ui::dim(format!(
14100×
                "{} {} older; pass -n to see more",
14110×
                ui::glyph("…", "..."),
14120×
                plural(ops.len() - i, "operation")
14130×
            ))
14140×
        );
14150×
    }
14160×
    Ok(0)
14171×
}
1418
1419
/// One change an operation made, in words.
142011×
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1421
    use oxy_core::repo::ViewChange::*;
14222×
    match c {
14230×
        BookmarkCreated { name, heads } => {
14240×
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1425
        }
14260×
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
14272×
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
14281×
        BookmarkMoved { name, from, to } => format!(
1429
            "{name}: {from} {} {}",
14301×
            ui::glyph("→", "->"),
14311×
            plural(*to, "head")
1432
        ),
14331×
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
14340×
        TagCreated { name } => format!("tagged {name}"),
14350×
        TagDeleted { name } => format!("removed tag {name}"),
14360×
        Policy => "trust policy changed".to_string(),
14378×
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
14388×
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
14390×
            Err(_) => "working copy moved".to_string(),
1440
        },
1441
    }
144211×
}
1443
14440×
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
14450×
    let repo = open()?;
14460×
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
14470×
    let r = repo.op_restore(op, discard)?;
14480×
    sp.done(&format!(
14490×
        "{} to operation {} {}",
14500×
        ui::done("Restored"),
14510×
        ui::hash(r.op.short(12)),
14520×
        ui::dim(r.command.lines().next().unwrap_or(""))
14530×
    ));
14540×
    println!(
1455
        "  {} {}",
14560×
        ui::note(),
14570×
        ui::dim(format!(
1458
            "{} written, {} removed; oxy undo goes back again",
14590×
            plural(r.checkout.written, "file"),
1460
            r.checkout.removed
1461
        ))
1462
    );
14630×
    where_now(&repo);
14640×
    Ok(0)
14650×
}
1466
14670×
pub fn op_revert(op: &str) -> Result<i32> {
14680×
    let repo = open()?;
14690×
    let r = repo.op_revert(op)?;
14700×
    let view = repo.view()?;
14710×
    let names: Vec<String> = r
14720×
        .reverted
14730×
        .iter()
14740×
        .map(|n| {
14750×
            if view.bookmarks.contains_key(n) {
14760×
                ui::bookmark(n)
1477
            } else {
14780×
                format!("{} (removed)", ui::bookmark(n))
1479
            }
14800×
        })
14810×
        .collect();
14820×
    println!(
1483
        "{} operation {} {}",
14840×
        ui::done("Reverted"),
14850×
        ui::hash(r.op.short(12)),
14860×
        ui::dim(r.command.lines().next().unwrap_or(""))
1487
    );
14880×
    println!(
1489
        "  {} {}",
14900×
        ui::note(),
14910×
        ui::dim(format!("as before it: {}", names.join(", ")))
1492
    );
14930×
    if !r.kept.is_empty() {
14940×
        println!(
14950×
            "  {} {}",
14960×
            ui::caution(),
14970×
            ui::warn(format!(
14980×
                "left as they are, having moved again since: {}",
14990×
                r.kept.join(", ")
15000×
            ))
15010×
        );
15020×
    }
15030×
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
15040×
        println!(
15050×
            "  {} {}",
15060×
            ui::note(),
15070×
            ui::dim("the working copy has work of its own: oxy checkout to move it")
15080×
        );
15090×
    }
15100×
    where_now(&repo);
15110×
    Ok(0)
15120×
}
1513
1514
/// Where the working copy and bookmark are now, after a command moved
1515
/// them (as jj says "Working copy now at").
151626×
pub fn where_now(repo: &Repo) {
151726×
    let Ok((_, wc)) = repo.working_copy() else {
15180×
        return;
1519
    };
152026×
    let heads = repo.bookmark_heads().unwrap_or_default();
152126×
    let newest = heads
152226×
        .iter()
152335×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
152426×
        .max_by_key(|(m, _)| m.hlc);
152526×
    println!(
1526
        "  {} {}",
152726×
        ui::dim(format!("{:<13}", "Working copy")),
152826×
        ui::id(wc.change_id.short(8))
1529
    );
153026×
    let tail = match newest {
153126×
        Some((m, _)) => format!(
1532
            ", newest {} {}",
153326×
            ui::id(m.change_id.short(8)),
153426×
            subject_of(&m.message)
1535
        ),
15360×
        None => String::new(),
1537
    };
153826×
    println!(
1539
        "  {} {}: {}{tail}",
154026×
        ui::dim(format!("{:<13}", "Bookmark")),
154126×
        ui::bookmark(&repo.config.bookmark),
154226×
        plural(heads.len(), "head")
1543
    );
154426×
}
1545
15460×
pub fn gc(now: bool) -> Result<i32> {
15470×
    let repo = open()?;
15480×
    let sp = ui::spinner("Packing and pruning…");
15490×
    let r = repo.gc_with(now, &mut |phase| sp.set(&format!("{phase}…")))?;
15500×
    sp.clear();
15510×
    if r.packed.objects > 0 {
15520×
        println!(
15530×
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
15540×
            plural(r.packed.objects, "object"),
15550×
            r.packed.raw_bytes,
15560×
            r.packed.packed_bytes,
15570×
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
15580×
        );
15590×
    }
15600×
    println!(
1561
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
15620×
        plural(r.reachable, "object"),
15630×
        plural(r.pruned.objects, "unreachable object"),
1564
        r.pruned.bytes,
15650×
        if r.pruned.deferred > 0 {
15660×
            format!(
1567
                "; {} deferred by the grace period (use --now)",
15680×
                plural(r.pruned.deferred, "object")
1569
            )
1570
        } else {
15710×
            String::new()
1572
        },
15730×
        if r.merged_packs > 0 {
15740×
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1575
        } else {
15760×
            String::new()
1577
        },
15780×
        plural(repo.store().pack_count(), "pack")
1579
    );
15800×
    Ok(0)
15810×
}
1582
1583
/// `oxy gc --remote NAME`: fold a store remote's bundles into one.
15842×
pub fn gc_remote(name: &str, now: bool) -> Result<i32> {
15852×
    let repo = open()?;
15862×
    let sp = ui::spinner(&format!("Folding {name}'s bundles…"));
15872×
    let r = repo.gc_remote(name, now)?;
15881×
    sp.clear();
15891×
    if r.merged > 0 {
15901×
        println!(
15911×
            "{} {} into one of {} bytes ({})",
15921×
            ui::done("Folded"),
15931×
            plural(r.merged, "bundle"),
15941×
            r.bundle_bytes,
15951×
            plural(r.changes, "change")
15961×
        );
15971×
    } else {
15980×
        println!(
15990×
            "{} {}",
16000×
            ui::note(),
16010×
            ui::dim("nothing to fold: one bundle holds everything")
16020×
        );
16030×
    }
16041×
    println!(
1605
        "  {} {}",
16061×
        ui::note(),
16071×
        ui::dim(format!(
1608
            "removed {}{}",
16091×
            plural(r.deleted, "superseded bundle"),
16101×
            if r.deferred > 0 {
16110×
                format!(
1612
                    "; {} kept for readers that may still fetch them (use --now)",
16130×
                    plural(r.deferred, "bundle")
1614
                )
1615
            } else {
16161×
                String::new()
1617
            }
1618
        ))
1619
    );
16201×
    Ok(0)
16212×
}
1622
1623
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
16240×
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1625
    use oxy_core::repo::Health;
16260×
    let repo = open()?;
16270×
    let sp = ui::spinner(if offline {
16280×
        "Checking…"
1629
    } else {
16300×
        "Checking, and contacting remotes…"
1631
    });
16320×
    let r = repo.doctor(!offline);
16330×
    sp.clear();
16340×
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
16350×
    let word = |h: Health| match h {
16360×
        Health::Ok => "ok",
16370×
        Health::Warn => "warning",
16380×
        Health::Fail => "fail",
16390×
    };
16400×
    if as_json {
16410×
        let checks: Vec<String> = r
16420×
            .checks
16430×
            .iter()
16440×
            .map(|c| {
16450×
                json::obj([
16460×
                    ("area", json::s(&c.area)),
16470×
                    ("health", json::s(word(c.health))),
16480×
                    ("message", json::s(&c.message)),
16490×
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
16500×
                ])
16510×
            })
16520×
            .collect();
16530×
        println!(
1654
            "{}",
16550×
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1656
        );
16570×
        return Ok(code);
16580×
    }
16590×
    let mut last = "";
16600×
    for c in &r.checks {
16610×
        if c.area != last {
16620×
            println!("{}", ui::section(&c.area));
16630×
            last = &c.area;
16640×
        }
16650×
        let mark = match c.health {
16660×
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
16670×
            Health::Warn => ui::caution(),
16680×
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1669
        };
16700×
        println!("  {mark} {}", c.message);
16710×
        if let Some(h) = &c.hint {
16720×
            println!("    {} {}", ui::dim("→"), ui::dim(h));
16730×
        }
1674
    }
16750×
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
16760×
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
16770×
    if fails + warns == 0 {
16780×
        println!("{}", ui::done("Everything looks right."));
16790×
    } else {
16800×
        println!(
1681
            "{} {}, {}.",
16820×
            if fails > 0 {
16830×
                ui::err(ui::glyph("✖", "x"))
1684
            } else {
16850×
                ui::caution()
1686
            },
16870×
            plural(fails, "problem"),
16880×
            plural(warns, "warning")
1689
        );
1690
    }
16910×
    Ok(code)
16920×
}
1693
1694
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
16950×
pub fn fsck(as_json: bool) -> Result<i32> {
1696
    use oxy_core::repo::Severity;
16970×
    let repo = open()?;
16980×
    let sp = ui::spinner("Checking every object…");
16990×
    let r = repo.fsck()?;
17000×
    sp.clear();
17010×
    let code = if r.errors() > 0 { 1 } else { 0 };
17020×
    if as_json {
17030×
        let problems: Vec<String> = r
17040×
            .problems
17050×
            .iter()
17060×
            .map(|p| {
17070×
                json::obj([
1708
                    (
1709
                        "severity",
17100×
                        json::s(match p.severity {
17110×
                            Severity::Error => "error",
17120×
                            Severity::Warning => "warning",
1713
                        }),
1714
                    ),
1715
                    (
17160×
                        "object",
17170×
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1718
                    ),
17190×
                    ("what", json::s(&p.what)),
1720
                ])
17210×
            })
17220×
            .collect();
17230×
        println!(
1724
            "{}",
17250×
            json::obj([
17260×
                ("ok", json::b(code == 0)),
17270×
                ("objects", json::n(r.objects)),
17280×
                ("ops", json::n(r.ops)),
17290×
                ("changes", json::n(r.changes)),
17300×
                ("signed", json::n(r.signed)),
17310×
                ("unsigned", json::n(r.unsigned)),
17320×
                ("checkpoints", json::n(r.checkpoints)),
17330×
                ("attestations", json::n(r.attestations)),
17340×
                ("errors", json::n(r.errors())),
17350×
                ("warnings", json::n(r.warnings())),
17360×
                ("problems", json::arr(problems)),
17370×
            ])
1738
        );
17390×
        return Ok(code);
17400×
    }
17410×
    println!(
1742
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
17430×
        plural(r.objects, "object"),
17440×
        plural(r.ops, "operation"),
17450×
        plural(r.changes, "change"),
1746
        r.signed,
1747
        r.unsigned,
17480×
        plural(r.checkpoints, "checkpoint"),
17490×
        plural(r.attestations, "attestation"),
1750
    );
17510×
    for p in &r.problems {
17520×
        let obj = p
17530×
            .object
17540×
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
17550×
            .unwrap_or_default();
17560×
        match p.severity {
17570×
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
17580×
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1759
        }
1760
    }
17610×
    if r.problems.is_empty() {
17620×
        println!("{}", ui::done("No problems found."));
17630×
    } else if code == 0 {
17640×
        println!(
17650×
            "{}",
17660×
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
17670×
        );
17680×
    } else {
17690×
        println!(
17700×
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
17710×
            ui::err(ui::glyph("✖", "x")),
17720×
            plural(r.errors(), "error"),
17730×
            plural(r.warnings(), "warning")
17740×
        );
17750×
    }
17760×
    Ok(code)
17770×
}
1778
1779
/// The head the working copy sits on, for commands that default to it. With
1780
/// several heads beneath the working copy, the most recently made one is
1781
/// chosen and announced.
17820×
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
17830×
    let snap = repo.snapshot_status("oxy")?;
17840×
    let base = snap.base.maximal(&snap.wc.deps);
17850×
    match base.as_slice() {
17860×
        [] => anyhow::bail!("the working copy sits on no change yet"),
17870×
        [h] => Ok(*h),
17880×
        many => {
17890×
            let latest = many
17900×
                .iter()
17910×
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
17920×
                .copied()
17930×
                .unwrap();
17940×
            let c = repo.store().get_change(&latest)?;
17950×
            println!(
1796
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
17970×
                short_id(&c),
17980×
                latest.short(12),
17990×
                many.len()
1800
            );
18010×
            Ok(latest)
1802
        }
1803
    }
18040×
}
1805
1806
/// `oxy describe` without -m: the working copy's name for a build.
18074×
pub fn describe_name(as_json: bool) -> Result<i32> {
18084×
    let repo = open()?;
18094×
    let d = repo.describe_working_copy()?;
18104×
    if as_json {
18113×
        println!(
1812
            "{}",
18133×
            json::obj([
18143×
                ("describe", json::s(&d.line())),
18153×
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
18163×
                ("distance", json::n(d.distance)),
18173×
                ("bookmark", json::s(&d.bookmark)),
18183×
                ("change", json::s(&d.change.to_hex())),
18193×
                ("hash", json::s(&d.hash.to_hex())),
18203×
                ("dirty", json::b(d.dirty)),
1821
            ])
1822
        );
18231×
    } else {
18241×
        println!("{}", d.line());
18251×
    }
18264×
    Ok(0)
18274×
}
1828
18290×
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
18300×
    let repo = open()?;
18310×
    let h = match change {
18320×
        Some(c) => repo.resolve_change(c)?,
18330×
        None => current_head(&repo)?,
1834
    };
18350×
    let new = repo.describe(&h, message)?;
18360×
    let c = repo.store().get_change_meta(&new)?;
18370×
    println!(
1838
        "{} {} {}  {}",
18390×
        ui::done("Described"),
18400×
        ui::id(c.change_id.short(8)),
18410×
        ui::hash(format!("#{}", new.short(12))),
18420×
        ui::subject(subject_of(message))
1843
    );
18440×
    Ok(0)
18450×
}
1846
18470×
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
18480×
    let repo = open()?;
18490×
    let new = match into {
18500×
        Some(spec) => {
18510×
            let target = repo.resolve_change(spec)?;
18520×
            repo.amend_into(&target, message)?
1853
        }
18540×
        None => repo.amend(message)?,
1855
    };
18560×
    let c = repo.store().get_change_meta(&new)?;
18570×
    println!(
1858
        "{} {} {}  {}",
18590×
        ui::done("Amended"),
18600×
        ui::id(c.change_id.short(8)),
18610×
        ui::hash(format!("#{}", new.short(12))),
18620×
        ui::subject(subject_of(&c.message))
1863
    );
18640×
    where_now(&repo);
18650×
    Ok(0)
18660×
}
1867
18680×
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
18690×
    let repo = open()?;
18700×
    let Some(r) = revset else {
18710×
        let h = repo.resolve_change(change.unwrap_or_default())?;
18720×
        abandon_one(&repo, h)?;
18730×
        where_now(&repo);
18740×
        return Ok(0);
1875
    };
1876
    // A revset: say what it selects, refuse an empty set, ask above a few.
18770×
    let selected = repo.revset(r)?;
18780×
    let wc = repo.working_copy().ok().map(|(h, _)| h);
18790×
    let hashes: Vec<ChangeHash> = selected
18800×
        .hashes
18810×
        .iter()
18820×
        .copied()
18830×
        .filter(|h| Some(*h) != wc)
18840×
        .collect();
18850×
    if hashes.is_empty() {
18860×
        anyhow::bail!("{r:?} selects no change to abandon");
18870×
    }
18880×
    println!(
1889
        "{} {} selects {}:",
18900×
        ui::section("abandon"),
18910×
        ui::id(r),
18920×
        plural(hashes.len(), "change")
1893
    );
18940×
    for h in &hashes {
18950×
        if let Some(m) = selected.metas.get(h) {
18960×
            println!(
18970×
                "  {} {}  {}",
18980×
                ui::id(m.change_id.short(8)),
18990×
                ui::hash(format!("#{}", h.short(12))),
19000×
                subject_of(&m.message)
19010×
            );
19020×
        }
1903
    }
1904
    const ASK_ABOVE: usize = 5;
19050×
    if hashes.len() > ASK_ABOVE && !yes {
19060×
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
19070×
    }
1908
    // Newest first: abandoning a change rewrites what depends on it, so a
1909
    // later member is found again by its ChangeId.
19100×
    let mut done = 0;
19110×
    for h in &hashes {
19120×
        let Some(m) = selected.metas.get(h) else {
19130×
            continue;
1914
        };
19150×
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
19160×
            Ok(h) => h,
19170×
            Err(_) => continue,
1918
        };
19190×
        abandon_one(&repo, now)?;
19200×
        done += 1;
1921
    }
19220×
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
19230×
    where_now(&repo);
19240×
    Ok(0)
19250×
}
1926
19270×
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
19280×
    let c = repo.store().get_change_meta(&h)?;
19290×
    let notes = repo.abandon(&h)?;
19300×
    println!(
1931
        "{} {} {}  {}",
19320×
        ui::done("Abandoned"),
19330×
        ui::id(c.change_id.short(8)),
19340×
        ui::hash(format!("#{}", h.short(12))),
19350×
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
1936
    );
19370×
    for n in notes {
19380×
        println!("  {} {n}", ui::note());
19390×
    }
19400×
    Ok(())
19410×
}
1942
19430×
pub fn checkpoint() -> Result<i32> {
19440×
    let repo = open()?;
19450×
    let sp = ui::spinner("Writing checkpoint…");
19460×
    let (r, changes, bytes) = repo.checkpoint()?;
19470×
    sp.done(&format!(
19480×
        "{} {} of {} ({} bytes) for {}",
19490×
        ui::done("Checkpoint"),
19500×
        ui::hash(format!("#{}", r.short(12))),
19510×
        plural(changes, "change"),
19520×
        bytes,
19530×
        ui::id(&repo.config.bookmark)
19540×
    ));
19550×
    Ok(0)
19560×
}
1957
1958
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
19590×
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
19600×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
19610×
        return Ok(1);
1962
    };
19630×
    let info = repo.quick_status()?;
19640×
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
19650×
        oxy_core::repo::GLYPH_PROMPT_FORMAT
1966
    } else {
19670×
        format
1968
    };
19690×
    let line = match color {
19700×
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
19710×
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
19720×
        Some(_) => info.format_colored(fmt, ("", "")),
19730×
        None => info.format(fmt),
1974
    };
19750×
    println!("{line}");
19760×
    Ok(0)
19770×
}
1978
19790×
pub fn sparse(paths: &[String]) -> Result<i32> {
19800×
    let mut repo = open()?;
19810×
    if paths.is_empty() {
19820×
        if repo.config.sparse_paths.is_empty() {
19830×
            println!("No sparse filter: the whole tree is materialized.");
19840×
        } else {
19850×
            println!("{}", ui::heading("Sparse filter"));
19860×
            for p in &repo.config.sparse_paths {
19870×
                println!("  {}", ui::path(p));
19880×
            }
1989
        }
19900×
        return Ok(0);
19910×
    }
19920×
    let snap = repo.snapshot("oxy sparse")?;
19930×
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
19940×
        anyhow::bail!(
1995
            "the working copy has changes; commit them before changing the sparse filter"
1996
        );
19970×
    }
19980×
    repo.config.set("filter.paths", &paths.join(","))?;
19990×
    repo.save_config()?;
20000×
    let heads = repo.bookmark_heads()?;
20010×
    let sp = ui::spinner("Re-checking out with the new filter…");
20020×
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
20030×
    sp.done(&format!(
20040×
        "{} {}: {} written, {} removed",
20050×
        ui::done("Sparse filter set to"),
20060×
        ui::path(paths.join(",")),
20070×
        plural(r.written, "file"),
20080×
        r.removed
20090×
    ));
20100×
    Ok(0)
20110×
}
2012
20132×
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
20142×
    let repo = open()?;
20152×
    repo.snapshot_status("oxy tag")?;
20162×
    let heads = if changes.is_empty() {
20172×
        repo.bookmark_heads()?
2018
    } else {
20190×
        let mut heads = Vec::new();
20200×
        for c in changes {
20210×
            heads.extend(repo.resolve_heads(c)?);
2022
        }
20230×
        heads
2024
    };
20252×
    let t = repo.tag_create(name, &heads, message)?;
20262×
    println!(
2027
        "{} {} {} {} ({}){}",
20282×
        ui::done("Tagged"),
20292×
        ui::bookmark(&t.name),
20302×
        ui::dim(ui::glyph("→", "->")),
20312×
        ui::hash(format!("#{}", t.state.short(12))),
20322×
        plural(t.heads.len(), "head"),
20332×
        t.signer
20342×
            .map(|s| format!(", signed by {s}"))
20352×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2036
    );
20372×
    Ok(0)
20382×
}
2039
20401×
pub fn tag_list(as_json: bool) -> Result<i32> {
20411×
    let repo = open()?;
20421×
    let tags = repo.tags()?;
20431×
    if as_json {
20441×
        println!(
2045
            "{}",
20461×
            json::arr(tags.iter().map(|t| {
20471×
                json::obj([
20481×
                    ("name", json::s(&t.name)),
20491×
                    ("state", json::s(&t.state.to_hex())),
20501×
                    ("heads", json::hashes(&t.heads)),
20511×
                    ("message", json::s(&t.message)),
2052
                    (
20531×
                        "signer",
20541×
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2055
                    ),
2056
                ])
20571×
            }))
2058
        );
20591×
        return Ok(0);
20600×
    }
20610×
    if tags.is_empty() {
20620×
        println!("{}", ui::dim("No tags."));
20630×
    }
20640×
    for t in tags {
20650×
        println!(
2066
            "{} {} {}{}{}{}",
20670×
            ui::ok(ui::glyph("⚑", "#")),
20680×
            ui::bookmark(&t.name),
2069
            // The heads, as `oxy log` shows changes, not the state hash.
20700×
            ui::hash(
20710×
                t.heads
20720×
                    .iter()
20730×
                    .map(|h| format!("#{}", h.short(12)))
20740×
                    .collect::<Vec<_>>()
20750×
                    .join(" ")
2076
            ),
20770×
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
20780×
            if t.message.is_empty() {
20790×
                String::new()
2080
            } else {
20810×
                format!("  {}", ui::subject(subject_of(&t.message)))
2082
            },
20830×
            t.signer
20840×
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
20850×
                .unwrap_or_default()
2086
        );
2087
    }
20880×
    Ok(0)
20891×
}
2090
2091
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2092
/// and workspace add take as "be on this bookmark" (oxygen#60).
20930×
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
20940×
    Ok(repo.view()?.bookmarks.contains_key(name)
20950×
        || repo
20960×
            .remote_only_bookmarks()?
20970×
            .iter()
20980×
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
20990×
}
2100
21010×
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
21020×
    let repo = open()?;
2103
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2104
    // this workspace's bookmark with that one's files.
21050×
    if let [name] = changes {
21060×
        if names_bookmark(&repo, name)? {
21070×
            let (local, _) = repo.local_bookmark_for(name)?;
21080×
            let heads = repo.resolve_heads(&local)?;
21090×
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
21100×
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
21110×
            sp.done(&format!(
21120×
                "{} {} (workspace {}) on {}",
21130×
                ui::done("Workspace created at"),
21140×
                ui::path(ws.root().display()),
21150×
                ui::id(ws.workspace().short(8)),
21160×
                ui::bookmark(&local)
21170×
            ));
21180×
            return Ok(0);
21190×
        }
21200×
    }
21210×
    let heads = if changes.is_empty() {
21220×
        None
2123
    } else {
21240×
        let mut heads = Vec::new();
21250×
        for c in changes {
21260×
            heads.extend(repo.resolve_heads(c)?);
2127
        }
21280×
        Some(heads)
2129
    };
21300×
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
21310×
    let ws = repo.workspace_add(path, heads.as_deref())?;
21320×
    sp.done(&format!(
21330×
        "{} {} (workspace {})",
21340×
        ui::done("Workspace created at"),
21350×
        ui::path(ws.root().display()),
21360×
        ui::id(ws.workspace().short(8))
21370×
    ));
21380×
    Ok(0)
21390×
}
2140
21411×
pub fn workspace_list(as_json: bool) -> Result<i32> {
21421×
    let repo = open()?;
21431×
    if as_json {
21441×
        println!(
2145
            "{}",
21461×
            json::arr(repo.workspaces()?.iter().map(|w| {
21471×
                json::obj([
21481×
                    ("id", json::s(&w.id.to_hex())),
21491×
                    ("path", json::s(&w.path.to_string_lossy())),
21501×
                    ("current", json::b(w.current)),
2151
                    (
21521×
                        "working_copy",
21531×
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2154
                    ),
2155
                ])
21561×
            }))
2157
        );
21581×
        return Ok(0);
21590×
    }
21600×
    for w in repo.workspaces()? {
21610×
        println!(
2162
            "{} {} {}{}",
21630×
            if w.current {
21640×
                ui::ok(ui::glyph("●", "*"))
2165
            } else {
21660×
                ui::dim(ui::glyph("○", "o"))
2167
            },
21680×
            ui::id(w.id.short(8)),
21690×
            ui::path(w.path.display()),
21700×
            w.working_copy
21710×
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
21720×
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2173
        );
2174
    }
21750×
    Ok(0)
21761×
}
2177
21780×
pub fn workspace_forget(spec: &str) -> Result<i32> {
21790×
    let repo = open()?;
21800×
    let all = repo.workspaces()?;
21810×
    let target = std::fs::canonicalize(spec).ok();
21820×
    let matches: Vec<_> = all
21830×
        .iter()
21840×
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
21850×
        .collect();
21860×
    let w = match matches.as_slice() {
21870×
        [w] => *w,
21880×
        [] => anyhow::bail!("no workspace matches {spec:?}"),
21890×
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2190
    };
21910×
    repo.workspace_forget(&w.id)?;
21920×
    println!(
2193
        "{} workspace {} at {}; its files were left in place.",
21940×
        ui::done("Forgot"),
21950×
        ui::id(w.id.short(8)),
21960×
        ui::path(w.path.display())
2197
    );
21980×
    Ok(0)
21990×
}
2200
22010×
pub fn lock(path: &str) -> Result<i32> {
22020×
    let repo = open()?;
22030×
    repo.lock_path(path)?;
22040×
    println!(
2205
        "{} {} {}",
22060×
        ui::done("Locked"),
22070×
        ui::path(path),
22080×
        ui::dim("(advisory, local)")
2209
    );
22100×
    Ok(0)
22110×
}
2212
22130×
pub fn unlock(path: &str) -> Result<i32> {
22140×
    let repo = open()?;
22150×
    repo.unlock_path(path)?;
22160×
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
22170×
    Ok(0)
22180×
}
2219
22200×
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
22210×
    let repo = open()?;
22220×
    let h = repo.resolve_change(change)?;
22230×
    let (h1, h2) = repo.split(&h, paths)?;
22240×
    let c1 = repo.store().get_change_meta(&h1)?;
22250×
    let c2 = repo.store().get_change_meta(&h2)?;
22260×
    println!(
2227
        "{} into {} {} and {} {}",
22280×
        ui::done("Split"),
22290×
        ui::id(c1.change_id.short(8)),
22300×
        ui::hash(format!("#{}", h1.short(12))),
22310×
        ui::id(c2.change_id.short(8)),
22320×
        ui::hash(format!("#{}", h2.short(12)))
2233
    );
22340×
    Ok(0)
22350×
}
2236
22375×
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
22385×
    let mut heads = Vec::new();
22395×
    for c in changes {
22405×
        heads.extend(repo.resolve_heads(c)?);
2241
    }
22425×
    Ok(heads)
22435×
}
2244
22455×
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
22465×
    let repo = open()?;
22475×
    repo.snapshot_status("oxy bookmark create")?;
22485×
    let heads = if changes.is_empty() {
22492×
        None
2250
    } else {
22513×
        let named = heads_from(&repo, changes)?;
22523×
        let (_, wc) = repo.working_copy()?;
22533×
        let gap = repo.state_gap(&wc.deps, &named)?;
22543×
        if upto {
22551×
            Some(gap.upto)
22562×
        } else if only || gap.earlier.is_empty() {
22571×
            Some(named)
2258
        } else {
22591×
            anyhow::bail!(
2260
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2261
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2262
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2263
                 or --only for just {0} and what it depends on.",
22641×
                changes.join(" "),
22651×
                plural(gap.earlier.len(), "change"),
22661×
                listed_changes(&repo, &gap.earlier)
2267
            );
2268
        }
2269
    };
22704×
    let heads = repo.bookmark_create(name, heads.as_deref())?;
22714×
    println!(
2272
        "{} bookmark {} {} {}",
22734×
        ui::done("Created"),
22744×
        ui::bookmark(name),
22754×
        ui::dim(ui::glyph("→", "->")),
22764×
        ui::dim(plural(heads.len(), "head"))
2277
    );
22784×
    println!(
2279
        "  {} {}",
22804×
        ui::note(),
22814×
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2282
    );
22834×
    Ok(0)
22845×
}
2285
2286
/// Up to five changes, newest last, as `  #hash subject` lines.
22872×
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
22882×
    let shown = changes.len().min(5);
22892×
    let mut lines: Vec<String> = changes[changes.len() - shown..]
22902×
        .iter()
22912×
        .map(|h| {
22922×
            let subject = repo
22932×
                .store()
22942×
                .get_change(h)
22952×
                .map(|c| subject_of(&c.message).to_string())
22962×
                .unwrap_or_default();
22972×
            format!("  #{} {subject}", h.short(12))
22982×
        })
22992×
        .collect();
23002×
    if changes.len() > shown {
23010×
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
23022×
    }
23032×
    lines.join("\n")
23042×
}
2305
23062×
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
23072×
    let repo = open()?;
23082×
    repo.snapshot_status("oxy bookmark set")?;
23092×
    let named = heads_from(&repo, changes)?;
2310
    // What the bookmark holds now and the new heads would leave out.
23112×
    let current = repo
23122×
        .bookmarks()?
23132×
        .into_iter()
23142×
        .find(|b| b.name == name)
23152×
        .map(|b| b.heads)
23162×
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
23172×
    let gap = repo.state_gap(&current, &named)?;
23182×
    let heads = if upto {
23191×
        gap.upto
23201×
    } else if only || gap.earlier.is_empty() {
23210×
        named
2322
    } else {
23231×
        anyhow::bail!(
2324
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2325
             A state is its heads and what they depend on, not everything recorded before them.\n\
2326
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2327
             or --only for just {0} and what it depends on.",
23281×
            changes.join(" "),
23291×
            plural(gap.earlier.len(), "change"),
23301×
            listed_changes(&repo, &gap.earlier)
2331
        );
2332
    };
23331×
    let heads = repo.bookmark_set(name, &heads)?;
23341×
    println!(
2335
        "{} bookmark {} {} {}",
23361×
        ui::done("Moved"),
23371×
        ui::bookmark(name),
23381×
        ui::dim(ui::glyph("→", "->")),
23391×
        ui::dim(plural(heads.len(), "head"))
2340
    );
23411×
    Ok(0)
23422×
}
2343
23440×
pub fn bookmark_delete(name: &str) -> Result<i32> {
23450×
    let repo = open()?;
23460×
    repo.bookmark_delete(name)?;
23470×
    println!(
2348
        "{} bookmark {} {}",
23490×
        ui::done("Deleted"),
23500×
        ui::bookmark(name),
23510×
        ui::dim("(its changes stay until unreachable)")
2352
    );
23530×
    Ok(0)
23540×
}
2355
23564×
pub fn bookmark_list(all: bool, as_json: bool) -> Result<i32> {
23574×
    let repo = open()?;
23584×
    let remote_only = repo.remote_only_bookmarks()?;
23594×
    if as_json {
23604×
        let mut items: Vec<String> = repo
23614×
            .bookmarks()?
23624×
            .into_iter()
23639×
            .map(|b| {
23649×
                json::obj([
23659×
                    ("name", json::s(&b.name)),
23669×
                    ("heads", json::hashes(&b.heads)),
23679×
                    ("current", json::b(b.current)),
23689×
                    ("ahead", json::opt(b.ahead, json::n)),
23699×
                    ("behind", json::opt(b.behind, json::n)),
23709×
                ])
23719×
            })
23724×
            .collect();
23734×
        if all {
23740×
            items.extend(remote_only.iter().map(|b| {
23750×
                json::obj([
23760×
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
23770×
                    ("heads", json::hashes(&b.heads)),
23780×
                    ("current", json::b(false)),
23790×
                    ("ahead", "null".into()),
23800×
                    ("behind", "null".into()),
23810×
                    ("remote", json::s(&b.remote)),
23820×
                ])
23830×
            }));
23844×
        }
23854×
        println!("{}", json::arr(items));
23864×
        return Ok(0);
23870×
    }
23880×
    for b in repo.bookmarks()? {
23890×
        let mark = if b.current {
23900×
            ui::ok(ui::glyph("●", "*"))
2391
        } else {
23920×
            ui::dim(ui::glyph("○", "o"))
2393
        };
23940×
        let mut tail = String::new();
23950×
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
23960×
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
23970×
        }
23980×
        if let Some(n) = b.behind.filter(|n| *n > 0) {
23990×
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
24000×
        }
24010×
        let head = b
24020×
            .heads
24030×
            .first()
24040×
            .map(|h| {
24050×
                repo.store()
24060×
                    .get_change(h)
24070×
                    .map(|c| ui::subject(subject_of(&c.message)))
24080×
                    .unwrap_or_default()
24090×
            })
24100×
            .unwrap_or_else(|| ui::dim("(empty)"));
24110×
        println!(
2412
            "{mark} {}{}{}{tail}  {head}",
24130×
            ui::bookmark(&b.name),
24140×
            ui::sep(),
24150×
            ui::dim(plural(b.heads.len(), "head"))
2416
        );
2417
    }
24180×
    if remote_only.is_empty() {
24190×
        return Ok(0);
24200×
    }
24210×
    if !all {
24220×
        println!(
2423
            "{}",
24240×
            ui::dim(format!(
2425
                "  and {} only on a remote: oxy bookmark list --all",
24260×
                plural(remote_only.len(), "bookmark")
2427
            ))
2428
        );
24290×
        return Ok(0);
24300×
    }
24310×
    for b in &remote_only {
24320×
        println!(
24330×
            "{} {}{}{}",
24340×
            ui::dim(ui::glyph("◌", ".")),
24350×
            ui::dim(format!("{}/{}", b.remote, b.name)),
24360×
            ui::sep(),
24370×
            ui::dim(plural(b.heads.len(), "head"))
24380×
        );
24390×
    }
24400×
    println!(
2441
        "  {} {}",
24420×
        ui::note(),
24430×
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2444
    );
24450×
    Ok(0)
24464×
}
2447
24482×
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
24492×
    let mut repo = open()?;
24502×
    let from = repo.config.bookmark.clone();
24512×
    let (local, created_from) = repo.local_bookmark_for(name)?;
24522×
    if let Some(remote) = created_from {
24530×
        println!(
24540×
            "{} {} from {}",
24550×
            ui::done("Created"),
24560×
            ui::bookmark(&local),
24570×
            ui::dim(format!("{remote}/{local}"))
24580×
        );
24592×
    }
24602×
    let name = local.as_str();
24612×
    let sp = ui::spinner(&format!("Switching to {name}…"));
24622×
    let (r, carried) = if carry {
24630×
        repo.bookmark_switch_carry(name)?
2464
    } else {
24652×
        (repo.bookmark_switch(name, discard)?, vec![])
2466
    };
24672×
    sp.done(&format!(
2468
        "{} to {}: {} written, {} removed{}",
24692×
        ui::done("Switched"),
24702×
        ui::bookmark(name),
24712×
        plural(r.written, "file"),
2472
        r.removed,
24732×
        if carried.is_empty() {
24742×
            String::new()
2475
        } else {
24760×
            format!("; carried {}", plural(carried.len(), "changed path"))
2477
        }
2478
    ));
24792×
    if r.conflicted {
24800×
        println!(
24810×
            "  {} {}",
24820×
            ui::caution(),
24830×
            ui::warn("this state has conflicts; see oxy status")
24840×
        );
24852×
    }
2486
    // Say when the new state leaves out work the old one had: a state is
2487
    // its heads and what they depend on, which can be far less than a Git
2488
    // user expects.
24892×
    if r.lacks > 0 {
24901×
        println!(
24911×
            "  {} {}",
24921×
            ui::note(),
24931×
            ui::dim(format!(
24941×
                "{name} lacks {} that {from} has",
24951×
                plural(r.lacks, "change")
24961×
            ))
24971×
        );
24981×
    }
24992×
    super::sync::subrepos_behind(&repo);
25002×
    where_now(&repo);
25012×
    Ok(0)
25022×
}
2503
25040×
pub fn merge(bookmark: &str) -> Result<i32> {
25050×
    let repo = open()?;
25060×
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
25070×
    let r = repo.merge(bookmark)?;
25080×
    if !r.changed {
25090×
        sp.done(&format!(
25100×
            "{} {}",
25110×
            ui::ok(ui::glyph("✔", "*")),
25120×
            ui::dim(format!(
25130×
                "{} already contains {bookmark}",
25140×
                repo.config.bookmark
25150×
            ))
25160×
        ));
25170×
        return Ok(0);
25180×
    }
25190×
    sp.done(&format!(
2520
        "{} {} into {}: now {}{}",
25210×
        ui::done("Merged"),
25220×
        ui::bookmark(bookmark),
25230×
        ui::bookmark(&repo.config.bookmark),
25240×
        plural(r.heads.len(), "head"),
25250×
        ui::dim(if r.checked_out {
25260×
            "; working copy updated"
2527
        } else {
25280×
            "; run oxy checkout to update the working copy"
2529
        })
2530
    ));
25310×
    let snap = repo.snapshot("oxy merge")?;
25320×
    if snap.base_snapshot.is_conflicted() {
25330×
        println!(
25340×
            "  {} {}",
25350×
            ui::caution(),
25360×
            ui::warn("the result has conflicts; see oxy status")
25370×
        );
25380×
    }
25390×
    where_now(&repo);
25400×
    Ok(0)
25410×
}
2542
25430×
pub fn squash(change: &str, into: &str) -> Result<i32> {
25440×
    let repo = open()?;
25450×
    let c = repo.resolve_change(change)?;
25460×
    let d = repo.resolve_change(into)?;
25470×
    let sp = ui::spinner("Squashing…");
25480×
    let h = repo.squash(&c, &d)?;
25490×
    let new = repo.store().get_change_meta(&h)?;
25500×
    sp.done(&format!(
25510×
        "{} into {} {}  {}",
25520×
        ui::done("Squashed"),
25530×
        ui::id(new.change_id.short(8)),
25540×
        ui::hash(format!("#{}", h.short(12))),
25550×
        ui::subject(subject_of(&new.message))
25560×
    ));
25570×
    Ok(0)
25580×
}
2559
25600×
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
25610×
    let repo = open()?;
25620×
    let c = repo.resolve_change(change)?;
25630×
    let mut heads = Vec::new();
25640×
    for o in onto {
25650×
        heads.extend(repo.resolve_heads(o)?);
2566
    }
25670×
    let sp = ui::spinner("Rebasing…");
25680×
    let h = match repo.rebase(&c, &heads) {
25690×
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
25700×
            let r = repo.rebase_into_working_copy(&c, &heads)?;
25710×
            sp.done(&format!(
25720×
                "{} {} into {}: now {}",
25730×
                ui::done("Merged"),
25740×
                onto.join(" "),
25750×
                ui::bookmark(&repo.config.bookmark),
25760×
                plural(r.heads.len(), "head"),
25770×
            ));
25780×
            if r.checked_out {
25790×
                println!(
25800×
                    "  {} {}",
25810×
                    ui::caution(),
25820×
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
25830×
                );
25840×
            } else {
25850×
                println!(
25860×
                    "  {} {}",
25870×
                    ui::caution(),
25880×
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
25890×
                );
25900×
            }
25910×
            where_now(&repo);
25920×
            return Ok(0);
2593
        }
25940×
        other => other?,
2595
    };
25960×
    let new = repo.store().get_change_meta(&h)?;
25970×
    sp.done(&format!(
25980×
        "{} {} {}  {}",
25990×
        ui::done("Rebased"),
26000×
        ui::id(new.change_id.short(8)),
26010×
        ui::hash(format!("#{}", h.short(12))),
26020×
        ui::dim(format!(
26030×
            "now depends on {}",
26040×
            plural(new.deps.len(), "change")
26050×
        ))
26060×
    ));
26070×
    where_now(&repo);
26080×
    Ok(0)
26090×
}