OXYGENHUB

Coverage / src/cli/workspace.rs 42.0%

1089 of 2592 lines run, 108 of 375 functions · run #427 on main · run missed

1
//! Commands that act on the local repository and working copy.
2
3
use super::format::{
4
    author_name, awaits_seal, deps_line, deps_of, plural, short_id, signature_line,
5
    signature_mark_of, 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
1719×
pub fn init(path: Option<PathBuf>, bare: bool, store: Option<&str>) -> Result<i32> {
1819×
    let path = path.unwrap_or(std::env::current_dir()?);
1919×
    let repo = Repo::init_new(&path, bare, store)?;
2019×
    println!(
21
        "{} {}oxy repository in {}",
2219×
        ui::done("Initialized"),
2319×
        if bare { "bare " } else { "" },
2419×
        ui::path(repo.root().display())
25
    );
2619×
    println!(
27
        "{}",
2819×
        ui::kv("bookmark", ui::bookmark(&repo.config.bookmark))
29
    );
3019×
    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×
        );
4219×
    }
4319×
    println!(
44
        "{}",
4519×
        ui::kv(
4619×
            "author",
4719×
            format!(
48
                "{} <{}>",
4919×
                ui::author(&repo.config.author_name),
50
                repo.config.author_email
51
            )
52
        )
53
    );
5419×
    Ok(0)
5519×
}
56
573×
fn status_tag(s: ChangeStatus) -> &'static str {
583×
    match s {
591×
        ChangeStatus::Added => "A",
601×
        ChangeStatus::Modified => "M",
610×
        ChangeStatus::Removed => "D",
620×
        ChangeStatus::Renamed => "R",
631×
        ChangeStatus::ModeChanged => "X",
640×
        ChangeStatus::ConflictEdited => "C!",
650×
        ChangeStatus::Resolved => "V",
66
    }
673×
}
68
69
/// New untracked files left out of the snapshot for their size (oxygen#98):
70
/// named, with how to keep them out quietly or take them in.
7146×
fn print_skipped_large(repo: &Repo) {
7246×
    let skipped = repo.skipped_large();
7346×
    if skipped.is_empty() {
7446×
        return;
750×
    }
760×
    let size = |n: u64| {
770×
        if n >= 1 << 30 {
780×
            format!("{:.1} GiB", n as f64 / (1u64 << 30) as f64)
79
        } else {
800×
            format!("{:.0} MiB", n as f64 / (1u64 << 20) as f64)
81
        }
820×
    };
830×
    println!();
840×
    println!(
85
        "{} {}",
860×
        ui::section(ui::warn("Not tracked")),
870×
        ui::dim(format!("new files over {}", size(repo.config.max_new_file)))
88
    );
890×
    for (p, n) in &skipped {
900×
        println!("  {} {}  {}", ui::caution(), ui::path(p), ui::dim(size(*n)));
910×
    }
920×
    println!(
93
        "  {} {}",
940×
        ui::note(),
950×
        ui::dim(
96
            "to leave them out quietly, list them in .oxyignore; to track one, \
97
             raise snapshot.max-new-file-size (oxy config snapshot.max-new-file-size 2G)"
98
        )
99
    );
10046×
}
101
102
/// Name what a checkout removed from the working copy (oxygen#102): a
103
/// switch to a bookmark lacking files takes them off disk, which an
104
/// editor open on the tree notices before a person reading a count does.
1053×
fn print_removed(r: &oxy_core::repo::CheckoutReport) {
1063×
    if r.removed == 0 {
1072×
        return;
1081×
    }
1091×
    let more = r.removed.saturating_sub(r.removed_paths.len());
1101×
    let names = r.removed_paths.join(", ");
1111×
    let tail = if more > 0 {
1120×
        format!(" and {more} more")
113
    } else {
1141×
        String::new()
115
    };
1161×
    let lead = if r.removed >= 20 {
1170×
        ui::caution()
118
    } else {
1191×
        ui::note()
120
    };
1211×
    println!(
122
        "  {} {}",
123
        lead,
1241×
        ui::dim(format!(
125
            "removed from disk (the bookmark does not have them): {names}{tail}"
126
        ))
127
    );
1283×
}
129
130
/// Name the work a switch carried (oxygen#120): it is still on disk, as it
131
/// was, on the new bookmark.
1323×
fn print_carried(paths: &[String]) {
1333×
    if paths.is_empty() {
1343×
        return;
1350×
    }
1360×
    let shown: Vec<&str> = paths.iter().take(10).map(String::as_str).collect();
1370×
    let more = paths.len().saturating_sub(shown.len());
1380×
    println!(
139
        "  {} {}",
1400×
        ui::note(),
1410×
        ui::dim(format!(
142
            "carried, as they were: {}{}",
1430×
            shown.join(", "),
1440×
            if more > 0 {
1450×
                format!(" and {more} more")
146
            } else {
1470×
                String::new()
148
            }
149
        ))
150
    );
1513×
}
152
153
/// Folders holding a repository of their own, which oxy leaves out (oxygen#43):
154
/// named, with how to track them.
15546×
fn print_untracked_nested(repo: &Repo, nested: &[String]) {
15646×
    if nested.is_empty() {
15744×
        return;
1582×
    }
1592×
    println!();
1602×
    println!(
161
        "{} {}",
1622×
        ui::section(ui::warn("Not tracked")),
1632×
        ui::dim("folders holding a repository of their own")
164
    );
1652×
    for p in nested {
1662×
        let kind = if repo.root().join(p).join(".git").exists() {
1672×
            "Git"
168
        } else {
1690×
            "Oxygen"
170
        };
1712×
        println!(
172
            "  {} {}  {}",
1732×
            ui::caution(),
1742×
            ui::path(format!("{p}/")),
1752×
            ui::dim(format!("a nested {kind} repository"))
176
        );
177
    }
1782×
    println!(
179
        "  {} {}",
1802×
        ui::note(),
1812×
        ui::dim(
182
            "to track one's files, remove its .git (or .oxy); to keep it a repository of its own, \
183
             oxy submodule add URL PATH; to leave it out quietly, list it in .oxyignore"
184
        )
185
    );
18646×
}
187
188
/// The working copy's changed paths, or that it is clean.
18910×
fn print_statuses(statuses: &[oxy_core::repo::PathStatus]) {
19010×
    if statuses.is_empty() {
1917×
        println!(
192
            "  {} {}",
1937×
            ui::ok(ui::glyph("✔", "*")),
1947×
            ui::dim("nothing to commit, working copy clean")
195
        );
1967×
        return;
1973×
    }
1983×
    println!();
1993×
    for s in statuses {
2003×
        println!(
2013×
            "  {} {}",
2023×
            ui::status_mark(status_tag(s.status)),
2033×
            ui::path(&s.path)
2043×
        );
2053×
    }
20610×
}
207
208
/// Say when the working copy has fallen behind its own bookmark: a
209
/// "clean" status there hid a pull that left it on old code (oxygen#89).
21010×
fn print_behind(repo: &Repo) {
21110×
    if let Ok(Some(n)) = repo.working_copy_behind() {
2120×
        println!(
2130×
            "  {} {}",
2140×
            ui::caution(),
2150×
            ui::warn(format!(
2160×
                "the working copy is behind {}: it lacks {} the bookmark has; oxy checkout brings it up",
2170×
                repo.config.bookmark,
2180×
                plural(n, "change")
2190×
            ))
2200×
        );
22110×
    }
22210×
}
223
22415×
pub fn status(json: bool) -> Result<i32> {
22515×
    let repo = open()?;
226
    // Answered by the manifest alone, with no history to load (oxygen#35,
227
    // #41): a clean working copy, or one as the last snapshot left it.
22815×
    let known = if json {
2295×
        None
230
    } else {
23110×
        repo.status_by_manifest()?
232
    };
23315×
    if let Some(statuses) = known {
2344×
        let (_, wc) = repo.working_copy()?;
2354×
        let heads = repo.bookmark_heads()?;
2364×
        println!(
237
            "{} {}{}working copy {}{}{}",
2384×
            ui::dim("On"),
2394×
            ui::bookmark(&repo.config.bookmark),
2404×
            ui::sep(),
2414×
            ui::id(wc.change_id.short(8)),
2424×
            ui::sep(),
2434×
            ui::dim(plural(heads.len(), "head"))
244
        );
2454×
        print_behind(&repo);
2464×
        print_statuses(&statuses);
2474×
        print_pin_moves(&pin_moves(&repo, None));
2484×
        print_untracked_nested(&repo, &repo.untracked_nested());
2494×
        print_skipped_large(&repo);
2504×
        return Ok(0);
25111×
    }
25211×
    let sp = ui::spinner("Snapshotting the working copy…");
25311×
    let snap = repo.snapshot_status("oxy status")?;
25411×
    let heads = {
25511×
        let _t = oxy_core::timing::phase("status: heads");
25611×
        repo.bookmark_heads()?
257
    };
25811×
    let _drop = oxy_core::timing::phase("status: print and drop");
25911×
    sp.clear();
26011×
    if json {
2615×
        println!("{}", repo.status_json(&snap)?);
2625×
        return Ok(if snap.base_snapshot.is_conflicted() {
2630×
            2
264
        } else {
2655×
            0
266
        });
2676×
    }
2686×
    println!(
269
        "{} {}{}working copy {}{}{}",
2706×
        ui::dim("On"),
2716×
        ui::bookmark(&repo.config.bookmark),
2726×
        ui::sep(),
2736×
        ui::id(snap.wc.change_id.short(8)),
2746×
        ui::sep(),
2756×
        ui::dim(plural(heads.len(), "head"))
276
    );
2776×
    print_behind(&repo);
2786×
    print_statuses(&snap.statuses);
2796×
    print_pin_moves(&pin_moves(&repo, None));
2806×
    print_untracked_nested(&repo, &snap.untracked_nested);
2816×
    print_skipped_large(&repo);
2826×
    if !snap.base_snapshot.is_conflicted() {
2836×
        return Ok(0);
2840×
    }
2850×
    println!();
2860×
    println!(
287
        "{} {}",
2880×
        ui::section(ui::err("Conflicts")),
2890×
        ui::dim("edit the marked files, or the .oxy-conflict-N candidates, then commit")
290
    );
2910×
    for c in &snap.base_snapshot.tree.conflicts {
2920×
        println!("  {} tree: {c:?}", ui::err(ui::glyph("✱", "!")));
2930×
    }
2940×
    for (p, f) in &snap.base_snapshot.files {
2950×
        if f.is_conflicted() {
2960×
            let state = match snap
2970×
                .statuses
2980×
                .iter()
2990×
                .find(|s| s.path == *p)
3000×
                .map(|s| s.status)
301
            {
302
                Some(ChangeStatus::Resolved) => {
3030×
                    ui::ok(format!("{} resolved in working copy", ui::glyph("✔", "*")))
304
                }
305
                Some(ChangeStatus::ConflictEdited) => {
3060×
                    ui::warn(format!("{} markers remain", ui::glyph("‼", "!")))
307
                }
3080×
                _ => ui::err(format!("{} unresolved", ui::glyph("✱", "!"))),
309
            };
3100×
            println!("  {}  {state}", ui::path(p));
3110×
            let resolved = matches!(
3120×
                snap.statuses
3130×
                    .iter()
3140×
                    .find(|s| s.path == *p)
3150×
                    .map(|s| s.status),
316
                Some(ChangeStatus::Resolved)
317
            );
3180×
            let both = if resolved {
3190×
                0
320
            } else {
3210×
                snap.base.both_sides(&f.node).iter().flatten().count()
322
            };
3230×
            if both > 0 {
3240×
                println!(
325
                    "     {}",
3260×
                    ui::dim(format!(
327
                        "{} adjacent {}: `oxy resolve --both {p}` keeps both sides, earliest first",
328
                        both,
3290×
                        if both == 1 { "insertion" } else { "insertions" }
330
                    ))
331
                );
3320×
            }
3330×
        }
334
    }
3350×
    Ok(2)
33615×
}
337
33836×
pub fn commit(
33936×
    message: &str,
34036×
    depends_on: &[String],
34136×
    paths: &[String],
34236×
    interactive: bool,
34336×
    hunks: &[usize],
34436×
) -> Result<i32> {
34536×
    let repo = open()?;
34636×
    let mut deps = Vec::new();
34736×
    for d in depends_on {
3480×
        deps.push(repo.resolve_change(d)?);
349
    }
35036×
    let selection = if !hunks.is_empty() {
3511×
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
35235×
    } else if interactive {
3530×
        let (_, hunks) = repo.hunks()?;
3540×
        if hunks.is_empty() {
3550×
            anyhow::bail!("nothing to commit: the working copy matches its base");
3560×
        }
3570×
        let hunks: Vec<_> = hunks
3580×
            .into_iter()
3590×
            .filter(|h| {
3600×
                paths.is_empty()
3610×
                    || paths.iter().any(|p| {
3620×
                        h.path == *p || h.path.starts_with(&format!("{}/", p.trim_end_matches('/')))
3630×
                    })
3640×
            })
3650×
            .collect();
3660×
        let mut chosen = Vec::new();
3670×
        let stdin = std::io::stdin();
3680×
        let mut take_rest = false;
3690×
        for (n, h) in hunks.iter().enumerate() {
3700×
            if take_rest {
3710×
                chosen.push(h.index);
3720×
                continue;
3730×
            }
3740×
            println!(
375
                "{} {} {}",
3760×
                ui::section(format!("hunk {} of {}", n + 1, hunks.len())),
3770×
                ui::path(&h.path),
3780×
                ui::dim(format!("(#{})", h.index))
379
            );
3800×
            for line in h.text.lines() {
3810×
                let styled = if line.starts_with('+') {
3820×
                    ui::ok(line)
3830×
                } else if line.starts_with('-') {
3840×
                    ui::err(line)
385
                } else {
3860×
                    ui::dim(line)
387
                };
3880×
                println!("  {styled}");
389
            }
390
            loop {
3910×
                print!(
392
                    "{} ",
3930×
                    ui::warn("Commit this hunk? [y]es [n]o [a]ll remaining [q]uit:")
394
                );
395
                use std::io::Write as _;
3960×
                std::io::stdout().flush()?;
3970×
                let mut answer = String::new();
3980×
                if stdin.read_line(&mut answer)? == 0 {
3990×
                    anyhow::bail!("aborted");
4000×
                }
4010×
                match answer.trim() {
4020×
                    "y" | "Y" => {
4030×
                        chosen.push(h.index);
4040×
                        break;
405
                    }
4060×
                    "n" | "N" | "" => break,
4070×
                    "a" | "A" => {
4080×
                        chosen.push(h.index);
4090×
                        take_rest = true;
4100×
                        break;
411
                    }
4120×
                    "q" | "Q" => anyhow::bail!("aborted; nothing committed"),
4130×
                    _ => continue,
414
                }
415
            }
416
        }
4170×
        if chosen.is_empty() {
4180×
            anyhow::bail!("no hunks chosen; nothing committed");
4190×
        }
4200×
        oxy_core::repo::Selection::Hunks(chosen)
42135×
    } else if paths.is_empty() {
42231×
        oxy_core::repo::Selection::All
423
    } else {
4244×
        oxy_core::repo::Selection::Paths(paths.to_vec())
425
    };
426
    // Pins this commit records as moved, said after it (oxygen#162): a pin
427
    // moved by work inside a subrepo is a pin bump, easy to make unasked.
42836×
    let moves = match &selection {
42931×
        oxy_core::repo::Selection::All => pin_moves(&repo, None),
4304×
        oxy_core::repo::Selection::Paths(p) => pin_moves(&repo, Some(p)),
4311×
        oxy_core::repo::Selection::Hunks(_) => Vec::new(),
432
    };
43336×
    let sp = ui::spinner("Committing…");
43436×
    let (h, partial) = repo.commit_selection_partial(message, &deps, &selection)?;
435
    // The metadata only: a first commit's change holds the whole tree.
43636×
    let meta = repo.store().get_change_meta(&h)?;
43736×
    sp.done(&format!(
43836×
        "{} {} {}  {}",
43936×
        ui::done("Committed"),
44036×
        ui::id(meta.change_id.short(8)),
44136×
        ui::hash(format!("#{}", h.short(12))),
44236×
        ui::subject(subject_of(message))
44336×
    ));
44436×
    for m in &moves {
4451×
        let line = match (&m.to, m.dirty) {
4461×
            (Some(to), _) => format!(
447
                "recorded subrepo {}'s pin moving {} {} {}: a pin bump. Meant only your own files? `oxy commit PATHS` leaves pins out",
448
                m.path,
449
                m.from,
4501×
                ui::glyph("→", "->"),
451
                to
452
            ),
4530×
            (None, true) => format!(
454
                "subrepo {} has uncommitted edits of its own: the pin names its last committed state; the edits stay in it",
455
                m.path
456
            ),
4570×
            (None, false) => continue,
458
        };
4591×
        println!("  {} {}", ui::caution(), ui::warn(line));
460
    }
46136×
    print_untracked_nested(&repo, &repo.untracked_nested());
46236×
    print_skipped_large(&repo);
463
    // Only a commit that took part of the working copy leaves anything.
46436×
    if partial {
4654×
        let rest = repo.snapshot_status("oxy commit")?;
4664×
        if !rest.statuses.is_empty() {
4674×
            println!(
4684×
                "  {} {}",
4694×
                ui::note(),
4704×
                ui::dim(format!(
4714×
                    "{} left uncommitted",
4724×
                    plural(rest.statuses.len(), "path")
4734×
                ))
4744×
            );
4754×
        }
47632×
    }
47736×
    where_now(&repo);
47836×
    Ok(0)
47936×
}
480
481
/// A subrepo whose pin the next commit would move (`to`), or which has
482
/// uncommitted edits of its own (oxygen#162).
483
struct PinMove {
484
    path: String,
485
    from: String,
486
    to: Option<String>,
487
    dirty: bool,
488
}
489
490
/// The subrepos (among `paths`, when given) whose checkout is not at the
491
/// pin the base records, or holds uncommitted edits. Only a checkout with
492
/// subrepos (an `.oxymodules`) pays for the look.
49345×
fn pin_moves(repo: &oxy_core::repo::Repo, paths: Option<&[String]>) -> Vec<PinMove> {
49445×
    if !repo.root().join(".oxymodules").exists() {
49538×
        return Vec::new();
4967×
    }
4977×
    let Ok(subs) = repo.subrepos() else {
4980×
        return Vec::new();
499
    };
5007×
    let chosen = |p: &str| {
5016×
        paths.is_none_or(|ps| {
5021×
            ps.iter().any(|x| {
5031×
                let x = x.trim_end_matches('/');
5041×
                p == x || p.starts_with(&format!("{x}/")) || x.is_empty() || x == "."
5051×
            })
5061×
        })
5076×
    };
5087×
    subs.into_iter()
5097×
        .filter(|s| s.committed && chosen(&s.path))
5107×
        .filter_map(|s| {
5115×
            let to = s
5125×
                .actual
5135×
                .as_ref()
5145×
                .filter(|a| !a.same_state(&s.pin))
5155×
                .map(|a| a.summary());
5165×
            (to.is_some() || s.dirty).then(|| PinMove {
5173×
                from: s.pin.summary(),
5183×
                to,
5193×
                dirty: s.dirty,
5203×
                path: s.path,
5213×
            })
5225×
        })
5237×
        .collect()
52445×
}
525
526
/// `oxy status`'s word on subrepos: a moved pin is a change the next commit
527
/// records; edits inside a subrepo are not.
52810×
fn print_pin_moves(moves: &[PinMove]) {
52910×
    if moves.is_empty() {
5308×
        return;
5312×
    }
5322×
    println!("{}", ui::section("Subrepo pins"));
5332×
    for m in moves {
5342×
        if let Some(to) = &m.to {
5351×
            println!(
5361×
                "  {} {}  {} {} {}  {}",
5371×
                ui::warn(ui::glyph("↕", "<>")),
5381×
                ui::path(&m.path),
5391×
                ui::dim(&m.from),
5401×
                ui::dim(ui::glyph("→", "->")),
5411×
                to,
5421×
                ui::dim("pin moved: a bare `oxy commit` records it")
5431×
            );
5441×
        }
5452×
        if m.dirty {
5461×
            println!(
5471×
                "  {} {}  {}",
5481×
                ui::warn(ui::glyph("✎", "~")),
5491×
                ui::path(&m.path),
5501×
                ui::dim("uncommitted edits inside it: commit them there; the parent records only its pin")
5511×
            );
5521×
        }
553
    }
55410×
}
555
5560×
pub fn blame(path: &str, json: bool) -> Result<i32> {
5570×
    let repo = open()?;
5580×
    let lines = repo.blame(path)?;
5590×
    if json {
5600×
        let items = lines.iter().map(|l| {
5610×
            format!(
562
                "{{\"line\":{},\"change_id\":{},\"hash\":{},\"index\":{},\"author\":{},\"when_ms\":{}}}",
563
                l.line,
5640×
                oxy_core::repo::json_str(&l.change_id.to_hex()),
5650×
                oxy_core::repo::json_str(&l.hash.to_hex()),
566
                l.index,
5670×
                oxy_core::repo::json_str(&l.author),
568
                l.when_ms
569
            )
5700×
        });
5710×
        println!("{}", oxy_core::repo::json_array(items));
5720×
        return Ok(0);
5730×
    }
5740×
    let width = lines
5750×
        .iter()
5760×
        .map(|l| l.author.chars().count())
5770×
        .max()
5780×
        .unwrap_or(0)
5790×
        .min(20);
5800×
    let digits = lines.len().to_string().len();
5810×
    let _t = oxy_core::timing::phase("blame: print");
582
    // Most lines share their change with many others: each change's id,
583
    // author and age are formatted once, and the lines go out through one
584
    // buffered lock on stdout.
5850×
    let mut prefix: std::collections::HashMap<oxy_core::hash::ChangeHash, String> =
5860×
        std::collections::HashMap::new();
5870×
    let bar = ui::dim(ui::glyph("│", "|"));
5880×
    let mut out = std::io::BufWriter::with_capacity(1 << 16, std::io::stdout().lock());
5890×
    for l in &lines {
5900×
        let p = prefix.entry(l.hash).or_insert_with(|| {
5910×
            let author: String = l.author.chars().take(20).collect();
5920×
            format!(
593
                "{} {} {}",
5940×
                ui::id(l.change_id.short(8)),
5950×
                ui::author(format!("{author:<width$}")),
5960×
                ui::dim(ui::ago(l.when_ms))
597
            )
5980×
        });
5990×
        let text = String::from_utf8_lossy(&l.text);
6000×
        if writeln!(
6010×
            out,
602
            "{p} {:>digits$}{bar} {}",
603
            l.line,
6040×
            text.trim_end_matches('\n')
605
        )
6060×
        .is_err()
607
        {
608
            // A closed pipe (blame | head): stop quietly.
6090×
            return Ok(0);
6100×
        }
611
    }
6120×
    let _ = out.flush();
6130×
    Ok(0)
6140×
}
615
6160×
fn bisect_report(repo: &Repo, step: &oxy_core::repo::BisectStep) -> Result<i32> {
617
    use oxy_core::repo::BisectStep::*;
6180×
    match step {
6190×
        NeedMarks { good, bad } => {
6200×
            println!(
621
                "{} {} {}",
6220×
                ui::note(),
6230×
                ui::dim(format!("{good} good, {bad} bad;")),
6240×
                ui::dim(if *good == 0 {
6250×
                    "mark a known-good change or bookmark: oxy bisect good CHANGE"
626
                } else {
6270×
                    "mark a known-bad change or bookmark: oxy bisect bad CHANGE"
628
                })
629
            );
6300×
            Ok(0)
631
        }
632
        Testing {
6330×
            heads,
6340×
            remaining,
6350×
            steps_left,
636
        } => {
6370×
            println!(
638
                "{} {} {}",
6390×
                ui::done("Testing"),
6400×
                ui::dim(format!(
641
                    "{} in the state under test;",
6420×
                    plural(heads.len(), "head")
643
                )),
6440×
                ui::dim(format!(
645
                    "{remaining} candidates left, about {steps_left} more steps"
646
                ))
647
            );
6480×
            println!(
649
                "  {} {}",
6500×
                ui::note(),
6510×
                ui::dim("run your test, then oxy bisect good | bad | skip")
652
            );
6530×
            Ok(0)
654
        }
6550×
        Found { culprit } => {
6560×
            let c = repo.store().get_change(culprit)?;
6570×
            println!(
658
                "{} {} {}  {}",
6590×
                ui::done("Found"),
6600×
                ui::id(short_id(&c)),
6610×
                ui::hash(format!("#{}", culprit.short(12))),
6620×
                ui::subject(subject_of(&c.message))
663
            );
6640×
            println!("  {} {}", ui::note(), ui::dim("the first change whose inclusion makes the state bad; oxy bisect reset to return"));
6650×
            Ok(0)
666
        }
6670×
        Inconclusive { candidates } => {
6680×
            println!(
669
                "{} {}",
6700×
                ui::caution(),
6710×
                ui::warn(format!(
672
                    "every remaining candidate was skipped ({}); oxy bisect reset to return",
6730×
                    plural(candidates.len(), "change")
674
                ))
675
            );
6760×
            Ok(1)
677
        }
678
    }
6790×
}
680
6810×
pub fn bisect_start() -> Result<i32> {
6820×
    let repo = open()?;
6830×
    repo.bisect_start()?;
6840×
    println!(
685
        "{} bisect; {}",
6860×
        ui::done("Started"),
6870×
        ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE")
688
    );
6890×
    Ok(0)
6900×
}
691
6920×
pub fn bisect_mark(good: Option<bool>, changes: &[String]) -> Result<i32> {
6930×
    let repo = open()?;
6940×
    let mut heads = Vec::new();
6950×
    for c in changes {
6960×
        heads.extend(repo.resolve_heads(c)?);
697
    }
6980×
    let step = repo.bisect_mark(good, &heads)?;
6990×
    bisect_report(&repo, &step)
7000×
}
701
7020×
pub fn bisect_run(command: &[String]) -> Result<i32> {
7030×
    let repo = open()?;
7040×
    let step = repo.bisect_run(command)?;
7050×
    bisect_report(&repo, &step)
7060×
}
707
7081×
pub fn bisect_status(as_json: bool) -> Result<i32> {
7091×
    let repo = open()?;
7101×
    if as_json {
711
        use oxy_core::repo::BisectStep::*;
7121×
        let v = match repo.bisect_status()? {
7131×
            None => "null".to_string(),
7140×
            Some(NeedMarks { good, bad }) => json::obj([
7150×
                ("state", json::s("need-marks")),
7160×
                ("good", json::n(good)),
7170×
                ("bad", json::n(bad)),
7180×
            ]),
719
            Some(Testing {
7200×
                heads,
7210×
                remaining,
7220×
                steps_left,
7230×
            }) => json::obj([
7240×
                ("state", json::s("testing")),
7250×
                ("heads", json::hashes(&heads)),
7260×
                ("remaining", json::n(remaining)),
7270×
                ("steps_left", json::n(steps_left)),
7280×
            ]),
7290×
            Some(Found { culprit }) => json::obj([
7300×
                ("state", json::s("found")),
7310×
                ("culprit", json::s(&culprit.to_hex())),
7320×
            ]),
7330×
            Some(Inconclusive { candidates }) => json::obj([
7340×
                ("state", json::s("inconclusive")),
7350×
                ("candidates", json::hashes(&candidates)),
7360×
            ]),
737
        };
7381×
        println!("{v}");
7391×
        return Ok(0);
7400×
    }
7410×
    match repo.bisect_status()? {
742
        None => {
7430×
            println!("{}", ui::dim("No bisect in progress."));
7440×
            Ok(0)
745
        }
7460×
        Some(step) => bisect_report(&repo, &step),
747
    }
7481×
}
749
7500×
pub fn bisect_reset() -> Result<i32> {
7510×
    let repo = open()?;
7520×
    repo.bisect_reset()?;
7530×
    println!("{} bisect; working copy restored", ui::done("Reset"));
7540×
    Ok(0)
7550×
}
756
757
/// The log: one entry per change, newest first, joined by a rail. The
758
/// default view is the subject and a metadata line; `verbose` adds the full
759
/// message, dependencies, and the authenticating key.
76016×
fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
76116×
    Ok(match repo.authenticate_change(h)? {
7629×
        SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]),
763
        SignatureStatus::Valid {
7647×
            key,
7657×
            name,
7667×
            email,
7677×
            sealed,
7687×
            revoked,
7697×
        } => json::obj([
7707×
            ("status", json::s(if sealed { "sealed" } else { "signed" })),
7717×
            ("key", json::s(&key.to_hex())),
7727×
            ("name", json::s(&name)),
7737×
            ("email", json::s(&email)),
7747×
            ("revoked", json::b(revoked)),
775
        ]),
7760×
        SignatureStatus::Invalid(why) => {
7770×
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
778
        }
779
    })
78016×
}
781
78222×
fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result<String> {
78322×
    let c = &e.change;
78422×
    Ok(json::obj([
78522×
        ("hash", json::s(&e.hash.to_hex())),
78622×
        ("change_id", json::s(&c.change_id.to_hex())),
78722×
        ("author", json::s(&author_name(repo, c))),
78822×
        ("author_key", json::s(&c.author.to_hex())),
789
        (
79022×
            "via",
79122×
            match via(
79222×
                repo,
79322×
                &repo.authenticate_change_known(&e.hash, Some(c))?,
79422×
                &c.author,
795
            ) {
7960×
                Some(v) => json::obj([
7970×
                    ("name", json::s(&v.name)),
7980×
                    ("email", json::s(&v.email)),
7990×
                    ("key", json::s(&v.key.to_hex())),
8000×
                    ("scope", json::opt(v.scope.as_deref(), json::s)),
8010×
                    ("expires_ms", json::opt(v.expires, json::n)),
8020×
                    ("revoked", json::b(v.revoked)),
8030×
                ]),
80422×
                None => "null".to_string(),
805
            },
806
        ),
80722×
        ("when_ms", json::n(c.hlc.wall_ms)),
80822×
        ("message", json::s(&c.message)),
80922×
        ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())),
81022×
        ("deps", json::hashes(&c.deps)),
81122×
        ("head", json::b(e.is_head)),
81222×
        ("working_copy", json::b(e.is_working_copy)),
813
        (
81422×
            "signature",
81522×
            if e.is_working_copy {
8166×
                "null".into()
817
            } else {
81816×
                signature_json(repo, &e.hash)?
819
            },
820
        ),
821
    ]))
82222×
}
823
824
/// `START,END:PATH` for `oxy log -L`.
8252×
fn parse_line_range(spec: &str) -> Result<(usize, usize, &str)> {
8262×
    let bad = || anyhow::anyhow!("-L {spec}: expected START,END:PATH, as 10,24:src/lib.rs");
8272×
    let (range, path) = spec.split_once(':').ok_or_else(bad)?;
8282×
    let (a, b) = range.split_once(',').ok_or_else(bad)?;
829
    Ok((
8301×
        a.trim().parse().map_err(|_| bad())?,
8311×
        b.trim().parse().map_err(|_| bad())?,
8321×
        path,
833
    ))
8342×
}
835
83610×
pub fn log(
83710×
    revset: Option<&str>,
83810×
    limit: Option<usize>,
83910×
    verbose: bool,
84010×
    path: Option<&str>,
84110×
    lines: Option<&str>,
84210×
    as_json: bool,
84310×
) -> Result<i32> {
84410×
    let repo = open()?;
845
    // Whether the working copy is clean and conflicted: from the manifest
846
    // when it proves the working copy clean, else from a snapshot.
847
    // The working copy as last recorded, without looking at the files (as
848
    // Git's log does not): whether its change holds edits, and whether its
849
    // base was conflicted. `oxy status` is what checks the disk.
85010×
    let conflicted = !repo.is_at_op() && repo.recorded_conflicted()?;
85110×
    let listing = oxy_core::timing::phase("log: entries");
85210×
    let entries = match (path, lines) {
85310×
        _ if revset.is_some() => repo.log_revset(revset.unwrap_or_default())?,
8542×
        (_, Some(spec)) => {
8552×
            let (first, last, p) = parse_line_range(spec)?;
8561×
            let (_, wc) = repo.working_copy()?;
8571×
            let base = repo.load_state_history(&wc.deps)?.maximal(&wc.deps);
8581×
            repo.line_history(&base, p, first, last)?
859
        }
8601×
        (Some(p), None) => repo.log_for_path(p)?,
8617×
        (None, None) => repo.log()?,
862
    };
8639×
    drop(listing);
8649×
    let _print = oxy_core::timing::phase("log: print");
8659×
    if as_json {
8668×
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
8678×
        let mut items = Vec::new();
86821×
        for e in entries.iter().take(shown) {
86921×
            items.push(log_entry_json(&repo, e)?);
870
        }
8718×
        println!(
872
            "{}",
8738×
            json::obj([
8748×
                ("bookmark", json::s(&repo.config.bookmark)),
8758×
                ("total", json::n(entries.len())),
8768×
                ("changes", json::arr(items))
8778×
            ])
878
        );
8798×
        return Ok(0);
8801×
    }
8811×
    let total = entries.len();
8821×
    let shown = limit.unwrap_or(total).min(total);
883
    // Lay out a little past what is shown, so edges into the cut are drawn.
8841×
    let window: Vec<(ChangeHash, Vec<ChangeHash>)> = entries
8851×
        .iter()
8861×
        .take((shown + MAX_EDGE).min(total))
8874×
        .map(|e| (e.hash, e.change.deps.clone()))
8881×
        .collect();
8891×
    let rows = oxy_core::lanes::graph(&window, MAX_EDGE);
890
    // Highlight the shortest prefix that names each change: against the
891
    // whole log, which is what `resolve_change` searches.
892
    let everything;
8931×
    let all = if path.is_some() || lines.is_some() || revset.is_some() {
8940×
        everything = repo.log()?;
8950×
        &everything
896
    } else {
8971×
        &entries
898
    };
8991×
    let prefixes = oxy_core::timing::phase("log: id prefixes");
9001×
    let id_prefix = id_prefixes(
9011×
        all.iter().map(|e| e.change.change_id.0).collect(),
9021×
        entries.iter().take(shown).map(|e| e.change.change_id.0),
903
    );
9041×
    drop(prefixes);
9051×
    let labels = reference_labels(&repo)?;
9064×
    for (e, row) in entries.iter().take(shown).zip(&rows) {
9074×
        let c = &e.change;
9084×
        let bullet = ui::log_bullet(
9094×
            e.is_working_copy,
9104×
            e.is_head,
9114×
            e.is_working_copy && conflicted,
912
        );
9134×
        let id = c.change_id.to_hex();
9144×
        let n = id_prefix.get(&c.change_id.0).copied().unwrap_or(8).min(8);
9154×
        let mut head = vec![format!("{}{}", ui::id(&id[..n]), ui::dim(&id[n..8]))];
9164×
        head.push(ui::author(author_name(&repo, c)));
9174×
        head.push(ui::dim(ui::ago(c.hlc.wall_ms)));
9184×
        if let Some(names) = labels.get(&e.hash) {
9192×
            head.push(names.join(" "));
9202×
        }
9214×
        if c.kind == ChangeKind::Resolution {
9220×
            head.push(ui::warn("resolution"));
9234×
        }
9244×
        if !e.is_working_copy {
9253×
            head.push(ui::hash(format!("#{}", e.hash.short(8))));
9263×
            let status = repo.authenticate_change_known(&e.hash, Some(c))?;
9273×
            if let Some(agent) = via(&repo, &status, &c.author) {
9280×
                head.push(ui::dim(format!("via {}", agent.name)));
9293×
            }
9303×
            head.push(signature_mark_of(
9313×
                &status,
9323×
                awaits_seal(&repo, &status, &c.author),
933
            ));
9341×
        }
9354×
        println!("{}{}", node_line(row, &bullet), head.join(" "));
9364×
        let subject = if e.is_working_copy && c.message.is_empty() {
9371×
            let edited = repo
9381×
                .store()
9391×
                .get_change(&e.hash)
9401×
                .is_ok_and(|w| !w.tree_ops.is_empty() || !w.edits.is_empty());
9411×
            ui::dim(if edited {
9420×
                "(working copy, uncommitted changes)"
943
            } else {
9441×
                "(working copy)"
945
            })
9463×
        } else if c.message.trim().is_empty() {
9470×
            ui::dim("(no description)")
948
        } else {
9493×
            subject_of(&c.message).to_string()
950
        };
9514×
        println!("{}{subject}", below_line(row));
9524×
        if verbose {
9530×
            let rail = continuation(row);
9540×
            if !e.is_working_copy {
9550×
                println!(
956
                    "{rail}{}",
9570×
                    ui::dim(format!(
958
                        "{} {}",
9590×
                        when(c.hlc.wall_ms),
9600×
                        signature_line(&repo, &e.hash)?
961
                    ))
962
                );
9630×
            }
9640×
            if !c.deps.is_empty() {
9650×
                println!(
9660×
                    "{rail}{} {}",
9670×
                    ui::dim(ui::glyph("↳", "->")),
9680×
                    ui::dim(deps_of(&c.deps))
9690×
                );
9700×
            }
9710×
            let body: Vec<&str> = c
9720×
                .message
9730×
                .lines()
9740×
                .skip(1)
9750×
                .skip_while(|l| l.trim().is_empty())
9760×
                .collect();
9770×
            for line in body {
9780×
                println!("{rail}  {line}");
9790×
            }
9804×
        }
981
    }
9821×
    if shown < total {
9830×
        if let Some(last) = rows.get(shown.saturating_sub(1)) {
9840×
            let cut: String = last
9850×
                .below
9860×
                .iter()
9870×
                .map(|c| match c {
9880×
                    Cell::Blank | Cell::Elided | Cell::JoinRight => "  ",
9890×
                    _ => "~ ",
9900×
                })
9910×
                .collect();
9920×
            if cut.trim().is_empty() {
9930×
                println!("{}", ui::dim("~"));
9940×
            } else {
9950×
                println!("{}", ui::dim(cut.trim_end()));
9960×
            }
9970×
        }
9980×
        println!(
999
            "{}",
10000×
            ui::dim(format!(
1001
                "{} {} more; pass -n to see them",
10020×
                ui::glyph("…", "..."),
10030×
                total - shown
1004
            ))
1005
        );
10061×
    }
10071×
    Ok(0)
100810×
}
1009
1010
/// Rows a drawn edge may span in `oxy log`; a longer one is elided (`~`).
1011
const MAX_EDGE: usize = 12;
1012
1013
use oxy_core::hash::ChangeHash;
1014
use oxy_core::lanes::{Cell, GraphRow};
1015
1016
/// A graph cell, two columns wide.
10176×
fn cell(c: Cell) -> &'static str {
10186×
    match c {
10191×
        Cell::Blank => "  ",
10203×
        Cell::Line => ui::glyph("│ ", "| "),
10210×
        Cell::Elided => "~ ",
10221×
        Cell::JoinLeft => ui::glyph("├─", "|-"),
10230×
        Cell::JoinPass => ui::glyph("──", "--"),
10240×
        Cell::JoinCross => ui::glyph("┼─", "+-"),
10251×
        Cell::JoinRight => ui::glyph("╯ ", "' "),
1026
    }
10276×
}
1028
1029
/// The graph part of a change's own line, its bullet in its column.
10304×
fn node_line(row: &GraphRow, bullet: &str) -> String {
10314×
    let width = row
10324×
        .passing
10334×
        .iter()
10344×
        .copied()
10354×
        .max()
10364×
        .unwrap_or(0)
10374×
        .max(row.column)
10384×
        + 1;
10394×
    let mut out = String::new();
10405×
    for c in 0..width {
10415×
        if c == row.column {
10424×
            out.push_str(bullet);
10434×
            out.push(' ');
10444×
        } else if row.passing.contains(&c) {
10451×
            out.push_str(&ui::dim(cell(Cell::Line)));
10461×
        } else {
10470×
            out.push_str("  ");
10480×
        }
1049
    }
10504×
    out.push(' ');
10514×
    out
10524×
}
1053
1054
/// The graph part of the line under a change: lanes carrying on, a join,
1055
/// or `~` for an elided edge.
10564×
fn below_line(row: &GraphRow) -> String {
10575×
    let g: String = row.below.iter().map(|c| cell(*c)).collect();
10584×
    format!("{} ", ui::dim(g))
10594×
}
1060
1061
/// The graph part of any further line of a change (`-v`).
10620×
fn continuation(row: &GraphRow) -> String {
10630×
    let g: String = row
10640×
        .below
10650×
        .iter()
10660×
        .map(|c| match c {
10670×
            Cell::Line | Cell::JoinLeft | Cell::JoinCross => cell(Cell::Line),
10680×
            _ => "  ",
10690×
        })
10700×
        .collect();
10710×
    format!("{} ", ui::dim(g))
10720×
}
1073
1074
/// For each hex ID, the length of its shortest prefix no other ID shares.
1075
/// The shortest prefix, in hex digits, that names each of `wanted` among
1076
/// `all`: worked out for the few shown rather than for the whole history.
10772×
fn id_prefixes(
10782×
    mut all: Vec<[u8; 16]>,
10792×
    wanted: impl Iterator<Item = [u8; 16]>,
10802×
) -> std::collections::HashMap<[u8; 16], usize> {
10812×
    all.sort_unstable();
10822×
    all.dedup();
1083
    // Hex digits two ids share at the start.
10844004×
    let common = |a: &[u8; 16], b: &[u8; 16]| {
108510720×
        let bytes = a.iter().zip(b).take_while(|(x, y)| x == y).count();
10864004×
        match (a.get(bytes), b.get(bytes)) {
10874004×
            (Some(x), Some(y)) if x >> 4 == y >> 4 => 2 * bytes + 1,
10881858×
            _ => 2 * bytes,
1089
        }
10904004×
    };
10912×
    let mut out = std::collections::HashMap::new();
10922004×
    for id in wanted {
10932004×
        let Ok(i) = all.binary_search(&id) else {
10940×
            continue;
1095
        };
10962004×
        let before = i.checked_sub(1).map_or(0, |j| common(&all[j], &id));
10972004×
        let after = all.get(i + 1).map_or(0, |n| common(&id, n));
10982004×
        out.insert(id, before.max(after) + 1);
1099
    }
11002×
    out
11012×
}
1102
11031×
fn unique_prefixes(ids: impl Iterator<Item = String>) -> std::collections::HashMap<String, usize> {
11041×
    let mut v: Vec<String> = ids.collect();
11051×
    v.sort();
11061×
    v.dedup();
110719576×
    let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
11081×
    let mut out = std::collections::HashMap::with_capacity(v.len());
11092000×
    for i in 0..v.len() {
11102000×
        let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 };
11112000×
        let after = if i + 1 < v.len() {
11121999×
            common(&v[i], &v[i + 1])
1113
        } else {
11141×
            0
1115
        };
11162000×
        out.insert(v[i].clone(), before.max(after) + 1);
1117
    }
11181×
    out
11191×
}
1120
1121
/// Bookmark, remote bookmark and tag names to show beside the changes they
1122
/// point at. A name is shown on each head of its state; one with more than
1123
/// three heads names too much of the log to help, so it is left out (oxy
1124
/// bookmark list shows it). A remote bookmark at the same state as the
1125
/// local one of that name is not repeated.
11261×
fn reference_labels(repo: &Repo) -> Result<std::collections::HashMap<ChangeHash, Vec<String>>> {
1127
    const MAX_HEADS: usize = 3;
11281×
    let view = repo.view()?;
11291×
    let mut out: std::collections::HashMap<ChangeHash, Vec<String>> = Default::default();
11301×
    let mut add = |heads: Vec<ChangeHash>, label: String| {
11311×
        if heads.len() <= MAX_HEADS {
11322×
            for h in heads {
11332×
                out.entry(h).or_default().push(label.clone());
11342×
            }
11350×
        }
11361×
    };
11371×
    for (name, st) in &view.bookmarks {
11381×
        add(repo.store().get_state(st)?.heads, ui::bookmark(name));
1139
    }
11401×
    for (remote, bookmarks) in &view.remotes {
11410×
        for (name, st) in bookmarks {
11420×
            if view.bookmarks.get(name) == Some(st) {
11430×
                continue;
11440×
            }
11450×
            add(
11460×
                repo.store().get_state(st)?.heads,
11470×
                ui::dim(format!("{remote}/{name}")),
1148
            );
1149
        }
1150
    }
11511×
    for t in repo.tags()? {
11520×
        add(t.heads.clone(), ui::warn(&t.name));
11530×
    }
11541×
    Ok(out)
11551×
}
1156
11571×
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
11581×
    let repo = open()?;
11591×
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
11601×
    if as_json {
11611×
        let files = repo.diff_files(hash.as_ref())?;
11623×
        let items = files.iter().map(|f| {
11633×
            json::obj([
11643×
                ("path", json::s(&f.path)),
11653×
                ("kind", json::s(&f.kind)),
11663×
                ("from", json::opt(f.from.as_deref(), json::s)),
1167
                (
11683×
                    "hunks",
11693×
                    json::arr(f.hunks.iter().map(|h| {
11703×
                        json::obj([
11713×
                            ("base_line", json::n(h.base_line)),
1172
                            (
11733×
                                "added",
11743×
                                json::arr(
11753×
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
1176
                                ),
1177
                            ),
1178
                            (
11793×
                                "removed",
11803×
                                json::arr(h.removed.iter().map(|(n, l)| {
11810×
                                    json::obj([
11820×
                                        ("line", json::n(*n)),
11830×
                                        ("text", json::s(&String::from_utf8_lossy(l))),
11840×
                                    ])
11850×
                                })),
1186
                            ),
1187
                        ])
11883×
                    })),
1189
                ),
1190
            ])
11913×
        });
11921×
        println!(
1193
            "{}",
11941×
            json::obj([
11951×
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
11961×
                ("files", json::arr(items))
1197
            ])
1198
        );
11991×
        return Ok(0);
12000×
    }
12010×
    match hash {
12020×
        Some(h) => {
12030×
            let c = repo.store().get_change(&h)?;
12040×
            let (base, snapshot) = repo.change_base(&c)?;
12050×
            print!("{}", render_change(&c, &base, &snapshot));
1206
        }
1207
        None => {
1208
            // Nothing changed: nothing to show, and no base to load.
12090×
            let Some((wc, base, snapshot)) = repo.working_copy_with_base_unless_unchanged()? else {
12100×
                return Ok(0);
1211
            };
12120×
            let text = {
12130×
                let _t = oxy_core::timing::phase("diff: render the change");
12140×
                render_change(&wc, &base, &snapshot)
1215
            };
12160×
            print!("{text}");
1217
            // The process ends here: freeing the base's tree and graphs
1218
            // one by one would only cost time (about 27 ms on Linux).
12190×
            std::mem::forget((wc, base, snapshot));
1220
        }
1221
    }
12220×
    Ok(0)
12231×
}
1224
12253×
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
12263×
    let repo = open()?;
12273×
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
12283×
    let bytes = match repo.file_at(path, heads.as_deref()) {
12293×
        Ok(b) => b,
1230
        // -r CHANGE reads that change's dependency closure, not the
1231
        // bookmark it is on: say so when the bookmark has the file
1232
        // (oxygen#76).
12330×
        Err(e) => match change {
12340×
            Some(c)
12350×
                if !repo.view()?.bookmarks.contains_key(c)
12360×
                    && repo.tag_heads(c)?.is_none()
12370×
                    && repo.file_at(path, None).is_ok() =>
1238
            {
12390×
                anyhow::bail!(
1240
                    "{path} is not in {c}'s dependency closure (the change and what it \
1241
                     depends on); it is on the bookmark: try -r {}, or --at-op OP for the \
1242
                     state at an operation",
1243
                    repo.config.bookmark
1244
                )
1245
            }
12460×
            _ => return Err(e.into()),
1247
        },
1248
    };
1249
    use std::io::Write as _;
12503×
    std::io::stdout().write_all(&bytes)?;
12513×
    Ok(0)
12523×
}
1253
12541×
pub fn root(as_json: bool) -> Result<i32> {
12551×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
12560×
        if as_json {
12570×
            println!("null");
12580×
        }
12590×
        return Ok(1);
1260
    };
12611×
    if as_json {
12621×
        println!(
12631×
            "{}",
12641×
            json::obj([
12651×
                ("root", json::s(&repo.root().to_string_lossy())),
12661×
                ("workspace", json::s(&repo.workspace().to_hex())),
12671×
                ("bookmark", json::s(&repo.config.bookmark))
12681×
            ])
12691×
        );
12701×
    } else {
12710×
        println!("{}", repo.root().display());
12720×
    }
12731×
    Ok(0)
12741×
}
1275
12761×
pub fn version(as_json: bool) -> Result<i32> {
12771×
    if as_json {
12781×
        println!(
12791×
            "{}",
12801×
            json::obj([
12811×
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
12821×
                // What was built: a release's or install's `oxy describe`,
12831×
                // a Flow build's heads, or "local build".
12841×
                ("build", json::s(env!("OXY_BUILD_ID"))),
12851×
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
12861×
                ("format", json::n(2))
12871×
            ])
12881×
        );
12891×
    } else {
12900×
        println!(
12910×
            "oxy {} (repository format 2, protocol {})",
12920×
            env!("OXY_VERSION_LONG"),
12930×
            oxy_core::protocol::PROTOCOL_VERSION
12940×
        );
12950×
    }
12961×
    Ok(0)
12971×
}
1298
12992×
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
13002×
    let repo = open()?;
13012×
    if paths.is_empty() && hunks.is_empty() {
13020×
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
13032×
    }
13042×
    let mut n = 0;
13052×
    if !hunks.is_empty() {
13061×
        n += repo.discard_hunks(hunks)?;
13071×
    }
13082×
    if !paths.is_empty() {
13091×
        n += repo.discard(paths)?;
13101×
    }
13112×
    println!(
1312
        "{} {} restored to the working copy's base",
13132×
        ui::done("Discarded"),
13142×
        plural(n, "path")
1315
    );
13162×
    Ok(0)
13172×
}
1318
13192×
pub fn hunks(as_json: bool) -> Result<i32> {
13202×
    let repo = open()?;
13212×
    let (_, hunks) = repo.hunks()?;
13222×
    if as_json {
13232×
        println!(
1324
            "{}",
13255×
            json::arr(hunks.iter().map(|h| json::obj([
13265×
                ("index", json::n(h.index)),
13275×
                ("path", json::s(&h.path)),
13285×
                ("text", json::s(&h.text))
13295×
            ])))
1330
        );
13312×
        return Ok(0);
13320×
    }
13330×
    if hunks.is_empty() {
13340×
        println!(
13350×
            "{}",
13360×
            ui::dim("No hunks: the working copy matches its base.")
13370×
        );
13380×
    }
13390×
    for h in &hunks {
13400×
        println!(
1341
            "{} {}",
13420×
            ui::section(format!("hunk {}", h.index)),
13430×
            ui::path(&h.path)
1344
        );
13450×
        for line in h.text.lines() {
13460×
            let styled = if line.starts_with('+') {
13470×
                ui::ok(line)
13480×
            } else if line.starts_with('-') {
13490×
                ui::err(line)
1350
            } else {
13510×
                ui::dim(line)
1352
            };
13530×
            println!("  {styled}");
1354
        }
1355
    }
13560×
    Ok(0)
13572×
}
1358
13593×
pub fn show(change: Option<&str>, revset: Option<&str>, stat: bool, as_json: bool) -> Result<i32> {
13603×
    let repo = open()?;
13613×
    repo.snapshot_status("oxy show")?;
13623×
    let Some(r) = revset else {
13633×
        let h = repo.resolve_change(change.unwrap_or("@"))?;
13643×
        return show_one(&repo, h, as_json, false, stat);
1365
    };
1366
    // Several changes: a JSON array, or the changes one after another.
13670×
    let hashes = repo.revset(r)?.hashes;
13680×
    if as_json {
13690×
        print!("[");
13700×
        for (i, h) in hashes.iter().enumerate() {
13710×
            if i > 0 {
13720×
                print!(",");
13730×
            }
13740×
            show_one(&repo, *h, true, true, stat)?;
1375
        }
13760×
        println!("]");
13770×
        return Ok(0);
13780×
    }
13790×
    if hashes.is_empty() {
13800×
        println!("{}", ui::dim(format!("No change matches {r:?}.")));
13810×
        return Ok(0);
13820×
    }
13830×
    for (i, h) in hashes.iter().enumerate() {
13840×
        if i > 0 {
13850×
            println!();
13860×
        }
13870×
        show_one(&repo, *h, false, false, stat)?;
1388
    }
13890×
    Ok(0)
13903×
}
1391
1392
/// Lines added and removed in one file's diff.
13932×
fn counts(f: &oxy_core::repo::FileDiff) -> (usize, usize) {
13942×
    f.hunks
13952×
        .iter()
13962×
        .fold((0, 0), |(a, r), h| (a + h.added.len(), r + h.removed.len()))
13972×
}
1398
1399
/// What `--stat` prints (oxygen#119): each file the change touched, its
1400
/// lines added and removed, then the total.
14011×
fn print_stat(files: &[oxy_core::repo::FileDiff]) {
14021×
    let width = files
14031×
        .iter()
14041×
        .map(|f| f.path.chars().count())
14051×
        .max()
14061×
        .unwrap_or(0)
14071×
        .min(60);
14081×
    let (mut added, mut removed) = (0, 0);
14091×
    for f in files {
14101×
        let (a, r) = counts(f);
14111×
        added += a;
14121×
        removed += r;
14131×
        let path = match &f.from {
14140×
            Some(from) => format!("{from} → {}", f.path),
14151×
            None => f.path.clone(),
1416
        };
14171×
        println!(
1418
            " {path:<width$}  {} {}  {}",
14191×
            ui::ok(format!("{:>6}", format!("+{a}"))),
14201×
            ui::err(format!("{:>6}", format!("-{r}"))),
14211×
            ui::dim(&f.kind)
1422
        );
1423
    }
14241×
    println!(
1425
        " {}",
14261×
        ui::dim(format!(
1427
            "{} changed, {added} added, {removed} removed",
14281×
            plural(files.len(), "file")
1429
        ))
1430
    );
14311×
}
1432
1433
/// One change, as `oxy show` prints it; `inline` JSON goes without its
1434
/// newline, for an array. `stat` lists the files instead of the diff.
14353×
fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool, stat: bool) -> Result<i32> {
14363×
    let c = repo.store().get_change(&h)?;
14373×
    if as_json {
14381×
        let files = repo.diff_files(Some(&h))?;
14391×
        let heads = repo.bookmark_heads()?;
14401×
        let entry = oxy_core::repo::LogEntry {
14411×
            hash: h,
14421×
            change: oxy_core::state::ChangeMeta::of(&c),
14431×
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
14441×
            is_head: heads.contains(&h),
14451×
        };
14461×
        let mut body = log_entry_json(repo, &entry)?;
14471×
        body.pop();
14481×
        body.push_str(&format!(
1449
            ",{}:{}}}",
14501×
            json::s("files"),
14511×
            json::arr(files.iter().map(|f| {
14521×
                let (a, r) = counts(f);
14531×
                json::obj([
14541×
                    ("path", json::s(&f.path)),
14551×
                    ("kind", json::s(&f.kind)),
14561×
                    ("from", json::opt(f.from.as_deref(), json::s)),
14571×
                    ("added", a.to_string()),
14581×
                    ("removed", r.to_string()),
14591×
                ])
14601×
            }))
1461
        ));
14621×
        if inline {
14630×
            print!("{body}");
14641×
        } else {
14651×
            println!("{body}");
14661×
        }
14671×
        return Ok(0);
14682×
    }
14692×
    println!(
1470
        "{} {} {}",
14712×
        ui::section("change"),
14722×
        ui::id(short_id(&c)),
14732×
        ui::hash(format!("#{h}"))
1474
    );
14752×
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1476
    // Fetched but not pulled (oxygen#56): say where it is.
14772×
    if let Some(at) = repo.remote_only_location(&h)? {
14780×
        println!(
14790×
            "{}",
14800×
            ui::kv(
14810×
                "only in",
14820×
                ui::warn(format!(
14830×
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
14840×
                ))
14850×
            )
14860×
        );
14872×
    }
14882×
    let meta = oxy_core::state::ChangeMeta::of(&c);
14892×
    let status = repo.authenticate_change_known(&h, Some(&meta))?;
14902×
    println!("{}", ui::kv("author", ui::author(author_name(repo, &meta))));
14912×
    if let Some(agent) = via(repo, &status, &meta.author) {
14920×
        println!("{}", ui::kv("via", agent.line()));
14932×
    }
14942×
    println!(
1495
        "{}",
14962×
        ui::kv(
14972×
            "date",
14982×
            format!(
1499
                "{} {}",
15002×
                when(c.hlc.wall_ms),
15012×
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1502
            )
1503
        )
1504
    );
15052×
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
15062×
    println!("{}", ui::kv("sig", signature_line(repo, &h)?));
15072×
    println!();
15085×
    for line in (if c.message.is_empty() {
15090×
        "(no description)"
1510
    } else {
15112×
        &c.message
1512
    })
15132×
    .lines()
15145×
    {
15155×
        println!("    {line}");
15165×
    }
15172×
    println!();
15182×
    if stat {
15191×
        print_stat(&repo.diff_files(Some(&h))?);
1520
    } else {
15211×
        print!("{}", repo.describe_change(&h)?);
1522
    }
15232×
    Ok(0)
15243×
}
1525
15260×
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
15270×
    let repo = open()?;
1528
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1529
    // BRANCH` is: checking its files out under another bookmark's name
1530
    // made the next commit move the wrong bookmark (oxygen#60).
15310×
    if let [name] = changes {
15320×
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
15330×
            drop(repo);
15340×
            return bookmark_switch(name, discard, carry);
15350×
        }
15360×
    }
15370×
    let heads = if changes.is_empty() {
15380×
        repo.bookmark_heads()?
1539
    } else {
15400×
        let mut heads = Vec::new();
15410×
        for c in changes {
15420×
            heads.extend(repo.resolve_heads(c)?);
1543
        }
15440×
        heads
1545
    };
15460×
    let spec = if changes.is_empty() {
15470×
        repo.config.bookmark.clone()
1548
    } else {
15490×
        changes.join(" ")
1550
    };
15510×
    let sp = ui::spinner(&format!("Checking out {spec}…"));
15520×
    let command = format!("oxy checkout {spec}");
15530×
    let (r, carried) = if carry {
15540×
        repo.checkout_carry(&heads, &spec, &command)?
1555
    } else {
15560×
        (repo.checkout(&heads, discard, &command)?, vec![])
1557
    };
15580×
    sp.done(&format!(
1559
        "{} on {}: {} written, {} removed{}",
15600×
        ui::done("Working copy"),
15610×
        ui::bookmark(&spec),
15620×
        plural(r.written, "file"),
1563
        r.removed,
15640×
        if carried.is_empty() {
15650×
            String::new()
1566
        } else {
15670×
            format!("; carried {}", plural(carried.len(), "changed path"))
1568
        }
1569
    ));
15700×
    print_removed(&r);
15710×
    for n in &r.notes {
15720×
        println!("  {} {n}", ui::note());
15730×
    }
15740×
    print_kept_both(&r);
15750×
    if r.conflicted {
15760×
        println!(
15770×
            "  {} {}",
15780×
            ui::caution(),
15790×
            ui::warn("this state has conflicts; see oxy status")
15800×
        );
15810×
    }
15820×
    where_now(&repo);
15830×
    Ok(0)
15840×
}
1585
1586
/// Union files (`merge=union`, oxygen#145) a checkout settled itself.
15873×
fn print_kept_both(r: &oxy_core::repo::CheckoutReport) {
15883×
    for k in &r.kept_both {
15890×
        let how = if k.identical.len() == k.settled.len() {
15900×
            "kept one of its identical sides"
15910×
        } else if k.identical.is_empty() {
15920×
            "kept both sides (merge=union)"
1593
        } else {
15940×
            "kept one of identical sides and both of others (merge=union)"
1595
        };
15960×
        println!(
1597
            "  {} settled {}: {how}; the next commit records it",
15980×
            ui::note(),
15990×
            ui::path(&k.path)
1600
        );
1601
    }
16023×
}
1603
16041×
pub fn resolve(paths: &[String], both: bool, reverse: bool, as_json: bool) -> Result<i32> {
16051×
    let repo = open()?;
16061×
    let mut snap = repo.snapshot("oxy resolve")?;
16071×
    let paths: Vec<String> = paths
16081×
        .iter()
16091×
        .map(|p| p.trim_start_matches("./").trim_end_matches('/').to_string())
16101×
        .collect();
16111×
    if both {
1612
        // Adjacent insertions (oxygen#121): every side kept, in order.
16130×
        let kept = repo.keep_both(&snap, &paths, reverse)?;
16140×
        if !as_json {
16150×
            for k in &kept {
16160×
                if !k.settled.is_empty() {
16170×
                    let n: Vec<String> = k.settled.iter().map(|n| n.to_string()).collect();
16180×
                    println!("kept both  {}: conflict {}", k.path, n.join(", "));
16190×
                }
16200×
                for (n, why) in &k.left {
16210×
                    println!("markers    {}: conflict {n}: {why}", k.path);
16220×
                }
1623
            }
16240×
        }
16250×
        snap = repo.snapshot("oxy resolve")?;
16261×
    } else if !paths.is_empty() {
1627
        // A replace conflict has no markers to edit out: the user says which
1628
        // content wins (oxygen#140, spec §9.3), and the snapshot builds it.
16290×
        repo.choose_resolutions(&snap.base_snapshot, &paths)?;
16300×
        snap = repo.snapshot("oxy resolve")?;
16311×
    }
16321×
    if as_json {
16331×
        println!("{}", repo.status_json(&snap)?);
16341×
        return Ok(if snap.base_snapshot.is_conflicted() {
16350×
            2
1636
        } else {
16371×
            0
1638
        });
16390×
    }
16400×
    if !snap.base_snapshot.is_conflicted() {
16410×
        println!("The working copy's base has no conflicts.");
16420×
        return Ok(0);
16430×
    }
16440×
    let mut remaining = 0;
16450×
    for (p, f) in &snap.base_snapshot.files {
16460×
        if !f.is_conflicted() {
16470×
            continue;
16480×
        }
16490×
        match snap
16500×
            .statuses
16510×
            .iter()
16520×
            .find(|s| s.path == *p)
16530×
            .map(|s| s.status)
1654
        {
16550×
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
16560×
            Some(ChangeStatus::ConflictEdited) => {
16570×
                remaining += 1;
16580×
                println!("markers    {p}");
16590×
            }
16600×
            _ => {
16610×
                remaining += 1;
16620×
                println!("unresolved {p}");
16630×
            }
1664
        }
1665
    }
16660×
    for c in &snap.base_snapshot.tree.conflicts {
16670×
        remaining += 1;
16680×
        println!("tree       {c:?}");
16690×
    }
16700×
    if remaining == 0 {
16710×
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
16720×
        Ok(0)
1673
    } else {
16740×
        Ok(2)
1675
    }
16761×
}
1677
16780×
pub fn undo() -> Result<i32> {
16790×
    let repo = open()?;
16800×
    let u = repo.undo()?;
16810×
    println!("{} {}", ui::done("Undone:"), u.command);
16820×
    for c in &u.changes {
16830×
        println!("  {} {}", ui::note(), change_words(&repo, c));
16840×
    }
16850×
    if u.others_kept > 0 {
16860×
        let s = if u.others_kept == 1 { "" } else { "s" };
16870×
        println!(
1688
            "  {} {}",
16890×
            ui::note(),
16900×
            ui::dim(format!(
1691
                "{} newer operation{s} from other workspaces left as they are",
1692
                u.others_kept
1693
            ))
1694
        );
16950×
    }
16960×
    for (bookmark, remote) in &u.pushed {
16970×
        println!(
16980×
            "  {} {}",
16990×
            ui::caution(),
17000×
            ui::warn(format!(
17010×
                "{remote}/{bookmark} already has what this undid: undone here only; the next push of {bookmark} needs --force to take it back there"
17020×
            ))
17030×
        );
17040×
    }
17050×
    where_now(&repo);
17060×
    Ok(0)
17070×
}
1708
17091×
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
17101×
    let repo = open()?;
17111×
    let ops = repo.op_log()?;
1712
    // What each operation changed, against the one before it.
171311×
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
171411×
        match ops.get(i + 1) {
171510×
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
17161×
            None => Ok(vec![]),
1717
        }
171811×
    };
17191×
    if as_json {
17201×
        let mut items = Vec::new();
172111×
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
172211×
            let summary: Vec<String> = changes_of(i)?
172311×
                .iter()
172411×
                .map(|c| change_words(&repo, c))
172511×
                .collect();
172611×
            items.push(json::obj([
172711×
                ("id", json::s(&r.to_hex())),
172811×
                ("when_ms", json::n(op.hlc.wall_ms)),
172911×
                ("command", json::s(&op.command)),
173011×
                ("snapshot", json::b(op.is_snapshot())),
173111×
                ("current", json::b(i == 0)),
173211×
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1733
            ]));
1734
        }
17351×
        println!("{}", json::arr(items));
17361×
        return Ok(0);
17370×
    }
17380×
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
17390×
    let id = |r: &oxy_core::hash::ObjectRef| {
17400×
        let hex = r.to_hex();
17410×
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
17420×
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
17430×
    };
17440×
    let rail = ui::dim(ui::glyph("│", "|"));
17450×
    let (mut i, mut shown) = (0, 0);
17460×
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
17470×
        let (r, op) = &ops[i];
17480×
        let bullet = if i == 0 {
17490×
            ui::ok(ui::glyph("@", "@"))
1750
        } else {
17510×
            ui::dim(ui::glyph("○", "o"))
1752
        };
1753
        // A run of snapshots folds into one entry.
17540×
        let mut run = 1;
17550×
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
17560×
            run += 1;
17570×
        }
17580×
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
17590×
        if op.is_snapshot() {
17600×
            let span = if run > 1 {
17610×
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1762
            } else {
17630×
                String::new()
1764
            };
17650×
            println!(
1766
                "{bullet}  {}{} {when}",
17670×
                id(r),
17680×
                if span.is_empty() {
17690×
                    String::new()
1770
                } else {
17710×
                    format!(" {span}")
1772
                }
1773
            );
17740×
            println!(
1775
                "{rail}  {}",
17760×
                ui::dim(if run == 1 {
17770×
                    "working-copy snapshot".to_string()
1778
                } else {
17790×
                    format!("{run} working-copy snapshots")
1780
                })
1781
            );
1782
        } else {
17830×
            println!("{bullet}  {} {when}", id(r));
17840×
            let words: Vec<String> = changes_of(i)?
17850×
                .iter()
17860×
                .map(|c| change_words(&repo, c))
17870×
                .collect();
17880×
            let summary = if words.is_empty() {
17890×
                if i + 1 == ops.len() {
17900×
                    "created the repository".to_string()
1791
                } else {
17920×
                    "no bookmark or working-copy change".to_string()
1793
                }
1794
            } else {
17950×
                words.join("; ")
1796
            };
17970×
            println!(
1798
                "{rail}  {}",
17990×
                if i == 0 {
18000×
                    ui::subject(&summary)
1801
                } else {
18020×
                    summary
1803
                }
1804
            );
18050×
            let cmd = op.command.lines().next().unwrap_or("");
18060×
            let cmd: String = cmd.chars().take(100).collect();
18070×
            println!("{rail}  {}", ui::dim(cmd));
1808
        }
18090×
        i += run;
18100×
        shown += 1;
1811
    }
18120×
    if i < ops.len() {
18130×
        println!(
18140×
            "{}",
18150×
            ui::dim(format!(
18160×
                "{} {} older; pass -n to see more",
18170×
                ui::glyph("…", "..."),
18180×
                plural(ops.len() - i, "operation")
18190×
            ))
18200×
        );
18210×
    }
18220×
    Ok(0)
18231×
}
1824
1825
/// One change an operation made, in words.
182611×
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1827
    use oxy_core::repo::ViewChange::*;
18282×
    match c {
18290×
        BookmarkCreated { name, heads } => {
18300×
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1831
        }
18320×
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
18332×
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
18341×
        BookmarkMoved { name, from, to } => format!(
1835
            "{name}: {from} {} {}",
18361×
            ui::glyph("→", "->"),
18371×
            plural(*to, "head")
1838
        ),
18391×
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
18400×
        TagCreated { name } => format!("tagged {name}"),
18410×
        TagDeleted { name } => format!("removed tag {name}"),
18420×
        Policy => "trust policy changed".to_string(),
18438×
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
18448×
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
18450×
            Err(_) => "working copy moved".to_string(),
1846
        },
1847
    }
184811×
}
1849
18500×
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
18510×
    let repo = open()?;
18520×
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
18530×
    let r = repo.op_restore(op, discard)?;
18540×
    sp.done(&format!(
18550×
        "{} to operation {} {}",
18560×
        ui::done("Restored"),
18570×
        ui::hash(r.op.short(12)),
18580×
        ui::dim(r.command.lines().next().unwrap_or(""))
18590×
    ));
18600×
    println!(
1861
        "  {} {}",
18620×
        ui::note(),
18630×
        ui::dim(format!(
1864
            "{} written, {} removed; oxy undo goes back again",
18650×
            plural(r.checkout.written, "file"),
1866
            r.checkout.removed
1867
        ))
1868
    );
18690×
    where_now(&repo);
18700×
    Ok(0)
18710×
}
1872
18730×
pub fn op_revert(op: &str) -> Result<i32> {
18740×
    let repo = open()?;
18750×
    let r = repo.op_revert(op)?;
18760×
    let view = repo.view()?;
18770×
    let names: Vec<String> = r
18780×
        .reverted
18790×
        .iter()
18800×
        .map(|n| {
18810×
            if view.bookmarks.contains_key(n) {
18820×
                ui::bookmark(n)
1883
            } else {
18840×
                format!("{} (removed)", ui::bookmark(n))
1885
            }
18860×
        })
18870×
        .collect();
18880×
    println!(
1889
        "{} operation {} {}",
18900×
        ui::done("Reverted"),
18910×
        ui::hash(r.op.short(12)),
18920×
        ui::dim(r.command.lines().next().unwrap_or(""))
1893
    );
18940×
    println!(
1895
        "  {} {}",
18960×
        ui::note(),
18970×
        ui::dim(format!("as before it: {}", names.join(", ")))
1898
    );
18990×
    if !r.kept.is_empty() {
19000×
        println!(
19010×
            "  {} {}",
19020×
            ui::caution(),
19030×
            ui::warn(format!(
19040×
                "left as they are, having moved again since: {}",
19050×
                r.kept.join(", ")
19060×
            ))
19070×
        );
19080×
    }
19090×
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
19100×
        println!(
19110×
            "  {} {}",
19120×
            ui::note(),
19130×
            ui::dim("the working copy has work of its own: oxy checkout to move it")
19140×
        );
19150×
    }
19160×
    where_now(&repo);
19170×
    Ok(0)
19180×
}
1919
1920
/// Where the working copy and bookmark are now, after a command moved
1921
/// them (as jj says "Working copy now at").
192241×
pub fn where_now(repo: &Repo) {
192341×
    let Ok((_, wc)) = repo.working_copy() else {
19240×
        return;
1925
    };
192641×
    let heads = repo.bookmark_heads().unwrap_or_default();
192741×
    let newest = heads
192841×
        .iter()
192955×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
193041×
        .max_by_key(|(m, _)| m.hlc);
193141×
    println!(
1932
        "  {} {}",
193341×
        ui::dim(format!("{:<13}", "Working copy")),
193441×
        ui::id(wc.change_id.short(8))
1935
    );
193641×
    let tail = match newest {
193741×
        Some((m, _)) => format!(
1938
            ", newest {} {}",
193941×
            ui::id(m.change_id.short(8)),
194041×
            subject_of(&m.message)
1941
        ),
19420×
        None => String::new(),
1943
    };
194441×
    println!(
1945
        "  {} {}: {}{tail}",
194641×
        ui::dim(format!("{:<13}", "Bookmark")),
194741×
        ui::bookmark(&repo.config.bookmark),
194841×
        plural(heads.len(), "head")
1949
    );
195041×
}
1951
19521×
pub fn gc(now: bool, expire_snapshots: bool) -> Result<i32> {
19531×
    let mut repo = open()?;
19541×
    if expire_snapshots {
19550×
        repo.config.snapshot_retention_days = 0;
19561×
    }
19571×
    let sp = ui::spinner("Packing and pruning…");
1958
    // Cylinder's artifacts are named from outside the history: keep them.
19591×
    let artifacts = cylinder::roots(&repo)?;
19605×
    let r = repo.gc_keeping(now, &artifacts, &mut |phase| sp.set(&format!("{phase}…")))?;
19611×
    sp.clear();
19621×
    if r.packed.objects > 0 {
19631×
        println!(
19641×
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
19651×
            plural(r.packed.objects, "object"),
19661×
            r.packed.raw_bytes,
19671×
            r.packed.packed_bytes,
19681×
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
19691×
        );
19701×
    }
19711×
    println!(
1972
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
19731×
        plural(r.reachable, "object"),
19741×
        plural(r.pruned.objects, "unreachable object"),
1975
        r.pruned.bytes,
19761×
        if r.pruned.deferred > 0 {
19770×
            format!(
1978
                "; {} deferred by the grace period (use --now)",
19790×
                plural(r.pruned.deferred, "object")
1980
            )
1981
        } else {
19821×
            String::new()
1983
        },
19841×
        if r.merged_packs > 0 {
19850×
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1986
        } else {
19871×
            String::new()
1988
        },
19891×
        plural(repo.store().pack_count(), "pack")
1990
    );
1991
    // What earlier repacks replaced stays an hour for readers still using
1992
    // it (oxygenhub#249); a collection after that deletes it.
19931×
    let kept = if r.retired.kept > 0 {
19940×
        format!(
1995
            "{} retired less than an hour ago kept for readers",
19960×
            plural(r.retired.kept, "file")
1997
        )
1998
    } else {
19991×
        String::new()
2000
    };
20011×
    if r.retired.packs + r.retired.loose > 0 {
20020×
        println!(
2003
            "Deleted {} and {} retired by earlier repacks{}.",
20040×
            plural(r.retired.packs, "pack"),
20050×
            plural(r.retired.loose, "loose object"),
20060×
            if kept.is_empty() {
20070×
                String::new()
2008
            } else {
20090×
                format!("; {kept}")
2010
            }
2011
        );
20121×
    } else if !kept.is_empty() {
20130×
        println!("{kept}.");
20141×
    }
20151×
    Ok(0)
20161×
}
2017
2018
/// `oxy gc --remote NAME`: fold a store remote's bundles into one.
20192×
pub fn gc_remote(name: &str, now: bool) -> Result<i32> {
20202×
    let repo = open()?;
20212×
    let sp = ui::spinner(&format!("Folding {name}'s bundles…"));
20222×
    let r = repo.gc_remote(name, now)?;
20231×
    sp.clear();
20241×
    if r.merged > 0 {
20251×
        println!(
20261×
            "{} {} into one of {} bytes ({})",
20271×
            ui::done("Folded"),
20281×
            plural(r.merged, "bundle"),
20291×
            r.bundle_bytes,
20301×
            plural(r.changes, "change")
20311×
        );
20321×
    } else {
20330×
        println!(
20340×
            "{} {}",
20350×
            ui::note(),
20360×
            ui::dim("nothing to fold: one bundle holds everything")
20370×
        );
20380×
    }
20391×
    println!(
2040
        "  {} {}",
20411×
        ui::note(),
20421×
        ui::dim(format!(
2043
            "removed {}{}",
20441×
            plural(r.deleted, "superseded bundle"),
20451×
            if r.deferred > 0 {
20460×
                format!(
2047
                    "; {} kept for readers that may still fetch them (use --now)",
20480×
                    plural(r.deferred, "bundle")
2049
                )
2050
            } else {
20511×
                String::new()
2052
            }
2053
        ))
2054
    );
20551×
    Ok(0)
20562×
}
2057
2058
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
20590×
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
2060
    use oxy_core::repo::Health;
20610×
    let repo = open()?;
20620×
    let sp = ui::spinner(if offline {
20630×
        "Checking…"
2064
    } else {
20650×
        "Checking, and contacting remotes…"
2066
    });
20670×
    let r = repo.doctor(!offline);
20680×
    sp.clear();
20690×
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
20700×
    let word = |h: Health| match h {
20710×
        Health::Ok => "ok",
20720×
        Health::Warn => "warning",
20730×
        Health::Fail => "fail",
20740×
    };
20750×
    if as_json {
20760×
        let checks: Vec<String> = r
20770×
            .checks
20780×
            .iter()
20790×
            .map(|c| {
20800×
                json::obj([
20810×
                    ("area", json::s(&c.area)),
20820×
                    ("health", json::s(word(c.health))),
20830×
                    ("message", json::s(&c.message)),
20840×
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
20850×
                ])
20860×
            })
20870×
            .collect();
20880×
        println!(
2089
            "{}",
20900×
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
2091
        );
20920×
        return Ok(code);
20930×
    }
20940×
    let mut last = "";
20950×
    for c in &r.checks {
20960×
        if c.area != last {
20970×
            println!("{}", ui::section(&c.area));
20980×
            last = &c.area;
20990×
        }
21000×
        let mark = match c.health {
21010×
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
21020×
            Health::Warn => ui::caution(),
21030×
            Health::Fail => ui::err(ui::glyph("✖", "x")),
2104
        };
21050×
        println!("  {mark} {}", c.message);
21060×
        if let Some(h) = &c.hint {
21070×
            println!("    {} {}", ui::dim("→"), ui::dim(h));
21080×
        }
2109
    }
21100×
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
21110×
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
21120×
    if fails + warns == 0 {
21130×
        println!("{}", ui::done("Everything looks right."));
21140×
    } else {
21150×
        println!(
2116
            "{} {}, {}.",
21170×
            if fails > 0 {
21180×
                ui::err(ui::glyph("✖", "x"))
2119
            } else {
21200×
                ui::caution()
2121
            },
21220×
            plural(fails, "problem"),
21230×
            plural(warns, "warning")
2124
        );
2125
    }
21260×
    Ok(code)
21270×
}
2128
2129
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
21300×
pub fn fsck(as_json: bool) -> Result<i32> {
2131
    use oxy_core::repo::Severity;
21320×
    let repo = open()?;
21330×
    let sp = ui::spinner("Checking every object…");
21340×
    let r = repo.fsck()?;
21350×
    sp.clear();
21360×
    let code = if r.errors() > 0 { 1 } else { 0 };
21370×
    if as_json {
21380×
        let problems: Vec<String> = r
21390×
            .problems
21400×
            .iter()
21410×
            .map(|p| {
21420×
                json::obj([
2143
                    (
2144
                        "severity",
21450×
                        json::s(match p.severity {
21460×
                            Severity::Error => "error",
21470×
                            Severity::Warning => "warning",
2148
                        }),
2149
                    ),
2150
                    (
21510×
                        "object",
21520×
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
2153
                    ),
21540×
                    ("what", json::s(&p.what)),
2155
                ])
21560×
            })
21570×
            .collect();
21580×
        println!(
2159
            "{}",
21600×
            json::obj([
21610×
                ("ok", json::b(code == 0)),
21620×
                ("objects", json::n(r.objects)),
21630×
                ("ops", json::n(r.ops)),
21640×
                ("changes", json::n(r.changes)),
21650×
                ("signed", json::n(r.signed)),
21660×
                ("unsigned", json::n(r.unsigned)),
21670×
                ("checkpoints", json::n(r.checkpoints)),
21680×
                ("attestations", json::n(r.attestations)),
21690×
                ("errors", json::n(r.errors())),
21700×
                ("warnings", json::n(r.warnings())),
21710×
                ("problems", json::arr(problems)),
21720×
            ])
2173
        );
21740×
        return Ok(code);
21750×
    }
21760×
    println!(
2177
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
21780×
        plural(r.objects, "object"),
21790×
        plural(r.ops, "operation"),
21800×
        plural(r.changes, "change"),
2181
        r.signed,
2182
        r.unsigned,
21830×
        plural(r.checkpoints, "checkpoint"),
21840×
        plural(r.attestations, "attestation"),
2185
    );
21860×
    for p in &r.problems {
21870×
        let obj = p
21880×
            .object
21890×
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
21900×
            .unwrap_or_default();
21910×
        match p.severity {
21920×
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
21930×
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
2194
        }
2195
    }
21960×
    if r.problems.is_empty() {
21970×
        println!("{}", ui::done("No problems found."));
21980×
    } else if code == 0 {
21990×
        println!(
22000×
            "{}",
22010×
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
22020×
        );
22030×
    } else {
22040×
        println!(
22050×
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
22060×
            ui::err(ui::glyph("✖", "x")),
22070×
            plural(r.errors(), "error"),
22080×
            plural(r.warnings(), "warning")
22090×
        );
22100×
    }
22110×
    Ok(code)
22120×
}
2213
2214
/// The head the working copy sits on, for commands that default to it. With
2215
/// several heads beneath the working copy, the most recently made one is
2216
/// chosen and announced.
22170×
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
22180×
    let snap = repo.snapshot_status("oxy")?;
22190×
    let base = snap.base.maximal(&snap.wc.deps);
22200×
    match base.as_slice() {
22210×
        [] => anyhow::bail!("the working copy sits on no change yet"),
22220×
        [h] => Ok(*h),
22230×
        many => {
22240×
            let latest = many
22250×
                .iter()
22260×
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
22270×
                .copied()
22280×
                .unwrap();
22290×
            let c = repo.store().get_change(&latest)?;
22300×
            println!(
2231
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
22320×
                short_id(&c),
22330×
                latest.short(12),
22340×
                many.len()
2235
            );
22360×
            Ok(latest)
2237
        }
2238
    }
22390×
}
2240
2241
/// `oxy describe` without -m: the working copy's name for a build.
22424×
pub fn describe_name(as_json: bool) -> Result<i32> {
22434×
    let repo = open()?;
22444×
    let d = repo.describe_working_copy()?;
22454×
    if as_json {
22463×
        println!(
2247
            "{}",
22483×
            json::obj([
22493×
                ("describe", json::s(&d.line())),
22503×
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
22513×
                ("distance", json::n(d.distance)),
22523×
                ("bookmark", json::s(&d.bookmark)),
22533×
                ("change", json::s(&d.change.to_hex())),
22543×
                ("hash", json::s(&d.hash.to_hex())),
22553×
                ("dirty", json::b(d.dirty)),
2256
            ])
2257
        );
22581×
    } else {
22591×
        println!("{}", d.line());
22601×
    }
22614×
    Ok(0)
22624×
}
2263
22640×
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
22650×
    let repo = open()?;
22660×
    let h = match change {
22670×
        Some(c) => repo.resolve_change(c)?,
22680×
        None => current_head(&repo)?,
2269
    };
22700×
    let new = repo.describe(&h, message)?;
22710×
    let c = repo.store().get_change_meta(&new)?;
22720×
    println!(
2273
        "{} {} {}  {}",
22740×
        ui::done("Described"),
22750×
        ui::id(c.change_id.short(8)),
22760×
        ui::hash(format!("#{}", new.short(12))),
22770×
        ui::subject(subject_of(message))
2278
    );
22790×
    Ok(0)
22800×
}
2281
22820×
pub fn amend(message: Option<&str>, into: Option<&str>, paths: &[String]) -> Result<i32> {
22830×
    let repo = open()?;
22840×
    let before = repo.view()?;
22850×
    let new = match into {
22860×
        Some(spec) => {
22870×
            let target = repo.resolve_change(spec)?;
22880×
            repo.amend_into(&target, message)?
2289
        }
22900×
        None if !paths.is_empty() => repo.amend_paths(message, paths)?,
22910×
        None => repo.amend(message)?,
2292
    };
22930×
    let c = repo.store().get_change_meta(&new)?;
22940×
    println!(
2295
        "{} {} {}  {}",
22960×
        ui::done("Amended"),
22970×
        ui::id(c.change_id.short(8)),
22980×
        ui::hash(format!("#{}", new.short(12))),
22990×
        ui::subject(subject_of(&c.message))
2300
    );
2301
    // Rewriting what a remote already has means the next push replaces it
2302
    // there (oxygen#99): say so now, not when the push is refused.
23030×
    let bookmark = repo.config.bookmark.clone();
23040×
    let (had, has) = (
23050×
        repo.heads_of(&before, &bookmark)?,
23060×
        repo.heads_of(&repo.view()?, &bookmark)?,
2307
    );
23080×
    for (remote, bookmarks) in &before.remotes {
23090×
        let Some(st) = bookmarks.get(&bookmark) else {
23100×
            continue;
2311
        };
23120×
        let theirs = repo.store().get_state(st)?.heads;
23130×
        if theirs.iter().any(|h| had.contains(h) && !has.contains(h)) {
23140×
            println!(
23150×
                "  {} {}",
23160×
                ui::caution(),
23170×
                ui::warn(format!(
23180×
                    "{remote}/{bookmark} has the change as it was: the next push of {bookmark} needs --force to replace it"
23190×
                ))
23200×
            );
23210×
        }
2322
    }
23230×
    where_now(&repo);
23240×
    Ok(0)
23250×
}
2326
23270×
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
23280×
    let repo = open()?;
23290×
    let Some(r) = revset else {
23300×
        let h = repo.resolve_change(change.unwrap_or_default())?;
23310×
        abandon_one(&repo, h)?;
23320×
        where_now(&repo);
23330×
        return Ok(0);
2334
    };
2335
    // A revset: say what it selects, refuse an empty set, ask above a few.
23360×
    let selected = repo.revset(r)?;
23370×
    let wc = repo.working_copy().ok().map(|(h, _)| h);
23380×
    let hashes: Vec<ChangeHash> = selected
23390×
        .hashes
23400×
        .iter()
23410×
        .copied()
23420×
        .filter(|h| Some(*h) != wc)
23430×
        .collect();
23440×
    if hashes.is_empty() {
23450×
        anyhow::bail!("{r:?} selects no change to abandon");
23460×
    }
23470×
    println!(
2348
        "{} {} selects {}:",
23490×
        ui::section("abandon"),
23500×
        ui::id(r),
23510×
        plural(hashes.len(), "change")
2352
    );
23530×
    for h in &hashes {
23540×
        if let Some(m) = selected.metas.get(h) {
23550×
            println!(
23560×
                "  {} {}  {}",
23570×
                ui::id(m.change_id.short(8)),
23580×
                ui::hash(format!("#{}", h.short(12))),
23590×
                subject_of(&m.message)
23600×
            );
23610×
        }
2362
    }
2363
    const ASK_ABOVE: usize = 5;
23640×
    if hashes.len() > ASK_ABOVE && !yes {
23650×
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
23660×
    }
2367
    // Newest first: abandoning a change rewrites what depends on it, so a
2368
    // later member is found again by its ChangeId.
23690×
    let mut done = 0;
23700×
    for h in &hashes {
23710×
        let Some(m) = selected.metas.get(h) else {
23720×
            continue;
2373
        };
23740×
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
23750×
            Ok(h) => h,
23760×
            Err(_) => continue,
2377
        };
23780×
        abandon_one(&repo, now)?;
23790×
        done += 1;
2380
    }
23810×
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
23820×
    where_now(&repo);
23830×
    Ok(0)
23840×
}
2385
23860×
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
23870×
    let c = repo.store().get_change_meta(&h)?;
23880×
    let notes = repo.abandon(&h)?;
23890×
    println!(
2390
        "{} {} {}  {}",
23910×
        ui::done("Abandoned"),
23920×
        ui::id(c.change_id.short(8)),
23930×
        ui::hash(format!("#{}", h.short(12))),
23940×
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
2395
    );
23960×
    for n in notes {
23970×
        println!("  {} {n}", ui::note());
23980×
    }
23990×
    Ok(())
24000×
}
2401
24020×
pub fn checkpoint() -> Result<i32> {
24030×
    let repo = open()?;
24040×
    let sp = ui::spinner("Writing checkpoint…");
24050×
    let (r, changes, bytes) = repo.checkpoint()?;
24060×
    sp.done(&format!(
24070×
        "{} {} of {} ({} bytes) for {}",
24080×
        ui::done("Checkpoint"),
24090×
        ui::hash(format!("#{}", r.short(12))),
24100×
        plural(changes, "change"),
24110×
        bytes,
24120×
        ui::id(&repo.config.bookmark)
24130×
    ));
24140×
    Ok(0)
24150×
}
2416
2417
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
24180×
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
24190×
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
24200×
        return Ok(1);
2421
    };
24220×
    let info = repo.quick_status()?;
24230×
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
24240×
        oxy_core::repo::GLYPH_PROMPT_FORMAT
2425
    } else {
24260×
        format
2427
    };
24280×
    let line = match color {
24290×
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
24300×
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
24310×
        Some(_) => info.format_colored(fmt, ("", "")),
24320×
        None => info.format(fmt),
2433
    };
24340×
    println!("{line}");
24350×
    Ok(0)
24360×
}
2437
24380×
pub fn sparse(paths: &[String]) -> Result<i32> {
24390×
    let mut repo = open()?;
24400×
    if paths.is_empty() {
24410×
        if repo.config.sparse_paths.is_empty() {
24420×
            println!("No sparse filter: the whole tree is materialized.");
24430×
        } else {
24440×
            println!("{}", ui::heading("Sparse filter"));
24450×
            for p in &repo.config.sparse_paths {
24460×
                println!("  {}", ui::path(p));
24470×
            }
2448
        }
24490×
        return Ok(0);
24500×
    }
24510×
    let snap = repo.snapshot("oxy sparse")?;
24520×
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
24530×
        anyhow::bail!(
2454
            "the working copy has changes; commit them before changing the sparse filter"
2455
        );
24560×
    }
24570×
    repo.config.set("filter.paths", &paths.join(","))?;
24580×
    repo.save_config()?;
24590×
    let heads = repo.bookmark_heads()?;
24600×
    let sp = ui::spinner("Re-checking out with the new filter…");
24610×
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
24620×
    sp.done(&format!(
24630×
        "{} {}: {} written, {} removed",
24640×
        ui::done("Sparse filter set to"),
24650×
        ui::path(paths.join(",")),
24660×
        plural(r.written, "file"),
24670×
        r.removed
24680×
    ));
24690×
    Ok(0)
24700×
}
2471
24722×
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
24732×
    let repo = open()?;
24742×
    repo.snapshot_status("oxy tag")?;
24752×
    let heads = if changes.is_empty() {
24762×
        repo.bookmark_heads()?
2477
    } else {
24780×
        let mut heads = Vec::new();
24790×
        for c in changes {
24800×
            heads.extend(repo.resolve_heads(c)?);
2481
        }
24820×
        heads
2483
    };
24842×
    let t = repo.tag_create(name, &heads, message)?;
24852×
    println!(
2486
        "{} {} {} {} ({}){}",
24872×
        ui::done("Tagged"),
24882×
        ui::bookmark(&t.name),
24892×
        ui::dim(ui::glyph("→", "->")),
24902×
        ui::hash(format!("#{}", t.state.short(12))),
24912×
        plural(t.heads.len(), "head"),
24922×
        t.signer
24932×
            .map(|s| format!(", signed by {s}"))
24942×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2495
    );
24962×
    Ok(0)
24972×
}
2498
24990×
pub fn tag_delete(name: &str, reason: &str) -> Result<i32> {
25000×
    let repo = open()?;
25010×
    let t = repo.tag_delete(name, reason)?;
25020×
    println!(
2503
        "{} {} {} {}{}",
25040×
        ui::done("Withdrew"),
25050×
        ui::bookmark(&t.name),
25060×
        ui::dim(ui::glyph("→", "->")),
25070×
        ui::hash(format!("#{}", t.state.short(12))),
25080×
        t.signer
25090×
            .map(|s| format!(", signed by {s}"))
25100×
            .unwrap_or_else(|| ui::dim(", unsigned"))
2511
    );
25120×
    println!(
2513
        "  {} {}",
25140×
        ui::note(),
25150×
        ui::dim("`oxy push` sends the withdrawal to a remote that has the tag; the name is not used again")
2516
    );
25170×
    Ok(0)
25180×
}
2519
25201×
pub fn tag_list(as_json: bool) -> Result<i32> {
25211×
    let repo = open()?;
25221×
    let tags = repo.tags()?;
25231×
    if as_json {
25241×
        println!(
2525
            "{}",
25261×
            json::arr(tags.iter().map(|t| {
25271×
                json::obj([
25281×
                    ("name", json::s(&t.name)),
25291×
                    ("state", json::s(&t.state.to_hex())),
25301×
                    ("heads", json::hashes(&t.heads)),
25311×
                    ("message", json::s(&t.message)),
2532
                    (
25331×
                        "signer",
25341×
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2535
                    ),
2536
                ])
25371×
            }))
2538
        );
25391×
        return Ok(0);
25400×
    }
25410×
    if tags.is_empty() {
25420×
        println!("{}", ui::dim("No tags."));
25430×
    }
25440×
    for t in tags {
25450×
        println!(
2546
            "{} {} {}{}{}{}",
25470×
            ui::ok(ui::glyph("⚑", "#")),
25480×
            ui::bookmark(&t.name),
2549
            // The heads, as `oxy log` shows changes, not the state hash.
25500×
            ui::hash(
25510×
                t.heads
25520×
                    .iter()
25530×
                    .map(|h| format!("#{}", h.short(12)))
25540×
                    .collect::<Vec<_>>()
25550×
                    .join(" ")
2556
            ),
25570×
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
25580×
            if t.message.is_empty() {
25590×
                String::new()
2560
            } else {
25610×
                format!("  {}", ui::subject(subject_of(&t.message)))
2562
            },
25630×
            t.signer
25640×
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
25650×
                .unwrap_or_default()
2566
        );
2567
    }
25680×
    Ok(0)
25691×
}
2570
2571
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2572
/// and workspace add take as "be on this bookmark" (oxygen#60).
25730×
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
25740×
    Ok(repo.view()?.bookmarks.contains_key(name)
25750×
        || repo
25760×
            .remote_only_bookmarks()?
25770×
            .iter()
25780×
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
25790×
}
2580
25810×
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
25820×
    let repo = open()?;
2583
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2584
    // this workspace's bookmark with that one's files.
25850×
    if let [name] = changes {
25860×
        if names_bookmark(&repo, name)? {
25870×
            let (local, _) = repo.local_bookmark_for(name)?;
25880×
            let heads = repo.resolve_heads(&local)?;
25890×
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
25900×
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
25910×
            sp.done(&format!(
25920×
                "{} {} (workspace {}) on {}",
25930×
                ui::done("Workspace created at"),
25940×
                ui::path(ws.root().display()),
25950×
                ui::id(ws.workspace().short(8)),
25960×
                ui::bookmark(&local)
25970×
            ));
25980×
            return Ok(0);
25990×
        }
26000×
    }
26010×
    let heads = if changes.is_empty() {
26020×
        None
2603
    } else {
26040×
        let mut heads = Vec::new();
26050×
        for c in changes {
26060×
            heads.extend(repo.resolve_heads(c)?);
2607
        }
26080×
        Some(heads)
2609
    };
26100×
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
26110×
    let ws = repo.workspace_add(path, heads.as_deref())?;
26120×
    sp.done(&format!(
26130×
        "{} {} (workspace {})",
26140×
        ui::done("Workspace created at"),
26150×
        ui::path(ws.root().display()),
26160×
        ui::id(ws.workspace().short(8))
26170×
    ));
26180×
    Ok(0)
26190×
}
2620
26211×
pub fn workspace_list(as_json: bool) -> Result<i32> {
26221×
    let repo = open()?;
26231×
    if as_json {
26241×
        println!(
2625
            "{}",
26261×
            json::arr(repo.workspaces()?.iter().map(|w| {
26271×
                json::obj([
26281×
                    ("id", json::s(&w.id.to_hex())),
26291×
                    ("path", json::s(&w.path.to_string_lossy())),
26301×
                    ("current", json::b(w.current)),
2631
                    (
26321×
                        "working_copy",
26331×
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2634
                    ),
2635
                ])
26361×
            }))
2637
        );
26381×
        return Ok(0);
26390×
    }
26400×
    for w in repo.workspaces()? {
26410×
        println!(
2642
            "{} {} {}{}",
26430×
            if w.current {
26440×
                ui::ok(ui::glyph("●", "*"))
2645
            } else {
26460×
                ui::dim(ui::glyph("○", "o"))
2647
            },
26480×
            ui::id(w.id.short(8)),
26490×
            ui::path(w.path.display()),
26500×
            w.working_copy
26510×
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
26520×
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2653
        );
2654
    }
26550×
    Ok(0)
26561×
}
2657
26580×
pub fn workspace_forget(spec: &str) -> Result<i32> {
26590×
    let repo = open()?;
26600×
    let all = repo.workspaces()?;
26610×
    let target = std::fs::canonicalize(spec).ok();
26620×
    let matches: Vec<_> = all
26630×
        .iter()
26640×
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
26650×
        .collect();
26660×
    let w = match matches.as_slice() {
26670×
        [w] => *w,
26680×
        [] => anyhow::bail!("no workspace matches {spec:?}"),
26690×
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2670
    };
26710×
    repo.workspace_forget(&w.id)?;
26720×
    println!(
2673
        "{} workspace {} at {}; its files were left in place.",
26740×
        ui::done("Forgot"),
26750×
        ui::id(w.id.short(8)),
26760×
        ui::path(w.path.display())
2677
    );
26780×
    Ok(0)
26790×
}
2680
26810×
pub fn lock(path: &str) -> Result<i32> {
26820×
    let repo = open()?;
26830×
    repo.lock_path(path)?;
26840×
    println!(
2685
        "{} {} {}",
26860×
        ui::done("Locked"),
26870×
        ui::path(path),
26880×
        ui::dim("(advisory, local)")
2689
    );
26900×
    Ok(0)
26910×
}
2692
26930×
pub fn unlock(path: &str) -> Result<i32> {
26940×
    let repo = open()?;
26950×
    repo.unlock_path(path)?;
26960×
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
26970×
    Ok(0)
26980×
}
2699
27000×
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
27010×
    let repo = open()?;
27020×
    let h = repo.resolve_change(change)?;
27030×
    let (h1, h2) = repo.split(&h, paths)?;
27040×
    let c1 = repo.store().get_change_meta(&h1)?;
27050×
    let c2 = repo.store().get_change_meta(&h2)?;
27060×
    println!(
2707
        "{} into {} {} and {} {}",
27080×
        ui::done("Split"),
27090×
        ui::id(c1.change_id.short(8)),
27100×
        ui::hash(format!("#{}", h1.short(12))),
27110×
        ui::id(c2.change_id.short(8)),
27120×
        ui::hash(format!("#{}", h2.short(12)))
2713
    );
27140×
    Ok(0)
27150×
}
2716
27176×
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
27186×
    let mut heads = Vec::new();
27196×
    for c in changes {
27206×
        heads.extend(repo.resolve_heads(c)?);
2721
    }
27226×
    Ok(heads)
27236×
}
2724
27256×
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
27266×
    let repo = open()?;
27276×
    repo.snapshot_status("oxy bookmark create")?;
27286×
    let heads = if changes.is_empty() {
27293×
        None
2730
    } else {
27313×
        let named = heads_from(&repo, changes)?;
27323×
        let (_, wc) = repo.working_copy()?;
27333×
        let gap = repo.state_gap(&wc.deps, &named)?;
27343×
        if upto {
27351×
            Some(gap.upto)
27362×
        } else if only || gap.earlier.is_empty() {
27371×
            Some(named)
2738
        } else {
27391×
            anyhow::bail!(
2740
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2741
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2742
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2743
                 or --only for just {0} and what it depends on.",
27441×
                changes.join(" "),
27451×
                plural(gap.earlier.len(), "change"),
27461×
                listed_changes(&repo, &gap.earlier)
2747
            );
2748
        }
2749
    };
27505×
    let heads = repo.bookmark_create(name, heads.as_deref())?;
27515×
    println!(
2752
        "{} bookmark {} {} {}",
27535×
        ui::done("Created"),
27545×
        ui::bookmark(name),
27555×
        ui::dim(ui::glyph("→", "->")),
27565×
        ui::dim(plural(heads.len(), "head"))
2757
    );
27585×
    println!(
2759
        "  {} {}",
27605×
        ui::note(),
27615×
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2762
    );
27635×
    Ok(0)
27646×
}
2765
2766
/// Up to five changes, newest last, as `  #hash subject` lines.
27672×
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
27682×
    let shown = changes.len().min(5);
27692×
    let mut lines: Vec<String> = changes[changes.len() - shown..]
27702×
        .iter()
27712×
        .map(|h| {
27722×
            let subject = repo
27732×
                .store()
27742×
                .get_change(h)
27752×
                .map(|c| subject_of(&c.message).to_string())
27762×
                .unwrap_or_default();
27772×
            format!("  #{} {subject}", h.short(12))
27782×
        })
27792×
        .collect();
27802×
    if changes.len() > shown {
27810×
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
27822×
    }
27832×
    lines.join("\n")
27842×
}
2785
27863×
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
27873×
    let repo = open()?;
27883×
    repo.snapshot_status("oxy bookmark set")?;
27893×
    let named = heads_from(&repo, changes)?;
2790
    // What the bookmark holds now and the new heads would leave out.
27913×
    let current = repo
27923×
        .bookmarks()?
27933×
        .into_iter()
27946×
        .find(|b| b.name == name)
27953×
        .map(|b| b.heads)
27963×
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
27973×
    let gap = repo.state_gap(&current, &named)?;
2798
    // A fast-forward: the new heads hold the bookmark's newest head, so
2799
    // what they leave out is older work nothing since has built on, such
2800
    // as an early change no later one depends on (oxygen#78). Keep it, as
2801
    // --upto does, and say so.
28023×
    let newest = current
28033×
        .iter()
28048×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m.hlc, *h)))
28053×
        .max()
28063×
        .map(|(_, h)| h);
2807
    // Ahead, too: a head the bookmark holds already (it would only drop
2808
    // the others) is not a move forward.
28093×
    let ahead = repo
28103×
        .load_state_history(&current)
28113×
        .is_ok_and(|st| named.iter().any(|h| !st.contains(h)));
28123×
    let forward = !only
28133×
        && ahead
28141×
        && !gap.earlier.is_empty()
28151×
        && newest.is_some_and(|n| {
28161×
            repo.load_state_history(&named)
28171×
                .is_ok_and(|st| st.contains(&n))
28181×
        });
28193×
    let heads = if upto {
28201×
        gap.upto
28212×
    } else if forward {
28221×
        println!(
2823
            "  {} {}",
28241×
            ui::note(),
28251×
            ui::dim(format!(
2826
                "{} builds on {name}'s newest head; keeping {} it holds that {0} does not depend on",
28271×
                changes.join(" "),
28281×
                plural(gap.earlier.len(), "change")
2829
            ))
2830
        );
28311×
        gap.upto
28321×
    } else if only || gap.earlier.is_empty() {
28330×
        named
2834
    } else {
28351×
        anyhow::bail!(
2836
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2837
             A state is its heads and what they depend on, not everything recorded before them.\n\
2838
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2839
             or --only for just {0} and what it depends on.",
28401×
            changes.join(" "),
28411×
            plural(gap.earlier.len(), "change"),
28421×
            listed_changes(&repo, &gap.earlier)
2843
        );
2844
    };
28452×
    let heads = repo.bookmark_set(name, &heads)?;
28462×
    println!(
2847
        "{} bookmark {} {} {}",
28482×
        ui::done("Moved"),
28492×
        ui::bookmark(name),
28502×
        ui::dim(ui::glyph("→", "->")),
28512×
        ui::dim(plural(heads.len(), "head"))
2852
    );
28532×
    Ok(0)
28543×
}
2855
28560×
pub fn bookmark_delete(name: &str) -> Result<i32> {
28570×
    let repo = open()?;
28580×
    repo.bookmark_delete(name)?;
28590×
    println!(
2860
        "{} bookmark {} {}",
28610×
        ui::done("Deleted"),
28620×
        ui::bookmark(name),
28630×
        ui::dim("(its changes stay until unreachable)")
2864
    );
28650×
    Ok(0)
28660×
}
2867
2868
/// Heads with their metadata, newest first.
28690×
fn heads_newest_first(
28700×
    repo: &Repo,
28710×
    heads: &[oxy_core::hash::ChangeHash],
28720×
) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> {
28730×
    let mut out: Vec<_> = heads
28740×
        .iter()
28750×
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m)))
28760×
        .collect();
28770×
    out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc));
28780×
    out
28790×
}
2880
2881
/// One head as a line: id, hash, author, when, subject.
28820×
fn print_head(
28830×
    repo: &Repo,
28840×
    indent: &str,
28850×
    h: &oxy_core::hash::ChangeHash,
28860×
    m: &oxy_core::state::ChangeMeta,
28870×
) {
28880×
    println!(
2889
        "{indent}{} {} {}{}{}{}{}",
28900×
        ui::id(m.change_id.short(8)),
28910×
        ui::dim(format!("#{}", &h.to_hex()[..8])),
28920×
        author_name(repo, m),
28930×
        ui::sep(),
28940×
        ui::dim(ui::ago(m.hlc.wall_ms)),
28950×
        ui::sep(),
28960×
        ui::subject(subject_of(&m.message))
2897
    );
28980×
}
2899
29000×
pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result<i32> {
29010×
    let repo = open()?;
29020×
    let name = name.unwrap_or(&repo.config.bookmark).to_string();
29030×
    let view = repo.view()?;
29040×
    let st = match view.bookmarks.get(&name) {
29050×
        Some(st) => *st,
29060×
        None => match oxy_core::repo::remote_bookmark(&view, &name) {
29070×
            Some((_, _, st)) => st,
29080×
            None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"),
2909
        },
2910
    };
29110×
    let heads = repo.store().get_state(&st)?.heads;
29120×
    let shown = heads_newest_first(&repo, &heads);
29130×
    if as_json {
29140×
        println!(
2915
            "{}",
29160×
            json::obj([
29170×
                ("name", json::s(&name)),
29180×
                ("current", json::b(name == repo.config.bookmark)),
2919
                (
29200×
                    "heads",
29210×
                    json::arr(shown.iter().map(|(h, m)| {
29220×
                        json::obj([
29230×
                            ("hash", json::s(&h.to_hex())),
29240×
                            ("id", json::s(&m.change_id.to_string())),
29250×
                            ("author", json::s(&author_name(&repo, m))),
29260×
                            ("time_ms", json::n(m.hlc.wall_ms)),
29270×
                            ("subject", json::s(subject_of(&m.message))),
29280×
                        ])
29290×
                    }))
2930
                ),
2931
            ])
2932
        );
29330×
        return Ok(0);
29340×
    }
29350×
    println!(
2936
        "{} {}{}{}",
29370×
        ui::ok(ui::glyph("●", "*")),
29380×
        ui::bookmark(&name),
29390×
        ui::sep(),
29400×
        ui::dim(plural(heads.len(), "head"))
2941
    );
29420×
    for (h, m) in &shown {
29430×
        print_head(&repo, "  ", h, m);
29440×
    }
29450×
    if heads.len() > 1 {
29460×
        println!(
29470×
            "  {}",
29480×
            ui::dim("None depends on another: the bookmark is all of them and their dependencies.")
29490×
        );
29500×
    }
29510×
    Ok(0)
29520×
}
2953
29545×
pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result<i32> {
29555×
    let repo = open()?;
29565×
    let remote_only = repo.remote_only_bookmarks()?;
29575×
    if as_json {
29585×
        let mut items: Vec<String> = repo
29595×
            .bookmarks()?
29605×
            .into_iter()
296113×
            .map(|b| {
296213×
                json::obj([
296313×
                    ("name", json::s(&b.name)),
296413×
                    ("heads", json::hashes(&b.heads)),
296513×
                    ("current", json::b(b.current)),
296613×
                    ("ahead", json::opt(b.ahead, json::n)),
296713×
                    ("behind", json::opt(b.behind, json::n)),
296813×
                    ("remote", json::opt(b.remote.as_deref(), json::s)),
296913×
                ])
297013×
            })
29715×
            .collect();
29725×
        if all {
29730×
            items.extend(remote_only.iter().map(|b| {
29740×
                json::obj([
29750×
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
29760×
                    ("heads", json::hashes(&b.heads)),
29770×
                    ("current", json::b(false)),
29780×
                    ("ahead", "null".into()),
29790×
                    ("behind", "null".into()),
29800×
                    ("remote", json::s(&b.remote)),
29810×
                ])
29820×
            }));
29835×
        }
29845×
        println!("{}", json::arr(items));
29855×
        return Ok(0);
29860×
    }
29870×
    for b in repo.bookmarks()? {
29880×
        let mark = if b.current {
29890×
            ui::ok(ui::glyph("●", "*"))
2990
        } else {
29910×
            ui::dim(ui::glyph("○", "o"))
2992
        };
29930×
        let mut tail = String::new();
29940×
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
29950×
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
29960×
        }
29970×
        if let Some(n) = b.behind.filter(|n| *n > 0) {
29980×
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
29990×
        }
3000
        // Which remote, when there is a choice (oxygen#83).
30010×
        if !tail.is_empty() && repo.config.remotes.len() > 1 {
30020×
            if let Some(r) = &b.remote {
30030×
                tail += &ui::dim(format!(" {r}"));
30040×
            }
30050×
        }
30060×
        let shown = heads_newest_first(&repo, &b.heads);
3007
        // The newest head's subject, so a busy bookmark shows its latest work.
30080×
        let head = match shown.first() {
30090×
            Some(_) if verbose => String::new(),
30100×
            Some((_, m)) if b.heads.len() > 1 => format!(
3011
                "{} {}",
30120×
                ui::dim("newest"),
30130×
                ui::subject(subject_of(&m.message))
3014
            ),
30150×
            Some((_, m)) => ui::subject(subject_of(&m.message)),
30160×
            None => ui::dim("(empty)"),
3017
        };
30180×
        let head = if head.is_empty() {
30190×
            head
3020
        } else {
30210×
            format!("  {head}")
3022
        };
30230×
        println!(
3024
            "{mark} {}{}{}{tail}{head}",
30250×
            ui::bookmark(&b.name),
30260×
            ui::sep(),
30270×
            ui::dim(plural(b.heads.len(), "head"))
3028
        );
30290×
        if verbose {
30300×
            for (h, m) in &shown {
30310×
                print_head(&repo, "    ", h, m);
30320×
            }
30330×
        }
3034
    }
30350×
    if remote_only.is_empty() {
30360×
        return Ok(0);
30370×
    }
30380×
    if !all {
30390×
        println!(
3040
            "{}",
30410×
            ui::dim(format!(
3042
                "  and {} only on a remote: oxy bookmark list --all",
30430×
                plural(remote_only.len(), "bookmark")
3044
            ))
3045
        );
30460×
        return Ok(0);
30470×
    }
30480×
    for b in &remote_only {
30490×
        println!(
30500×
            "{} {}{}{}",
30510×
            ui::dim(ui::glyph("◌", ".")),
30520×
            ui::dim(format!("{}/{}", b.remote, b.name)),
30530×
            ui::sep(),
30540×
            ui::dim(plural(b.heads.len(), "head"))
30550×
        );
30560×
    }
30570×
    println!(
3058
        "  {} {}",
30590×
        ui::note(),
30600×
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
3061
    );
30620×
    Ok(0)
30635×
}
3064
30653×
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
30663×
    let mut repo = open()?;
30673×
    let from = repo.config.bookmark.clone();
30683×
    let (local, created_from) = repo.local_bookmark_for(name)?;
30693×
    if let Some(remote) = created_from {
30700×
        println!(
30710×
            "{} {} from {}",
30720×
            ui::done("Created"),
30730×
            ui::bookmark(&local),
30740×
            ui::dim(format!("{remote}/{local}"))
30750×
        );
30763×
    }
30773×
    let name = local.as_str();
3078
    // Only behind its remote: take the remote's state, so the switch does
3079
    // not check out a stale one (oxygen#74).
30803×
    if let Some(n) = repo.catch_up_bookmark(name)? {
30810×
        println!(
30820×
            "{} {} with {}: {} it lacked",
30830×
            ui::done("Caught up"),
30840×
            ui::bookmark(name),
30850×
            ui::dim(format!("{}/{name}", repo.default_remote())),
30860×
            plural(n, "change")
30870×
        );
30883×
    }
30893×
    let sp = ui::spinner(&format!("Switching to {name}…"));
30903×
    let (r, carried) = if carry {
30910×
        repo.bookmark_switch_carry(name)?
3092
    } else {
30933×
        (repo.bookmark_switch(name, discard)?, vec![])
3094
    };
30953×
    sp.done(&format!(
3096
        "{} to {}: {} written, {} removed{}",
30973×
        ui::done("Switched"),
30983×
        ui::bookmark(name),
30993×
        plural(r.written, "file"),
3100
        r.removed,
31013×
        if carried.is_empty() {
31023×
            String::new()
3103
        } else {
31040×
            format!("; carried {}", plural(carried.len(), "changed path"))
3105
        }
3106
    ));
31073×
    print_removed(&r);
31083×
    print_carried(&carried);
31093×
    print_kept_both(&r);
31103×
    if r.conflicted {
31110×
        println!(
31120×
            "  {} {}",
31130×
            ui::caution(),
31140×
            ui::warn("this state has conflicts; see oxy status")
31150×
        );
31163×
    }
3117
    // Say when the new state leaves out work the old one had: a state is
3118
    // its heads and what they depend on, which can be far less than a Git
3119
    // user expects.
31203×
    if r.lacks > 0 {
31211×
        println!(
31221×
            "  {} {}",
31231×
            ui::note(),
31241×
            ui::dim(format!(
31251×
                "{name} lacks {} that {from} has",
31261×
                plural(r.lacks, "change")
31271×
            ))
31281×
        );
31292×
    }
31303×
    super::sync::subrepos_behind(&repo);
31313×
    where_now(&repo);
31323×
    Ok(0)
31333×
}
3134
31350×
pub fn merge(bookmark: &str) -> Result<i32> {
31360×
    let repo = open()?;
31370×
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
31380×
    let r = repo.merge(bookmark)?;
31390×
    if !r.changed {
31400×
        sp.done(&format!(
31410×
            "{} {}",
31420×
            ui::ok(ui::glyph("✔", "*")),
31430×
            ui::dim(format!(
31440×
                "{} already contains {bookmark}",
31450×
                repo.config.bookmark
31460×
            ))
31470×
        ));
31480×
        return Ok(0);
31490×
    }
31500×
    sp.done(&format!(
3151
        "{} {} into {}: now {}{}",
31520×
        ui::done("Merged"),
31530×
        ui::bookmark(bookmark),
31540×
        ui::bookmark(&repo.config.bookmark),
31550×
        plural(r.heads.len(), "head"),
31560×
        ui::dim(if r.checked_out {
31570×
            "; working copy updated"
3158
        } else {
31590×
            "; run oxy checkout to update the working copy"
3160
        })
3161
    ));
31620×
    let snap = repo.snapshot("oxy merge")?;
31630×
    if snap.base_snapshot.is_conflicted() {
31640×
        println!(
31650×
            "  {} {}",
31660×
            ui::caution(),
31670×
            ui::warn("the result has conflicts; see oxy status")
31680×
        );
31690×
    }
31700×
    where_now(&repo);
31710×
    Ok(0)
31720×
}
3173
31740×
pub fn squash(change: &str, into: &str) -> Result<i32> {
31750×
    let repo = open()?;
31760×
    let c = repo.resolve_change(change)?;
31770×
    let d = repo.resolve_change(into)?;
31780×
    let sp = ui::spinner("Squashing…");
31790×
    let h = repo.squash(&c, &d)?;
31800×
    let new = repo.store().get_change_meta(&h)?;
31810×
    sp.done(&format!(
31820×
        "{} into {} {}  {}",
31830×
        ui::done("Squashed"),
31840×
        ui::id(new.change_id.short(8)),
31850×
        ui::hash(format!("#{}", h.short(12))),
31860×
        ui::subject(subject_of(&new.message))
31870×
    ));
31880×
    Ok(0)
31890×
}
3190
31910×
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
31920×
    let repo = open()?;
31930×
    let c = repo.resolve_change(change)?;
31940×
    let mut heads = Vec::new();
31950×
    for o in onto {
31960×
        heads.extend(repo.resolve_heads(o)?);
3197
    }
31980×
    let sp = ui::spinner("Rebasing…");
31990×
    let h = match repo.rebase(&c, &heads) {
32000×
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
32010×
            let r = repo.rebase_into_working_copy(&c, &heads)?;
32020×
            sp.done(&format!(
32030×
                "{} {} into {}: now {}",
32040×
                ui::done("Merged"),
32050×
                onto.join(" "),
32060×
                ui::bookmark(&repo.config.bookmark),
32070×
                plural(r.heads.len(), "head"),
32080×
            ));
32090×
            if r.checked_out {
32100×
                println!(
32110×
                    "  {} {}",
32120×
                    ui::caution(),
32130×
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
32140×
                );
32150×
            } else {
32160×
                println!(
32170×
                    "  {} {}",
32180×
                    ui::caution(),
32190×
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
32200×
                );
32210×
            }
32220×
            where_now(&repo);
32230×
            return Ok(0);
3224
        }
32250×
        other => other?,
3226
    };
32270×
    let new = repo.store().get_change_meta(&h)?;
32280×
    sp.done(&format!(
32290×
        "{} {} {}  {}",
32300×
        ui::done("Rebased"),
32310×
        ui::id(new.change_id.short(8)),
32320×
        ui::hash(format!("#{}", h.short(12))),
32330×
        ui::dim(format!(
32340×
            "now depends on {}",
32350×
            plural(new.deps.len(), "change")
32360×
        ))
32370×
    ));
32380×
    where_now(&repo);
32390×
    Ok(0)
32400×
}
3241
3242
#[cfg(test)]
3243
mod tests {
3244
    use super::*;
3245
3246
    #[test]
32471×
    fn id_prefixes_agree_with_the_whole_list() {
3248
        // Ids that share long prefixes, and some that differ only in a
3249
        // half byte, from a fixed sequence.
32501×
        let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
32517999×
        let mut next = || {
32527999×
            x ^= x << 13;
32537999×
            x ^= x >> 7;
32547999×
            x ^= x << 17;
32557999×
            x
32567999×
        };
32571×
        let mut ids: Vec<[u8; 16]> = Vec::new();
32581×
        for _ in 0..2000 {
32592000×
            let mut id = [0u8; 16];
32602000×
            id[..8].copy_from_slice(&next().to_le_bytes());
32612000×
            id[8..].copy_from_slice(&next().to_le_bytes());
32622000×
            let share = (next() % 4) as usize;
32632000×
            if let Some(prev) = ids.last() {
32641999×
                id[..share].copy_from_slice(&prev[..share]);
32651999×
                if next() % 2 == 0 {
3266973×
                    id[share] = (prev[share] & 0xf0) | (id[share] & 0x0f);
32671026×
                }
32681×
            }
32692000×
            ids.push(id);
3270
        }
32714000×
        let hex = |id: &[u8; 16]| oxy_core::ids::ChangeId(*id).to_hex();
32721×
        let whole = unique_prefixes(ids.iter().map(hex));
32731×
        let some = id_prefixes(ids.clone(), ids.iter().copied());
32742000×
        for id in &ids {
32752000×
            assert_eq!(some[id], whole[&hex(id)], "{}", hex(id));
3276
        }
32771×
    }
3278
}