OXYGENHUB

Coverage / src/cli/sync.rs 40.6%

367 of 905 lines run, 32 of 138 functions · run #252 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!(
5271×
            "{} {}",
5281×
            ui::ok(ui::glyph("✔", "*")),
5291×
            ui::dim(format!(
5301×
                "{} is up to date with {remote}.",
5311×
                repo.config.bookmark
5321×
            ))
5331×
        ));
5341×
        others_pulled(&r.others);
5351×
        others_behind(&repo, &remote);
5361×
        return Ok(0);
5372×
    }
5382×
    sp.done(&format!(
539
        "{} {} now has {}{}",
5402×
        ui::done("Pulled:"),
5412×
        ui::bookmark(&repo.config.bookmark),
5422×
        plural(r.heads.len(), "head"),
5432×
        ui::dim(if r.checked_out {
5442×
            "; working copy updated"
545
        } else {
5460×
            "; run oxy checkout to update the working copy"
547
        })
548
    ));
5492×
    let snap = repo.snapshot("oxy pull")?;
5502×
    if snap.base_snapshot.is_conflicted() {
5510×
        println!(
5520×
            "  {} {}",
5530×
            ui::caution(),
5540×
            ui::warn("the result has conflicts; see oxy status")
5550×
        );
5562×
    }
5572×
    others_pulled(&r.others);
5582×
    others_behind(&repo, &remote);
5592×
    subrepos_behind(&repo);
5602×
    super::workspace::where_now(&repo);
5612×
    Ok(0)
5624×
}
563
564
/// The other bookmarks a pull moved.
5653×
fn others_pulled(others: &[String]) {
5663×
    if others.is_empty() {
5672×
        return;
5681×
    }
5691×
    let shown: Vec<String> = others.iter().take(8).map(ui::bookmark).collect();
5701×
    let more = others.len().saturating_sub(8);
5711×
    println!(
572
        "  {} {}{}",
5731×
        ui::done("Also updated"),
5741×
        shown.join(", "),
5751×
        if more > 0 {
5760×
            ui::dim(format!(" and {more} more"))
577
        } else {
5781×
            String::new()
579
        }
580
    );
5813×
}
582
583
/// `oxy push [REMOTE] --delete NAME`.
5840×
pub fn push_delete(remote: Option<&str>, name: &str, as_json: bool) -> Result<i32> {
5850×
    let repo = open()?;
5860×
    let remote = remote_name(&repo, remote);
5870×
    let sp = ui::spinner(&format!("Deleting {remote}/{name}…"));
5880×
    let results = repo.push_delete(&remote, name)?;
5890×
    sp.clear();
5900×
    if as_json {
5910×
        println!(
592
            "{}",
5930×
            json::arr(results.iter().map(|r| {
5940×
                json::obj([
5950×
                    ("name", json::s(&r.name)),
5960×
                    ("ok", json::b(r.ok)),
5970×
                    ("reason", json::s(&r.reason)),
5980×
                    ("state", json::s("")),
5990×
                ])
6000×
            }))
601
        );
6020×
        return Ok(if results.iter().all(|r| r.ok) { 0 } else { 1 });
6030×
    }
6040×
    let mut code = 0;
6050×
    for r in results {
6060×
        if r.ok {
6070×
            println!(
6080×
                "{} {}",
6090×
                ui::done("Deleted"),
6100×
                ui::id(format!("{remote}/{}", r.name))
6110×
            );
6120×
        } else {
6130×
            println!(
6140×
                "{} {} {}{}{}",
6150×
                ui::err(ui::glyph("✖", "x")),
6160×
                ui::err("Rejected"),
6170×
                ui::id(format!("{remote}/{}", r.name)),
6180×
                ui::sep(),
6190×
                r.reason
6200×
            );
6210×
            code = 1;
6220×
        }
623
    }
6240×
    Ok(code)
6250×
}
626
6277×
pub fn push(
6287×
    remote: Option<&str>,
6297×
    force: bool,
6307×
    bookmark: Option<&str>,
6317×
    as_json: bool,
6327×
) -> Result<i32> {
6337×
    let repo = open()?;
6347×
    let remote = remote_name(&repo, remote);
6357×
    let sp = ui::spinner(&format!("Pushing to {remote}…"));
6367×
    let results = match bookmark {
6371×
        Some(b) => repo.push_bookmark(&remote, b, force)?,
6386×
        None => repo.push(&remote, force)?,
639
    };
6406×
    sp.clear();
6416×
    if as_json {
642
        // The state each accepted bookmark now holds on the remote (its local
643
        // state object), so a caller can look up what the push started, such
644
        // as the checks a forge runs on it.
6451×
        let view = repo.view()?;
6461×
        println!(
647
            "{}",
6481×
            json::arr(results.iter().map(|r| {
6491×
                let state = view
6501×
                    .bookmarks
6511×
                    .get(&r.name)
6521×
                    .filter(|_| r.ok)
6531×
                    .map(|st| st.to_hex())
6541×
                    .unwrap_or_default();
6551×
                json::obj([
6561×
                    ("name", json::s(&r.name)),
6571×
                    ("ok", json::b(r.ok)),
6581×
                    ("reason", json::s(&r.reason)),
6591×
                    ("state", json::s(&state)),
6601×
                ])
6611×
            }))
662
        );
6631×
        return Ok(if results.iter().all(|r| r.ok) { 0 } else { 1 });
6645×
    }
6655×
    let mut code = 0;
6665×
    for r in results {
6675×
        if r.ok {
6685×
            println!(
669
                "{} {}{}{}",
6705×
                ui::done("Pushed"),
6715×
                ui::id(format!("{remote}/{}", r.name)),
6725×
                ui::sep(),
6735×
                ui::dim(if r.reason.is_empty() {
6745×
                    "updated"
675
                } else {
6760×
                    r.reason.as_str()
677
                })
678
            );
6790×
        } else {
6800×
            println!(
6810×
                "{} {} {}{}{}",
6820×
                ui::err(ui::glyph("✖", "x")),
6830×
                ui::err("Rejected"),
6840×
                ui::id(format!("{remote}/{}", r.name)),
6850×
                ui::sep(),
6860×
                r.reason
6870×
            );
6880×
            code = 1;
6890×
        }
690
    }
6915×
    Ok(code)
6927×
}
693
6940×
pub fn serve(
6950×
    root: PathBuf,
6960×
    bind: &str,
6970×
    tokens: Vec<String>,
6980×
    tls: Option<(PathBuf, PathBuf)>,
6990×
) -> Result<i32> {
7000×
    let listener = std::net::TcpListener::bind(bind).with_context(|| format!("binding {bind}"))?;
7010×
    let root = root.canonicalize()?;
7020×
    let tls = tls.map(|(cert, key)| oxy_server::TlsFiles { cert, key });
7030×
    println!(
704
        "Serving repositories under {} on {}://{bind}/<repo>/oxy/v1/ ({})",
7050×
        root.display(),
7060×
        if tls.is_some() { "https" } else { "http" },
7070×
        if tokens.is_empty() {
7080×
            "open: no push tokens configured"
709
        } else {
7100×
            "push requires a token"
711
        }
712
    );
7130×
    if tls.is_none()
7140×
        && !bind.starts_with("127.")
7150×
        && !bind.starts_with("localhost")
7160×
        && !bind.starts_with("[::1]")
7170×
    {
7180×
        eprintln!("warning: serving plain HTTP on a non-loopback address; put a TLS terminator in front or pass --tls-cert/--tls-key");
7190×
    }
7200×
    oxy_server::run_blocking(listener, oxy_server::ServerConfig { root, tokens, tls })?;
7210×
    Ok(0)
7220×
}
723
7240×
pub fn git_export(git_dir: &std::path::Path, branch: Option<&str>) -> Result<i32> {
7250×
    let repo = open()?;
7260×
    let sp = ui::spinner("Exporting to Git…");
7270×
    let r = match branch {
7280×
        Some(b) => repo.git_export_as(git_dir, b)?,
7290×
        None => repo.git_export(git_dir)?,
730
    };
7310×
    sp.clear();
7320×
    println!(
733
        "{} {} to {} as branch {} {}",
7340×
        ui::done("Exported"),
7350×
        plural(r.exported, "new state"),
7360×
        ui::path(git_dir.display()),
7370×
        ui::bookmark(&r.branch),
7380×
        ui::dim(format!(
739
            "(currently {}; {} already exported)",
7400×
            plural(r.heads, "head"),
741
            r.skipped
742
        ))
743
    );
7440×
    Ok(0)
7450×
}
746
7470×
pub fn git_recover() -> Result<i32> {
7480×
    let repo = open()?;
7490×
    let sp = ui::spinner("Reading the store…");
7500×
    let (changes, heads) = repo.recover_git_import(&|m| sp.set(m))?;
7510×
    sp.done(&format!(
7520×
        "{} {} from imported Git commits: {} now has {}",
7530×
        ui::done("Recovered"),
7540×
        plural(changes, "change"),
7550×
        ui::bookmark(&repo.config.bookmark),
7560×
        plural(heads, "head")
7570×
    ));
7580×
    println!(
759
        "  {} {}",
7600×
        ui::note(),
7610×
        ui::dim("carry on with oxy git fetch GIT_DIR --branch BRANCH")
762
    );
7630×
    Ok(0)
7640×
}
765
7660×
pub fn git_fetch(url: &str, branch: &str) -> Result<i32> {
7670×
    let repo = open()?;
7680×
    let sp = ui::spinner(&format!("Fetching {url} {branch}…"));
7690×
    let r = repo.git_fetch(url, branch)?;
7700×
    sp.clear();
7710×
    if r.commits == 0 {
7720×
        println!(
7730×
            "{} {}",
7740×
            ui::done("Fetched"),
7750×
            ui::dim(format!("nothing new from {url} {branch}"))
7760×
        );
7770×
    } else {
7780×
        println!(
779
            "{} {} ({} merges) from {} {}{}{} now has {}",
7800×
            ui::done("Fetched"),
7810×
            plural(r.commits, "new commit"),
782
            r.merges,
7830×
            ui::path(url),
7840×
            ui::bookmark(branch),
7850×
            ui::sep(),
7860×
            ui::bookmark(&repo.config.bookmark),
7870×
            plural(r.heads, "head")
788
        );
7890×
        if !repo.snapshot("oxy git fetch")?.changed {
7900×
            println!("  {} {}", ui::note(), ui::dim("working copy updated"));
7910×
        } else {
7920×
            println!(
7930×
                "  {} {}",
7940×
                ui::note(),
7950×
                ui::dim("run oxy checkout to update the working copy")
7960×
            );
7970×
        }
798
    }
7990×
    if r.submodules > 0 {
8000×
        println!(
801
            "  {} {}",
8020×
            ui::note(),
8030×
            ui::dim(format!(
804
                "{} submodule {} imported as subrepos with Git pins",
805
                r.submodules,
8060×
                if r.submodules == 1 {
8070×
                    "entry"
808
                } else {
8090×
                    "entries"
810
                }
811
            ))
812
        );
8130×
    }
8140×
    Ok(0)
8150×
}
816
8170×
pub fn git_push(url: &str, branch: &str) -> Result<i32> {
8180×
    let repo = open()?;
8190×
    let sp = ui::spinner(&format!("Pushing to {url} {branch}…"));
8200×
    let r = repo.git_push(url, branch)?;
8210×
    sp.clear();
8220×
    println!(
823
        "{} {} to {} {} {}",
8240×
        ui::done("Pushed"),
8250×
        plural(r.exported, "new commit"),
8260×
        ui::path(url),
8270×
        ui::bookmark(&r.branch),
8280×
        ui::dim(format!("({} already there)", r.skipped))
829
    );
8300×
    Ok(0)
8310×
}
832
833
/// `oxy git verify`: exit 1 if any commit's tree is not reproduced.
8340×
pub fn git_verify(git_dir: &std::path::Path, branch: &str, last: Option<usize>) -> Result<i32> {
8350×
    let repo = open()?;
8360×
    let started = std::time::Instant::now();
8370×
    let sp = ui::spinner(&format!(
8380×
        "Rebuilding every commit of {} {branch}…",
8390×
        git_dir.display()
8400×
    ));
8410×
    let r = repo.verify_git_import_last(git_dir, branch, last)?;
8420×
    sp.clear();
8430×
    for (_, what) in &r.mismatches {
8440×
        println!("{} {what}", ui::err(ui::glyph("✖", "x")));
8450×
    }
8460×
    if r.not_yet > 0 {
8470×
        println!(
8480×
            "  {} {}",
8490×
            ui::note(),
8500×
            ui::dim(format!(
8510×
                "{} not imported yet, after the last imported commit: not checked",
8520×
                plural(r.not_yet, "commit")
8530×
            ))
8540×
        );
8550×
    }
8560×
    if r.mismatches.is_empty() {
8570×
        println!(
858
            "{}",
8590×
            ui::done(if r.skipped > 0 {
8600×
                format!(
861
                    "The last {} commits reproduced ({} followed), {} files compared, in {:.1}s",
8620×
                    r.commits - r.skipped,
863
                    r.skipped,
864
                    r.files_compared,
8650×
                    started.elapsed().as_secs_f64()
866
                )
867
            } else {
8680×
                format!(
869
                    "Every commit reproduced: {} commits, {} files compared, in {:.1}s",
870
                    r.commits,
871
                    r.files_compared,
8720×
                    started.elapsed().as_secs_f64()
873
                )
874
            })
875
        );
8760×
        Ok(0)
877
    } else {
8780×
        println!(
879
            "{} differences in {} commits checked",
8800×
            r.mismatches.len(),
881
            r.commits
882
        );
8830×
        Ok(1)
884
    }
8850×
}
886
8870×
pub fn git_import(git_dir: &std::path::Path, dest: &std::path::Path, branch: &str) -> Result<i32> {
8880×
    let repo = Repo::init(dest)?;
8890×
    let started = std::time::Instant::now();
8900×
    let sp = ui::spinner(&format!("Importing {} {branch}…", git_dir.display()));
8910×
    let r = repo.import_git_with(git_dir, branch, &mut |where_| sp.set(where_))?;
8920×
    sp.clear();
8930×
    println!(
894
        "{} {} ({} merges) from {} {} into {} {}",
8950×
        ui::done("Imported"),
8960×
        plural(r.commits, "commit"),
897
        r.merges,
8980×
        ui::path(git_dir.display()),
8990×
        ui::bookmark(branch),
9000×
        ui::path(repo.root().display()),
9010×
        ui::dim(format!(
902
            "in {:.1?}; {} now has {}",
9030×
            started.elapsed(),
904
            repo.config.bookmark,
9050×
            plural(r.heads, "head")
906
        ))
907
    );
9080×
    if r.submodules > 0 {
9090×
        println!(
910
            "  {} {}",
9110×
            ui::note(),
9120×
            ui::dim(format!(
913
                "{} submodule {} imported as subrepos with Git pins",
914
                r.submodules,
9150×
                if r.submodules == 1 {
9160×
                    "entry"
917
                } else {
9180×
                    "entries"
919
                }
920
            ))
921
        );
9220×
    }
9230×
    Ok(0)
9240×
}
925
9260×
pub fn submodule_add(url: &str, path: &str, bookmark: Option<&str>) -> Result<i32> {
9270×
    let repo = open()?;
9280×
    let sp = ui::spinner(&format!("Cloning {url} into {path}…"));
9290×
    let pin = repo.submodule_add(url, path, bookmark)?;
9300×
    sp.done(&format!(
9310×
        "{} subrepo {} {} {}",
9320×
        ui::done("Added"),
9330×
        ui::path(path),
9340×
        ui::dim(ui::glyph("→", "->")),
9350×
        ui::dim(pin.summary())
9360×
    ));
9370×
    println!(
938
        "  {} {}",
9390×
        ui::note(),
9400×
        ui::dim("recorded in .oxymodules; commit to pin it")
941
    );
9420×
    Ok(0)
9430×
}
944
9450×
pub fn submodule_update(init: bool, paths: &[String]) -> Result<i32> {
9460×
    let repo = open()?;
9470×
    let sp = ui::spinner("Updating subrepos…");
9480×
    let results = repo.submodule_update(init, paths)?;
9490×
    let unpinned: Vec<_> = repo
9500×
        .unpinned_modules()?
9510×
        .into_iter()
9520×
        .filter(|(p, _)| paths.is_empty() || paths.iter().any(|q| q.trim_end_matches('/') == p))
9530×
        .collect();
9540×
    sp.clear();
9550×
    if results.is_empty() && unpinned.is_empty() {
9560×
        println!("{}", ui::dim("No subrepos."));
9570×
    }
9580×
    let code = print_subrepo_results(results);
9590×
    print_unpinned(&unpinned);
9600×
    Ok(if unpinned.is_empty() { code } else { 1 })
9610×
}
962
963
/// `.oxymodules` entries never added: nothing to clone, so say how to add
964
/// them (oxygen#72).
9650×
fn print_unpinned(unpinned: &[(String, oxy_core::subrepo::Module)]) {
9660×
    for (path, m) in unpinned {
9670×
        let url = if m.url.is_empty() { "<url>" } else { &m.url };
9680×
        println!(
969
            "{} {}",
9700×
            ui::warn(format!(
971
                "{} in .oxymodules but never added, so no pin",
9720×
                ui::glyph("⚠", "!")
973
            )),
9740×
            ui::path(path)
975
        );
9760×
        println!(
977
            "  {}",
9780×
            ui::dim(format!("add it with: oxy submodule add {url} {path}"))
979
        );
980
    }
9810×
}
982
9830×
fn print_subrepo_results(results: Vec<(String, oxy_core::repo::SubrepoSync)>) -> i32 {
9840×
    let mut code = 0;
9850×
    for (path, r) in results {
986
        use oxy_core::repo::SubrepoSync::*;
9870×
        let line = match r {
9880×
            Updated => ui::done("Updated"),
9890×
            UpToDate => ui::ok(format!("{} up to date", ui::glyph("✔", "*"))),
990
            Missing => {
9910×
                code = 1;
9920×
                ui::warn(format!(
993
                    "{} missing (pass --init to clone)",
9940×
                    ui::glyph("⚠", "!")
995
                ))
996
            }
997
            Dirty => {
9980×
                code = 1;
9990×
                ui::warn(format!(
1000
                    "{} has uncommitted changes; left as is",
10010×
                    ui::glyph("⚠", "!")
1002
                ))
1003
            }
10040×
            KeptBookmark { bookmark, newer } => ui::warn(format!(
1005
                "{} checked out at the pin; its bookmark {bookmark} keeps {} the pin lacks",
10060×
                ui::glyph("⚠", "!"),
10070×
                plural(newer, "newer change")
1008
            )),
10090×
            Failed(e) => {
10100×
                code = 1;
10110×
                ui::err(format!("{} {e}", ui::glyph("✖", "x")))
1012
            }
1013
        };
10140×
        println!("{line} {}", ui::path(path));
1015
    }
10160×
    code
10170×
}
1018
10190×
fn pin_json(p: &oxy_core::subrepo::Pin) -> String {
10200×
    match p {
1021
        oxy_core::subrepo::Pin::Oxy {
10220×
            repo,
10230×
            heads,
10240×
            bookmark,
10250×
        } => json::obj([
10260×
            ("kind", json::s("oxy")),
1027
            (
10280×
                "repo",
10290×
                json::s(&repo.iter().map(|b| format!("{b:02x}")).collect::<String>()),
1030
            ),
10310×
            ("heads", json::hashes(heads)),
10320×
            ("bookmark", json::s(bookmark)),
1033
        ]),
10340×
        oxy_core::subrepo::Pin::Git { sha, branch } => json::obj([
10350×
            ("kind", json::s("git")),
10360×
            ("sha", json::s(sha)),
10370×
            ("branch", json::s(branch)),
10380×
        ]),
1039
    }
10400×
}
1041
10421×
pub fn submodule_status(as_json: bool) -> Result<i32> {
10431×
    let repo = open()?;
10441×
    let subs = repo.subrepos()?;
10451×
    let unpinned = repo.unpinned_modules()?;
10461×
    if as_json {
10471×
        let pinned = subs.iter().map(|s| {
10480×
            json::obj([
10490×
                ("path", json::s(&s.path)),
10500×
                ("pin", pin_json(&s.pin)),
10510×
                ("actual", json::opt(s.actual.as_ref(), pin_json)),
10520×
                ("at_pin", json::b(s.actual.as_ref() == Some(&s.pin))),
10530×
                ("dirty", json::b(s.dirty)),
10540×
                ("committed", json::b(s.committed)),
10550×
                ("url", json::opt(s.url.as_deref(), json::s)),
10560×
            ])
10570×
        });
1058
        // Listed in .oxymodules but never added: no pin at all.
10591×
        let unpinned_json = unpinned.iter().map(|(path, m)| {
10600×
            json::obj([
10610×
                ("path", json::s(path)),
10620×
                ("pin", "null".to_string()),
10630×
                ("actual", "null".to_string()),
10640×
                ("at_pin", json::b(false)),
10650×
                ("dirty", json::b(false)),
10660×
                ("committed", json::b(false)),
10670×
                ("url", json::s(&m.url)),
10680×
            ])
10690×
        });
10701×
        println!("{}", json::arr(pinned.chain(unpinned_json)));
10711×
        return Ok(0);
10720×
    }
10730×
    if subs.is_empty() && unpinned.is_empty() {
10740×
        println!("{}", ui::dim("No subrepos."));
10750×
    }
10760×
    for s in subs {
10770×
        let state = match (&s.actual, s.dirty) {
10780×
            _ if !s.committed => {
10790×
                ui::warn(format!("{} added, not committed yet", ui::glyph("+", "+")))
1080
            }
10810×
            (None, _) => ui::warn(format!("{} missing", ui::glyph("⚠", "!"))),
10820×
            (Some(a), dirty) if *a == s.pin => {
10830×
                if dirty {
10840×
                    ui::warn(format!(
1085
                        "{} at pin, uncommitted changes",
10860×
                        ui::glyph("✎", "~")
1087
                    ))
1088
                } else {
10890×
                    ui::ok(format!("{} at pin", ui::glyph("✔", "*")))
1090
                }
1091
            }
10920×
            (Some(a), _) => ui::warn(format!("{} at {}", ui::glyph("↕", "<>"), a.summary())),
1093
        };
10940×
        println!(
1095
            "{} {}{}{}{}{state}",
10960×
            ui::ok(ui::glyph("⧉", "#")),
10970×
            ui::path(&s.path),
10980×
            ui::sep(),
10990×
            ui::dim(s.pin.summary()),
11000×
            ui::sep()
1101
        );
11020×
        if let Some(u) = s.url {
11030×
            println!("    {} {}", ui::dim(ui::glyph("↳", "->")), ui::dim(u));
11040×
        }
1105
    }
11060×
    print_unpinned(&unpinned);
11070×
    Ok(0)
11081×
}
1109
11100×
pub fn submodule_remove(path: &str) -> Result<i32> {
11110×
    let repo = open()?;
11120×
    repo.submodule_remove(path)?;
11130×
    println!(
1114
        "{} subrepo {} {}",
11150×
        ui::done("Removed"),
11160×
        ui::path(path),
11170×
        ui::dim("(directory left in place; commit to record the removal)")
1118
    );
11190×
    Ok(0)
11200×
}
1121
11220×
pub fn deepen(remote: &str, depth: u32) -> Result<i32> {
11230×
    let repo = open()?;
11240×
    if !repo.is_shallow() {
11250×
        println!(
1126
            "{}",
11270×
            ui::dim("This repository is not shallow; nothing to deepen.")
1128
        );
11290×
        return Ok(0);
11300×
    }
11310×
    let sp = ui::spinner(&format!("Fetching {depth} more levels from {remote}…"));
11320×
    let n = repo.deepen(remote, depth)?;
11330×
    sp.done(&format!(
1134
        "{} {}; {}",
11350×
        ui::done("Deepened by"),
11360×
        plural(n, "change"),
11370×
        if repo.is_shallow() {
11380×
            "still shallow".to_string()
1139
        } else {
11400×
            ui::ok("history is now complete")
1141
        }
1142
    ));
11430×
    Ok(0)
11440×
}