OXYGENHUB

Coverage / src/cli/sync.rs 38.9%

367 of 944 lines run, 33 of 146 functions · run #266 on main · run missed

1
//! Commands that talk to remotes, and the reference server.
2
3
use super::format::plural;
4
use super::json;
5
use super::open;
6
use super::ui;
7
use anyhow::{Context, Result};
8
use oxy_core::repo::Repo;
9
use std::path::PathBuf;
10
115×
pub fn clone(
125×
    url: &str,
135×
    dest: Option<PathBuf>,
145×
    max_blob: Option<&str>,
155×
    sparse: &[String],
165×
    depth: Option<u32>,
175×
    recursive: bool,
185×
) -> Result<i32> {
195×
    let dest = dest.unwrap_or_else(|| {
200×
        let base = url
210×
            .trim_end_matches('/')
220×
            .rsplit('/')
230×
            .next()
240×
            .unwrap_or("repo");
250×
        PathBuf::from(base)
260×
    });
275×
    let max_blob = max_blob.map(oxy_core::repo::parse_size).transpose()?;
285×
    let sp = ui::spinner(&format!("Cloning {url}…"));
295×
    let repo = match depth {
300×
        Some(d) => Repo::clone_shallow(url, &dest, d, max_blob, sparse)?,
315×
        None => Repo::clone_with(url, &dest, max_blob, sparse)?,
32
    };
335×
    let heads = repo.bookmark_heads()?;
345×
    sp.done(&format!(
355×
        "{} into {} {}",
365×
        ui::done("Cloned"),
375×
        ui::path(repo.root().display()),
385×
        ui::dim(format!(
395×
            "({url}, {} with {})",
405×
            ui::bookmark(&repo.config.bookmark),
415×
            plural(heads.len(), "head")
425×
        ))
435×
    ));
445×
    let others = repo.remote_only_bookmarks()?.len();
455×
    if others > 0 {
460×
        println!(
470×
            "  {} {}",
480×
            ui::note(),
490×
            ui::dim(format!(
500×
                "origin has {} more: oxy bookmark list --all, then oxy bookmark switch NAME",
510×
                plural(others, "bookmark")
520×
            ))
530×
        );
545×
    }
555×
    let subrepos = repo.subrepos()?.len();
565×
    if subrepos == 0 {
575×
        return Ok(0);
580×
    }
590×
    if recursive {
600×
        let sp = ui::spinner("Cloning subrepos…");
610×
        let results = repo.submodule_update(true, &[])?;
620×
        sp.clear();
630×
        return Ok(print_subrepo_results(results));
640×
    }
650×
    println!(
66
        "  {} {}",
670×
        ui::note(),
680×
        ui::dim(format!(
69
            "{} not cloned: oxy submodule update --init (or clone with --recursive)",
700×
            plural(subrepos, "subrepo")
71
        ))
72
    );
730×
    Ok(0)
745×
}
75
76
/// After a switch or pull: say when subrepos are not at their pins.
775×
pub fn subrepos_behind(repo: &Repo) {
785×
    let Ok(subs) = repo.subrepos() else {
790×
        return;
80
    };
815×
    let stale = subs
825×
        .iter()
835×
        .filter(|s| s.committed && s.actual.as_ref() != Some(&s.pin))
845×
        .count();
855×
    if stale > 0 {
860×
        println!(
87
            "  {} {}",
880×
            ui::note(),
890×
            ui::dim(format!(
90
                "{} not at {} pin: oxy submodule update --init",
910×
                plural(stale, "subrepo"),
920×
                if stale == 1 { "its" } else { "their" }
93
            ))
94
        );
955×
    }
965×
}
97
98
/// Whether a URL names a store (a bucket or a directory in the store
99
/// layout) rather than a repository.
1002×
fn is_store_url(url: &str) -> bool {
1012×
    ["s3://", "gs://", "az://", "dir://"]
1022×
        .iter()
1035×
        .any(|p| url.starts_with(p))
1042×
}
105
106
/// Percent-encode what would break a query parameter.
1072×
fn encode_param(v: &str) -> String {
1082×
    let mut out = String::with_capacity(v.len());
10913×
    for b in v.bytes() {
11013×
        match b {
11110×
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' | b':' => {
11213×
                out.push(b as char)
113
            }
1140×
            _ => out.push_str(&format!("%{b:02X}")),
115
        }
116
    }
1172×
    out
1182×
}
119
120
/// A store URL with settings added as query parameters, which is where a
121
/// store remote keeps them (`s3://b/p?profile=work&region=eu-west-2`).
1224×
fn url_with_settings(url: &str, settings: &[(&str, Option<String>)]) -> Result<String> {
1234×
    let given: Vec<(&str, &str)> = settings
1244×
        .iter()
12516×
        .filter_map(|(k, v)| v.as_deref().map(|v| (*k, v)))
1264×
        .collect();
1274×
    if given.is_empty() {
1282×
        return Ok(url.to_string());
1292×
    }
1302×
    if !is_store_url(url) || url.starts_with("dir://") {
1311×
        let names: Vec<String> = given.iter().map(|(k, _)| format!("--{k}")).collect();
1321×
        anyhow::bail!(
133
            "{} apply to a store remote (s3://, gs://, az://), not to {url}",
1341×
            names.join(", ")
135
        );
1361×
    }
1371×
    let mut out = url.to_string();
1382×
    for (k, v) in given {
1392×
        out.push(if out.contains('?') { '&' } else { '?' });
1402×
        out.push_str(k);
1412×
        out.push('=');
1422×
        out.push_str(&encode_param(v));
143
    }
1441×
    Ok(out)
1454×
}
146
1474×
pub fn remote_add(name: &str, url: &str, settings: &[(&str, Option<String>)]) -> Result<i32> {
1484×
    let mut repo = open()?;
1494×
    let url = url_with_settings(url, settings)?;
1503×
    let url = url.as_str();
1513×
    repo.config.set(
1523×
        &format!("remote.{name}.url"),
1533×
        &oxy_core::protocol::stored_url(url),
1540×
    )?;
1553×
    repo.save_config()?;
1563×
    println!(
157
        "{} remote {} {} {url}",
1583×
        ui::done("Added"),
1593×
        ui::bookmark(name),
1603×
        ui::dim(ui::glyph("→", "->"))
161
    );
1623×
    Ok(0)
1634×
}
164
165
/// `oxy remote check NAME`: reach the remote with the credentials in
166
/// hand, say what it holds, and, for a store, put it through the
167
/// conformance check under a probe prefix (left empty afterwards).
1683×
pub fn remote_check(name: &str) -> Result<i32> {
1693×
    let repo = open()?;
1703×
    let Some(url) = repo.config.remotes.get(name).cloned() else {
1710×
        anyhow::bail!("no remote {name:?}; oxy remote list shows the remotes there are");
172
    };
1733×
    let options = repo.options_for_url(&url);
1743×
    let mine = repo.id()?;
1753×
    let started = std::time::Instant::now();
1763×
    let sp = ui::spinner(&format!("Checking {name}…"));
1773×
    let Some(store) = oxy_core::protocol::open_store(&url, &options) else {
178
        // A hub or another repository: reach it and read its references.
1790×
        let (_, remote) = repo.open_remote_at(&url)?;
1800×
        let id = remote.repo_id()?;
1810×
        let refs = remote.refs()?;
1820×
        sp.done(&format!(
1830×
            "{} {} {}",
1840×
            ui::done("Reachable"),
1850×
            ui::bookmark(name),
1860×
            ui::dim(format!("({url}, {} ms)", started.elapsed().as_millis()))
1870×
        ));
1880×
        describe_holding(id, mine, refs.refs.len(), refs.tags.len(), None);
1890×
        return Ok(0);
190
    };
1913×
    let store = store.with_context(|| format!("opening the store of {name}"))?;
192
    // What it holds, in one listing and two reads.
1933×
    let marker = match store.get("oxygen.toml") {
1942×
        Ok(b) => Some(b),
1951×
        Err(oxy_core::strata::Error::NotFound(_)) => None,
1960×
        Err(e) => {
1970×
            sp.clear();
1980×
            return Err(anyhow::anyhow!("{e}"))
1990×
                .with_context(|| format!("reaching the store of {name}"));
200
        }
201
    };
2023×
    let reached = started.elapsed();
2033×
    let bundles = store.list("bundles/")?.len();
2043×
    let record = store.read_ref("refs")?;
2053×
    sp.done(&format!(
2063×
        "{} {} {}",
2073×
        ui::done("Reachable"),
2083×
        ui::bookmark(name),
2093×
        ui::dim(format!("({url}, {} ms)", reached.as_millis()))
2103×
    ));
2113×
    match marker {
2121×
        None => println!(
213
            "  {} {}",
2141×
            ui::note(),
2151×
            ui::dim("holds no repository yet: oxy push NAME binds it to this one")
216
        ),
217
        Some(_) => {
2182×
            let (id, bookmarks, tags) = match record {
2192×
                Some((bytes, _)) => {
2202×
                    let (id, resp) = oxy_core::protocol::wire::decode_refs(&bytes)?;
2212×
                    (id, resp.refs.len(), resp.tags.len())
222
                }
2230×
                None => (mine, 0, 0),
224
            };
2252×
            describe_holding(id, mine, bookmarks, tags, Some(bundles));
226
        }
227
    }
228
    // Then the behaviour a repository depends on, under a prefix of its own.
2293×
    let sp = ui::spinner("Checking that the store behaves…");
2303×
    let probe = format!("oxy-check-{}", std::process::id());
2313×
    let began = std::time::Instant::now();
2323×
    match oxy_core::strata::conformance(store.as_ref(), &probe) {
2333×
        Ok(passed) => {
2343×
            sp.clear();
23524×
            for p in &passed {
23624×
                println!("  {} {}", ui::ok(ui::glyph("✔", "*")), p);
23724×
            }
2383×
            println!(
239
                "{} {}",
2403×
                ui::done("Behaves"),
2413×
                ui::dim(format!(
242
                    "({} checks in {} ms; nothing left behind)",
2433×
                    passed.len(),
2443×
                    began.elapsed().as_millis()
245
                ))
246
            );
2473×
            Ok(0)
248
        }
2490×
        Err(e) => {
2500×
            sp.clear();
251
            // Leave nothing behind, even after a failed check.
2520×
            if let Ok(left) = store.list(&probe) {
2530×
                for entry in left {
2540×
                    let _ = store.delete(&entry.key);
2550×
                }
2560×
            }
2570×
            println!("{} {}", ui::err(ui::glyph("✘", "x")), e);
2580×
            println!(
259
                "  {} {}",
2600×
                ui::note(),
2610×
                ui::dim("a store that fails this cannot keep a repository safely; check the service and the credentials' permissions")
262
            );
2630×
            Ok(1)
264
        }
265
    }
2663×
}
267
2682×
fn describe_holding(
2692×
    id: [u8; 16],
2702×
    mine: [u8; 16],
2712×
    bookmarks: usize,
2722×
    tags: usize,
2732×
    bundles: Option<usize>,
2742×
) {
27512×
    let short: String = id[..6].iter().map(|b| format!("{b:02x}")).collect();
2762×
    let mut what = format!(
277
        "repository {short}: {} and {}",
2782×
        plural(bookmarks, "bookmark"),
2792×
        plural(tags, "tag")
280
    );
2812×
    if let Some(b) = bundles {
2822×
        what.push_str(&format!(" in {}", plural(b, "bundle")));
2832×
    }
2842×
    if id == mine {
2851×
        println!("  {} {}", ui::note(), ui::dim(format!("holds this {what}")));
2861×
    } else if id == oxy_core::protocol::UNBOUND_ID {
2870×
        println!("  {} {}", ui::note(), ui::dim("holds no repository yet"));
2881×
    } else {
2891×
        println!(
2901×
            "  {} {}",
2911×
            ui::caution(),
2921×
            ui::warn(format!("holds another {what}; a push would be refused"))
2931×
        );
2941×
    }
2952×
}
296
2971×
pub fn remote_remove(name: &str) -> Result<i32> {
2981×
    let mut repo = open()?;
2991×
    repo.config.set(&format!("remote.{name}.url"), "")?;
3001×
    repo.save_config()?;
3011×
    println!("{} remote {}", ui::done("Removed"), ui::bookmark(name));
3021×
    Ok(0)
3031×
}
304
3052×
pub fn remote_list(as_json: bool) -> Result<i32> {
3062×
    let repo = open()?;
3072×
    let view = repo.view()?;
3082×
    if as_json {
3091×
        let items = repo.config.remotes.iter().map(|(name, url)| {
3101×
            let bms = view.remotes.get(name).map(|b| {
3111×
                json::arr(b.iter().map(|(bm, st)| {
3121×
                    let heads = repo
3131×
                        .store()
3141×
                        .get_state(st)
3151×
                        .map(|s| s.heads)
3161×
                        .unwrap_or_default();
3171×
                    json::obj([("name", json::s(bm)), ("heads", json::hashes(&heads))])
3181×
                }))
3191×
            });
3201×
            json::obj([
3211×
                ("name", json::s(name)),
3221×
                ("url", json::s(url)),
323
                // The CA file `remote.NAME.ca` names, for tools that talk to
324
                // the same hub (an editor's forge view, `oh`).
325
                (
3261×
                    "ca",
3271×
                    json::opt(repo.config.remote_cas.get(name), |c| json::s(c)),
328
                ),
3291×
                ("bookmarks", bms.unwrap_or_else(|| "[]".into())),
330
            ])
3311×
        });
3321×
        println!("{}", json::arr(items));
3331×
        return Ok(0);
3341×
    }
3351×
    if repo.config.remotes.is_empty() {
3360×
        println!(
3370×
            "{}",
3380×
            ui::dim("No remotes; add one with oxy remote add <name> <url>.")
3390×
        );
3401×
    }
3411×
    for (name, url) in &repo.config.remotes {
3421×
        println!(
343
            "{} {}{}{}",
3441×
            ui::ok(ui::glyph("⇄", "<>")),
3451×
            ui::bookmark(name),
3461×
            ui::sep(),
3471×
            ui::dim(url)
348
        );
3491×
        if let Some(bms) = view.remotes.get(name) {
3500×
            for (bm, st) in bms {
3510×
                let heads = repo
3520×
                    .store()
3530×
                    .get_state(st)
3540×
                    .map(|s| s.heads.len())
3550×
                    .unwrap_or(0);
3560×
                println!(
357
                    "    {} {}{}{}",
3580×
                    ui::dim(ui::glyph("↳", "->")),
3590×
                    ui::id(format!("{name}/{bm}")),
3600×
                    ui::sep(),
3610×
                    ui::dim(plural(heads, "head"))
362
                );
363
            }
3641×
        }
365
    }
3661×
    Ok(0)
3672×
}
368
369
/// The remote named, else `origin`, else the only remote there is.
37012×
fn remote_name(repo: &oxy_core::repo::Repo, remote: Option<&str>) -> String {
37112×
    remote.map_or_else(|| repo.default_remote(), str::to_string)
37212×
}
373
3741×
pub fn fetch(remote: Option<&str>, as_json: bool) -> Result<i32> {
3751×
    let repo = open()?;
3761×
    let remote = remote_name(&repo, remote);
3771×
    let sp = ui::spinner(&format!("Fetching from {remote}…"));
3781×
    let report = repo.fetch(&remote)?;
3791×
    sp.clear();
3801×
    if as_json {
3811×
        println!(
382
            "{}",
3831×
            json::obj([
3841×
                ("remote", json::s(&remote)),
385
                (
3861×
                    "refs",
3871×
                    json::arr(report.refs.iter().map(|(name, heads, n)| {
3881×
                        let t = repo.tracking(&remote, name).ok().flatten();
3891×
                        json::obj([
3901×
                            ("name", json::s(name)),
3911×
                            ("heads", json::hashes(heads)),
3921×
                            ("new", json::n(*n)),
393
                            (
3941×
                                "ahead",
3951×
                                t.map_or_else(|| "null".into(), |(a, _)| json::n(a)),
396
                            ),
397
                            (
3981×
                                "behind",
3991×
                                t.map_or_else(|| "null".into(), |(_, b)| json::n(b)),
400
                            ),
401
                        ])
4021×
                    }))
403
                ),
4041×
                ("new_tags", json::n(report.new_tags)),
4051×
                ("unverified", json::b(report.unverified)),
406
            ])
407
        );
4081×
        return Ok(0);
4090×
    }
4100×
    if report.refs.is_empty() {
4110×
        println!(
4120×
            "{} {}",
4130×
            ui::done("Fetched"),
4140×
            ui::dim(format!("nothing new from {remote}"))
4150×
        );
4160×
    }
4170×
    for (name, heads, n) in &report.refs {
418
        // What was fetched, then how the local bookmark stands against it:
419
        // "up to date" only when the two are the same (oxygen#56).
4200×
        let fetched =
4210×
            (*n > 0).then(|| format!("{}{}", ui::ok(plural(*n, "new change")), ui::sep()));
4220×
        let them = |k: usize| if k == 1 { "it" } else { "them" };
4230×
        let standing = match repo.tracking(&remote, name).ok().flatten() {
4240×
            None => ui::dim(format!("no local bookmark {name}")),
4250×
            Some((0, 0)) => ui::dim(format!("{name} up to date")),
4260×
            Some((0, b)) if *name == repo.config.bookmark => ui::warn(format!(
427
                "{name} is {} behind: oxy pull to take {}",
4280×
                plural(b, "change"),
4290×
                them(b)
430
            )),
4310×
            Some((0, b)) => ui::warn(format!(
432
                "{name} is {} behind: oxy bookmark switch {name} then oxy pull to take {}",
4330×
                plural(b, "change"),
4340×
                them(b)
435
            )),
4360×
            Some((a, 0)) => ui::dim(format!(
437
                "{name} is {} ahead: oxy push to send {}",
4380×
                plural(a, "change"),
4390×
                them(a)
440
            )),
4410×
            Some((a, b)) => ui::warn(format!(
442
                "{name} and {remote}/{name} have diverged ({a} here, {b} there): oxy pull to merge them"
443
            )),
444
        };
4450×
        let what = format!("{}{standing}", fetched.unwrap_or_default());
4460×
        println!(
447
            "{} {}{}{}{}{what}",
4480×
            ui::done("Fetched"),
4490×
            ui::id(format!("{remote}/{name}")),
4500×
            ui::sep(),
4510×
            ui::dim(plural(heads.len(), "head")),
4520×
            ui::sep()
453
        );
454
    }
4550×
    if report.new_tags > 0 {
4560×
        println!(
4570×
            "  {} {}",
4580×
            ui::note(),
4590×
            ui::dim(format!("{} adopted", plural(report.new_tags, "tag")))
4600×
        );
4610×
    }
4620×
    if report.unverified {
4630×
        eprintln!(
4640×
            "{} {remote} has no trust policy; nothing fetched from it was verified",
4650×
            ui::caution()
4660×
        );
4670×
    }
4680×
    Ok(0)
4691×
}
470
471
/// Pull acts on the current bookmark only: name the others the fetch
472
/// found behind their remote, which is easy to take for the current one
473
/// (oxygen#29).
4743×
fn others_behind(repo: &oxy_core::repo::Repo, remote: &str) {
4753×
    let Ok(bookmarks) = repo.bookmarks() else {
4760×
        return;
477
    };
4784×
    for b in bookmarks {
4794×
        let Some(n) = b.behind.filter(|n| *n > 0) else {
4804×
            continue;
481
        };
4820×
        if b.current {
4830×
            continue;
4840×
        }
4850×
        println!(
486
            "  {} {}",
4870×
            ui::note(),
4880×
            ui::dim(format!(
489
                "{} is {} behind {remote}/{}: oxy bookmark switch {} then oxy pull to take {}",
490
                b.name,
4910×
                plural(n, "change"),
492
                b.name,
493
                b.name,
4940×
                if n == 1 { "it" } else { "them" }
495
            ))
496
        );
497
    }
4983×
}
499
5004×
pub fn pull(remote: Option<&str>, as_json: bool) -> Result<i32> {
5014×
    let repo = open()?;
5024×
    let remote = remote_name(&repo, remote);
5034×
    let sp = ui::spinner(&format!("Pulling from {remote}…"));
5044×
    let r = repo.pull(&remote)?;
5054×
    if as_json {
5061×
        sp.clear();
5071×
        let conflicted = repo
5081×
            .snapshot_status("oxy pull")?
509
            .base_snapshot
5101×
            .is_conflicted();
5111×
        println!(
512
            "{}",
5131×
            json::obj([
5141×
                ("remote", json::s(&remote)),
5151×
                ("bookmark", json::s(&repo.config.bookmark)),
5161×
                ("heads", json::hashes(&r.heads)),
5171×
                ("changed", json::b(r.changed)),
5181×
                ("checked_out", json::b(r.checked_out)),
5191×
                ("conflicted", json::b(conflicted)),
5201×
                ("others", json::arr(r.others.iter().map(|o| json::s(o))))
521
            ])
522
        );
5231×
        return Ok(0);
5243×
    }
5253×
    if !r.changed {
5261×
        sp.done(&format!(
527
            "{} {}{}",
5281×
            ui::ok(ui::glyph("✔", "*")),
5291×
            ui::dim(format!(
530
                "{} is up to date with {remote}.",
531
                repo.config.bookmark
532
            )),
5331×
            if r.checked_out {
5340×
                ui::dim(" The working copy had fallen behind it and is updated.")
535
            } else {
5361×
                String::new()
537
            }
538
        ));
5391×
        others_pulled(&r.others);
5401×
        others_behind(&repo, &remote);
5411×
        if r.checked_out {
5420×
            super::workspace::where_now(&repo);
5431×
        }
5441×
        return Ok(0);
5452×
    }
5462×
    sp.done(&format!(
547
        "{} {} now has {}{}",
5482×
        ui::done("Pulled:"),
5492×
        ui::bookmark(&repo.config.bookmark),
5502×
        plural(r.heads.len(), "head"),
5512×
        ui::dim(if r.checked_out {
5522×
            "; working copy updated"
553
        } else {
5540×
            "; run oxy checkout to update the working copy"
555
        })
556
    ));
5572×
    let snap = repo.snapshot("oxy pull")?;
5582×
    if snap.base_snapshot.is_conflicted() {
5590×
        println!(
5600×
            "  {} {}",
5610×
            ui::caution(),
5620×
            ui::warn("the result has conflicts; see oxy status")
5630×
        );
5642×
    }
5652×
    others_pulled(&r.others);
5662×
    others_behind(&repo, &remote);
5672×
    subrepos_behind(&repo);
5682×
    super::workspace::where_now(&repo);
5692×
    Ok(0)
5704×
}
571
572
/// The other bookmarks a pull moved.
5733×
fn others_pulled(others: &[String]) {
5743×
    if others.is_empty() {
5752×
        return;
5761×
    }
5771×
    let shown: Vec<String> = others.iter().take(8).map(ui::bookmark).collect();
5781×
    let more = others.len().saturating_sub(8);
5791×
    println!(
580
        "  {} {}{}",
5811×
        ui::done("Also updated"),
5821×
        shown.join(", "),
5831×
        if more > 0 {
5840×
            ui::dim(format!(" and {more} more"))
585
        } else {
5861×
            String::new()
587
        }
588
    );
5893×
}
590
591
/// `oxy push [REMOTE] --delete NAME`.
5920×
pub fn push_delete(remote: Option<&str>, name: &str, as_json: bool) -> Result<i32> {
5930×
    let repo = open()?;
5940×
    let remote = remote_name(&repo, remote);
5950×
    let sp = ui::spinner(&format!("Deleting {remote}/{name}…"));
5960×
    let results = repo.push_delete(&remote, name)?;
5970×
    sp.clear();
5980×
    if as_json {
5990×
        println!(
600
            "{}",
6010×
            json::arr(results.iter().map(|r| {
6020×
                json::obj([
6030×
                    ("name", json::s(&r.name)),
6040×
                    ("ok", json::b(r.ok)),
6050×
                    ("reason", json::s(&r.reason)),
6060×
                    ("state", json::s("")),
6070×
                ])
6080×
            }))
609
        );
6100×
        return Ok(if results.iter().all(|r| r.ok) { 0 } else { 1 });
6110×
    }
6120×
    let mut code = 0;
6130×
    for r in results {
6140×
        if r.ok {
6150×
            println!(
6160×
                "{} {}",
6170×
                ui::done("Deleted"),
6180×
                ui::id(format!("{remote}/{}", r.name))
6190×
            );
6200×
        } else {
6210×
            println!(
6220×
                "{} {} {}{}{}",
6230×
                ui::err(ui::glyph("✖", "x")),
6240×
                ui::err("Rejected"),
6250×
                ui::id(format!("{remote}/{}", r.name)),
6260×
                ui::sep(),
6270×
                r.reason
6280×
            );
6290×
            code = 1;
6300×
        }
631
    }
6320×
    Ok(code)
6330×
}
634
6357×
pub fn push(
6367×
    remote: Option<&str>,
6377×
    force: bool,
6387×
    bookmark: Option<&str>,
6397×
    as_json: bool,
6407×
) -> Result<i32> {
6417×
    let repo = open()?;
6427×
    let remote = remote_name(&repo, remote);
6437×
    let sp = ui::spinner(&format!("Pushing to {remote}…"));
6447×
    let bookmark_name = bookmark.map_or_else(|| repo.config.bookmark.clone(), String::from);
645
    // A long push goes in parts: the spinner says which.
6467×
    let results = repo.push_bookmark_with(&remote, &bookmark_name, force, &mut |m| {
6470×
        sp.set(&format!("Pushing to {remote}… {m}"))
6481×
    })?;
6496×
    sp.clear();
6506×
    if as_json {
651
        // The state each accepted bookmark now holds on the remote (its local
652
        // state object), so a caller can look up what the push started, such
653
        // as the checks a forge runs on it.
6541×
        let view = repo.view()?;
6551×
        println!(
656
            "{}",
6571×
            json::arr(results.iter().map(|r| {
6581×
                let state = view
6591×
                    .bookmarks
6601×
                    .get(&r.name)
6611×
                    .filter(|_| r.ok)
6621×
                    .map(|st| st.to_hex())
6631×
                    .unwrap_or_default();
6641×
                json::obj([
6651×
                    ("name", json::s(&r.name)),
6661×
                    ("ok", json::b(r.ok)),
6671×
                    ("reason", json::s(&r.reason)),
6681×
                    ("state", json::s(&state)),
6691×
                ])
6701×
            }))
671
        );
6721×
        return Ok(if results.iter().all(|r| r.ok) { 0 } else { 1 });
6735×
    }
6745×
    let mut code = 0;
6755×
    for r in results {
6765×
        if r.ok {
6775×
            println!(
678
                "{} {}{}{}",
6795×
                ui::done("Pushed"),
6805×
                ui::id(format!("{remote}/{}", r.name)),
6815×
                ui::sep(),
6825×
                ui::dim(if r.reason.is_empty() {
6835×
                    "updated"
684
                } else {
6850×
                    r.reason.as_str()
686
                })
687
            );
6880×
        } else {
6890×
            println!(
6900×
                "{} {} {}{}{}",
6910×
                ui::err(ui::glyph("✖", "x")),
6920×
                ui::err("Rejected"),
6930×
                ui::id(format!("{remote}/{}", r.name)),
6940×
                ui::sep(),
6950×
                r.reason
6960×
            );
6970×
            code = 1;
6980×
        }
699
    }
7005×
    Ok(code)
7017×
}
702
7030×
pub fn serve(
7040×
    root: PathBuf,
7050×
    bind: &str,
7060×
    tokens: Vec<String>,
7070×
    tls: Option<(PathBuf, PathBuf)>,
7080×
) -> Result<i32> {
7090×
    let listener = std::net::TcpListener::bind(bind).with_context(|| format!("binding {bind}"))?;
7100×
    let root = root.canonicalize()?;
7110×
    let tls = tls.map(|(cert, key)| oxy_server::TlsFiles { cert, key });
7120×
    println!(
713
        "Serving repositories under {} on {}://{bind}/<repo>/oxy/v1/ ({})",
7140×
        root.display(),
7150×
        if tls.is_some() { "https" } else { "http" },
7160×
        if tokens.is_empty() {
7170×
            "open: no push tokens configured"
718
        } else {
7190×
            "push requires a token"
720
        }
721
    );
7220×
    if tls.is_none()
7230×
        && !bind.starts_with("127.")
7240×
        && !bind.starts_with("localhost")
7250×
        && !bind.starts_with("[::1]")
7260×
    {
7270×
        eprintln!("warning: serving plain HTTP on a non-loopback address; put a TLS terminator in front or pass --tls-cert/--tls-key");
7280×
    }
7290×
    oxy_server::run_blocking(listener, oxy_server::ServerConfig { root, tokens, tls })?;
7300×
    Ok(0)
7310×
}
732
7330×
pub fn git_export(git_dir: &std::path::Path, branch: Option<&str>) -> Result<i32> {
7340×
    let repo = open()?;
7350×
    let sp = ui::spinner("Exporting to Git…");
7360×
    let r = match branch {
7370×
        Some(b) => repo.git_export_as(git_dir, b)?,
7380×
        None => repo.git_export(git_dir)?,
739
    };
7400×
    sp.clear();
7410×
    println!(
742
        "{} {} to {} as branch {} {}",
7430×
        ui::done("Exported"),
7440×
        plural(r.exported, "new state"),
7450×
        ui::path(git_dir.display()),
7460×
        ui::bookmark(&r.branch),
7470×
        ui::dim(format!(
748
            "(currently {}; {} already exported)",
7490×
            plural(r.heads, "head"),
750
            r.skipped
751
        ))
752
    );
7530×
    Ok(0)
7540×
}
755
7560×
pub fn git_recover() -> Result<i32> {
7570×
    let repo = open()?;
7580×
    let sp = ui::spinner("Reading the store…");
7590×
    let (changes, heads) = repo.recover_git_import(&|m| sp.set(m))?;
7600×
    sp.done(&format!(
7610×
        "{} {} from imported Git commits: {} now has {}",
7620×
        ui::done("Recovered"),
7630×
        plural(changes, "change"),
7640×
        ui::bookmark(&repo.config.bookmark),
7650×
        plural(heads, "head")
7660×
    ));
7670×
    println!(
768
        "  {} {}",
7690×
        ui::note(),
7700×
        ui::dim("carry on with oxy git fetch GIT_DIR --branch BRANCH")
771
    );
7720×
    Ok(0)
7730×
}
774
775
/// `--claim` (oxygen#97): record `git.claim`, so this import and every
776
/// later fetch author the identity's own commits with its key.
7770×
fn claim_commits(repo: &mut Repo) -> Result<()> {
7780×
    repo.config.set("git.claim", "true")?;
7790×
    repo.save_config()?;
7800×
    Ok(())
7810×
}
782
7830×
pub fn git_fetch(url: &str, branch: &str, claim: bool) -> Result<i32> {
7840×
    let mut repo = open()?;
7850×
    if claim {
7860×
        claim_commits(&mut repo)?;
7870×
    }
7880×
    let sp = ui::spinner(&format!("Fetching {url} {branch}…"));
7890×
    let r = repo.git_fetch(url, branch)?;
7900×
    sp.clear();
7910×
    if r.commits == 0 {
7920×
        println!(
7930×
            "{} {}",
7940×
            ui::done("Fetched"),
7950×
            ui::dim(format!("nothing new from {url} {branch}"))
7960×
        );
7970×
    } else {
7980×
        println!(
799
            "{} {} ({} merges) from {} {}{}{} now has {}",
8000×
            ui::done("Fetched"),
8010×
            plural(r.commits, "new commit"),
802
            r.merges,
8030×
            ui::path(url),
8040×
            ui::bookmark(branch),
8050×
            ui::sep(),
8060×
            ui::bookmark(&repo.config.bookmark),
8070×
            plural(r.heads, "head")
808
        );
8090×
        if !repo.snapshot("oxy git fetch")?.changed {
8100×
            println!("  {} {}", ui::note(), ui::dim("working copy updated"));
8110×
        } else {
8120×
            println!(
8130×
                "  {} {}",
8140×
                ui::note(),
8150×
                ui::dim("run oxy checkout to update the working copy")
8160×
            );
8170×
        }
818
    }
8190×
    if r.submodules > 0 {
8200×
        println!(
821
            "  {} {}",
8220×
            ui::note(),
8230×
            ui::dim(format!(
824
                "{} submodule {} imported as subrepos with Git pins",
825
                r.submodules,
8260×
                if r.submodules == 1 {
8270×
                    "entry"
828
                } else {
8290×
                    "entries"
830
                }
831
            ))
832
        );
8330×
    }
8340×
    Ok(0)
8350×
}
836
8370×
pub fn git_push(url: &str, branch: &str) -> Result<i32> {
8380×
    let repo = open()?;
8390×
    let sp = ui::spinner(&format!("Pushing to {url} {branch}…"));
8400×
    let r = repo.git_push(url, branch)?;
8410×
    sp.clear();
8420×
    println!(
843
        "{} {} to {} {} {}",
8440×
        ui::done("Pushed"),
8450×
        plural(r.exported, "new commit"),
8460×
        ui::path(url),
8470×
        ui::bookmark(&r.branch),
8480×
        ui::dim(format!("({} already there)", r.skipped))
849
    );
8500×
    Ok(0)
8510×
}
852
853
/// `oxy git verify`: exit 1 if any commit's tree is not reproduced.
8540×
pub fn git_verify(
8550×
    git_dir: &std::path::Path,
8560×
    branch: &str,
8570×
    last: Option<usize>,
8580×
    max: usize,
8590×
) -> Result<i32> {
8600×
    let repo = open()?;
8610×
    let started = std::time::Instant::now();
8620×
    let sp = ui::spinner(&format!(
8630×
        "Rebuilding every commit of {} {branch}…",
8640×
        git_dir.display()
8650×
    ));
8660×
    let r = repo.verify_git_import_last(git_dir, branch, last, max)?;
8670×
    sp.clear();
8680×
    for (_, what) in &r.mismatches {
8690×
        println!("{} {what}", ui::err(ui::glyph("✖", "x")));
8700×
    }
8710×
    if r.not_yet > 0 {
8720×
        println!(
8730×
            "  {} {}",
8740×
            ui::note(),
8750×
            ui::dim(format!(
8760×
                "{} not imported yet, after the last imported commit: not checked",
8770×
                plural(r.not_yet, "commit")
8780×
            ))
8790×
        );
8800×
    }
8810×
    if r.mismatches.is_empty() {
8820×
        println!(
883
            "{}",
8840×
            ui::done(if r.skipped > 0 {
8850×
                format!(
886
                    "The last {} commits reproduced ({} followed), {} files compared, in {:.1}s",
8870×
                    r.commits - r.skipped,
888
                    r.skipped,
889
                    r.files_compared,
8900×
                    started.elapsed().as_secs_f64()
891
                )
892
            } else {
8930×
                format!(
894
                    "Every commit reproduced: {} commits, {} files compared, in {:.1}s",
895
                    r.commits,
896
                    r.files_compared,
8970×
                    started.elapsed().as_secs_f64()
898
                )
899
            })
900
        );
9010×
        Ok(0)
902
    } else {
903
        // What differs, by kind, the commit taken off: one difference
904
        // carried through history reads as one line.
9050×
        let mut kinds: std::collections::BTreeMap<String, usize> = Default::default();
9060×
        for (_, what) in &r.mismatches {
9070×
            let kind = what.split_once(": ").map_or(what.as_str(), |(_, k)| k);
9080×
            *kinds.entry(kind.to_string()).or_default() += 1;
909
        }
9100×
        let mut kinds: Vec<_> = kinds.into_iter().collect();
9110×
        kinds.sort_by_key(|k| std::cmp::Reverse(k.1));
9120×
        for (kind, n) in kinds.iter().take(10) {
9130×
            println!("  {} {}", ui::dim(format!("{n:>6} ×")), kind);
9140×
        }
9150×
        println!(
916
            "{} differences in {} commits checked{}",
9170×
            r.mismatches.len(),
918
            r.commits,
9190×
            if max > 0 && r.mismatches.len() >= max {
9200×
                format!(" (stopped at {max}; --max-differences 0 checks every commit)")
921
            } else {
9220×
                String::new()
923
            }
924
        );
9250×
        Ok(1)
926
    }
9270×
}
928
9290×
pub fn git_import(
9300×
    git_dir: &std::path::Path,
9310×
    dest: &std::path::Path,
9320×
    branch: &str,
9330×
    claim: bool,
9340×
) -> Result<i32> {
9350×
    let mut repo = Repo::init(dest)?;
9360×
    if claim {
9370×
        claim_commits(&mut repo)?;
9380×
    }
9390×
    let started = std::time::Instant::now();
9400×
    let sp = ui::spinner(&format!("Importing {} {branch}…", git_dir.display()));
9410×
    let r = repo.import_git_with(git_dir, branch, &mut |where_| sp.set(where_))?;
9420×
    sp.clear();
9430×
    println!(
944
        "{} {} ({} merges) from {} {} into {} {}",
9450×
        ui::done("Imported"),
9460×
        plural(r.commits, "commit"),
947
        r.merges,
9480×
        ui::path(git_dir.display()),
9490×
        ui::bookmark(branch),
9500×
        ui::path(repo.root().display()),
9510×
        ui::dim(format!(
952
            "in {:.1?}; {} now has {}",
9530×
            started.elapsed(),
954
            repo.config.bookmark,
9550×
            plural(r.heads, "head")
956
        ))
957
    );
9580×
    if r.submodules > 0 {
9590×
        println!(
960
            "  {} {}",
9610×
            ui::note(),
9620×
            ui::dim(format!(
963
                "{} submodule {} imported as subrepos with Git pins",
964
                r.submodules,
9650×
                if r.submodules == 1 {
9660×
                    "entry"
967
                } else {
9680×
                    "entries"
969
                }
970
            ))
971
        );
9720×
    }
9730×
    Ok(0)
9740×
}
975
9760×
pub fn submodule_add(url: &str, path: &str, bookmark: Option<&str>) -> Result<i32> {
9770×
    let repo = open()?;
9780×
    let sp = ui::spinner(&format!("Cloning {url} into {path}…"));
9790×
    let pin = repo.submodule_add(url, path, bookmark)?;
9800×
    sp.done(&format!(
9810×
        "{} subrepo {} {} {}",
9820×
        ui::done("Added"),
9830×
        ui::path(path),
9840×
        ui::dim(ui::glyph("→", "->")),
9850×
        ui::dim(pin.summary())
9860×
    ));
9870×
    println!(
988
        "  {} {}",
9890×
        ui::note(),
9900×
        ui::dim("recorded in .oxymodules; commit to pin it")
991
    );
9920×
    Ok(0)
9930×
}
994
9950×
pub fn submodule_update(init: bool, paths: &[String]) -> Result<i32> {
9960×
    let repo = open()?;
9970×
    let sp = ui::spinner("Updating subrepos…");
9980×
    let results = repo.submodule_update(init, paths)?;
9990×
    let unpinned: Vec<_> = repo
10000×
        .unpinned_modules()?
10010×
        .into_iter()
10020×
        .filter(|(p, _)| paths.is_empty() || paths.iter().any(|q| q.trim_end_matches('/') == p))
10030×
        .collect();
10040×
    sp.clear();
10050×
    if results.is_empty() && unpinned.is_empty() {
10060×
        println!("{}", ui::dim("No subrepos."));
10070×
    }
10080×
    let code = print_subrepo_results(results);
10090×
    print_unpinned(&unpinned);
10100×
    Ok(if unpinned.is_empty() { code } else { 1 })
10110×
}
1012
1013
/// `.oxymodules` entries never added: nothing to clone, so say how to add
1014
/// them (oxygen#72).
10150×
fn print_unpinned(unpinned: &[(String, oxy_core::subrepo::Module)]) {
10160×
    for (path, m) in unpinned {
10170×
        let url = if m.url.is_empty() { "<url>" } else { &m.url };
10180×
        println!(
1019
            "{} {}",
10200×
            ui::warn(format!(
1021
                "{} in .oxymodules but never added, so no pin",
10220×
                ui::glyph("⚠", "!")
1023
            )),
10240×
            ui::path(path)
1025
        );
10260×
        println!(
1027
            "  {}",
10280×
            ui::dim(format!("add it with: oxy submodule add {url} {path}"))
1029
        );
1030
    }
10310×
}
1032
10330×
fn print_subrepo_results(results: Vec<(String, oxy_core::repo::SubrepoSync)>) -> i32 {
10340×
    let mut code = 0;
10350×
    for (path, r) in results {
1036
        use oxy_core::repo::SubrepoSync::*;
10370×
        let line = match r {
10380×
            Updated => ui::done("Updated"),
10390×
            UpToDate => ui::ok(format!("{} up to date", ui::glyph("✔", "*"))),
1040
            Missing => {
10410×
                code = 1;
10420×
                ui::warn(format!(
1043
                    "{} missing (pass --init to clone)",
10440×
                    ui::glyph("⚠", "!")
1045
                ))
1046
            }
1047
            Dirty => {
10480×
                code = 1;
10490×
                ui::warn(format!(
1050
                    "{} has uncommitted changes; left as is",
10510×
                    ui::glyph("⚠", "!")
1052
                ))
1053
            }
10540×
            KeptBookmark { bookmark, newer } => ui::warn(format!(
1055
                "{} checked out at the pin; its bookmark {bookmark} keeps {} the pin lacks",
10560×
                ui::glyph("⚠", "!"),
10570×
                plural(newer, "newer change")
1058
            )),
10590×
            Failed(e) => {
10600×
                code = 1;
10610×
                ui::err(format!("{} {e}", ui::glyph("✖", "x")))
1062
            }
1063
        };
10640×
        println!("{line} {}", ui::path(path));
1065
    }
10660×
    code
10670×
}
1068
10690×
fn pin_json(p: &oxy_core::subrepo::Pin) -> String {
10700×
    match p {
1071
        oxy_core::subrepo::Pin::Oxy {
10720×
            repo,
10730×
            heads,
10740×
            bookmark,
10750×
        } => json::obj([
10760×
            ("kind", json::s("oxy")),
1077
            (
10780×
                "repo",
10790×
                json::s(&repo.iter().map(|b| format!("{b:02x}")).collect::<String>()),
1080
            ),
10810×
            ("heads", json::hashes(heads)),
10820×
            ("bookmark", json::s(bookmark)),
1083
        ]),
10840×
        oxy_core::subrepo::Pin::Git { sha, branch } => json::obj([
10850×
            ("kind", json::s("git")),
10860×
            ("sha", json::s(sha)),
10870×
            ("branch", json::s(branch)),
10880×
        ]),
1089
    }
10900×
}
1091
10921×
pub fn submodule_status(as_json: bool) -> Result<i32> {
10931×
    let repo = open()?;
10941×
    let subs = repo.subrepos()?;
10951×
    let unpinned = repo.unpinned_modules()?;
10961×
    if as_json {
10971×
        let pinned = subs.iter().map(|s| {
10980×
            json::obj([
10990×
                ("path", json::s(&s.path)),
11000×
                ("pin", pin_json(&s.pin)),
11010×
                ("actual", json::opt(s.actual.as_ref(), pin_json)),
11020×
                ("at_pin", json::b(s.actual.as_ref() == Some(&s.pin))),
11030×
                ("dirty", json::b(s.dirty)),
11040×
                ("committed", json::b(s.committed)),
11050×
                ("url", json::opt(s.url.as_deref(), json::s)),
11060×
            ])
11070×
        });
1108
        // Listed in .oxymodules but never added: no pin at all.
11091×
        let unpinned_json = unpinned.iter().map(|(path, m)| {
11100×
            json::obj([
11110×
                ("path", json::s(path)),
11120×
                ("pin", "null".to_string()),
11130×
                ("actual", "null".to_string()),
11140×
                ("at_pin", json::b(false)),
11150×
                ("dirty", json::b(false)),
11160×
                ("committed", json::b(false)),
11170×
                ("url", json::s(&m.url)),
11180×
            ])
11190×
        });
11201×
        println!("{}", json::arr(pinned.chain(unpinned_json)));
11211×
        return Ok(0);
11220×
    }
11230×
    if subs.is_empty() && unpinned.is_empty() {
11240×
        println!("{}", ui::dim("No subrepos."));
11250×
    }
11260×
    for s in subs {
11270×
        let state = match (&s.actual, s.dirty) {
11280×
            _ if !s.committed => {
11290×
                ui::warn(format!("{} added, not committed yet", ui::glyph("+", "+")))
1130
            }
11310×
            (None, _) => ui::warn(format!("{} missing", ui::glyph("⚠", "!"))),
11320×
            (Some(a), dirty) if *a == s.pin => {
11330×
                if dirty {
11340×
                    ui::warn(format!(
1135
                        "{} at pin, uncommitted changes",
11360×
                        ui::glyph("✎", "~")
1137
                    ))
1138
                } else {
11390×
                    ui::ok(format!("{} at pin", ui::glyph("✔", "*")))
1140
                }
1141
            }
11420×
            (Some(a), _) => ui::warn(format!("{} at {}", ui::glyph("↕", "<>"), a.summary())),
1143
        };
11440×
        println!(
1145
            "{} {}{}{}{}{state}",
11460×
            ui::ok(ui::glyph("⧉", "#")),
11470×
            ui::path(&s.path),
11480×
            ui::sep(),
11490×
            ui::dim(s.pin.summary()),
11500×
            ui::sep()
1151
        );
11520×
        if let Some(u) = s.url {
11530×
            println!("    {} {}", ui::dim(ui::glyph("↳", "->")), ui::dim(u));
11540×
        }
1155
    }
11560×
    print_unpinned(&unpinned);
11570×
    Ok(0)
11581×
}
1159
11600×
pub fn submodule_remove(path: &str) -> Result<i32> {
11610×
    let repo = open()?;
11620×
    repo.submodule_remove(path)?;
11630×
    println!(
1164
        "{} subrepo {} {}",
11650×
        ui::done("Removed"),
11660×
        ui::path(path),
11670×
        ui::dim("(directory left in place; commit to record the removal)")
1168
    );
11690×
    Ok(0)
11700×
}
1171
11720×
pub fn deepen(remote: &str, depth: u32) -> Result<i32> {
11730×
    let repo = open()?;
11740×
    if !repo.is_shallow() {
11750×
        println!(
1176
            "{}",
11770×
            ui::dim("This repository is not shallow; nothing to deepen.")
1178
        );
11790×
        return Ok(0);
11800×
    }
11810×
    let sp = ui::spinner(&format!("Fetching {depth} more levels from {remote}…"));
11820×
    let n = repo.deepen(remote, depth)?;
11830×
    sp.done(&format!(
1184
        "{} {}; {}",
11850×
        ui::done("Deepened by"),
11860×
        plural(n, "change"),
11870×
        if repo.is_shallow() {
11880×
            "still shallow".to_string()
1189
        } else {
11900×
            ui::ok("history is now complete")
1191
        }
1192
    ));
11930×
    Ok(0)
11940×
}