OXYGENHUB
◆ v0.4.6 oxygen / src / cli / sync.rs
37.7 KiB · Rust · last changed remote remove: remove all of the remote 25 days ago source blame history raw
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
11
pub fn clone(
12
    url: &str,
13
    dest: Option<PathBuf>,
14
    max_blob: Option<&str>,
15
    sparse: &[String],
16
    depth: Option<u32>,
17
    recursive: bool,
18
) -> Result<i32> {
19
    let dest = dest.unwrap_or_else(|| {
20
        let base = url
21
            .trim_end_matches('/')
22
            .rsplit('/')
23
            .next()
24
            .unwrap_or("repo");
25
        PathBuf::from(base)
26
    });
27
    let max_blob = max_blob.map(oxy_core::repo::parse_size).transpose()?;
28
    let sp = ui::spinner(&format!("Cloning {url}…"));
29
    let repo = match depth {
30
        Some(d) => Repo::clone_shallow(url, &dest, d, max_blob, sparse)?,
31
        None => Repo::clone_with(url, &dest, max_blob, sparse)?,
32
    };
33
    let heads = repo.bookmark_heads()?;
34
    sp.done(&format!(
35
        "{} into {} {}",
36
        ui::done("Cloned"),
37
        ui::path(repo.root().display()),
38
        ui::dim(format!(
39
            "({url}, {} with {})",
40
            ui::bookmark(&repo.config.bookmark),
41
            plural(heads.len(), "head")
42
        ))
43
    ));
44
    let others = repo.remote_only_bookmarks()?.len();
45
    if others > 0 {
46
        println!(
47
            "  {} {}",
48
            ui::note(),
49
            ui::dim(format!(
50
                "origin has {} more: oxy bookmark list --all, then oxy bookmark switch NAME",
51
                plural(others, "bookmark")
52
            ))
53
        );
54
    }
55
    let subrepos = repo.subrepos()?.len();
56
    if subrepos == 0 {
57
        return Ok(0);
58
    }
59
    if recursive {
60
        let sp = ui::spinner("Cloning subrepos…");
61
        let results = repo.submodule_update(true, &[])?;
62
        sp.clear();
63
        return Ok(print_subrepo_results(results));
64
    }
65
    println!(
66
        "  {} {}",
67
        ui::note(),
68
        ui::dim(format!(
69
            "{} not cloned: oxy submodule update --init (or clone with --recursive)",
70
            plural(subrepos, "subrepo")
71
        ))
72
    );
73
    Ok(0)
74
}
75
76
/// After a switch or pull: say when subrepos are not at their pins.
77
pub fn subrepos_behind(repo: &Repo) {
78
    let Ok(subs) = repo.subrepos() else {
79
        return;
80
    };
81
    let stale = subs
82
        .iter()
83
        .filter(|s| s.committed && s.actual.as_ref() != Some(&s.pin))
84
        .count();
85
    if stale > 0 {
86
        println!(
87
            "  {} {}",
88
            ui::note(),
89
            ui::dim(format!(
90
                "{} not at {} pin: oxy submodule update --init",
91
                plural(stale, "subrepo"),
92
                if stale == 1 { "its" } else { "their" }
93
            ))
94
        );
95
    }
96
}
97
98
/// Whether a URL names a store (a bucket or a directory in the store
99
/// layout) rather than a repository.
100
fn is_store_url(url: &str) -> bool {
101
    ["s3://", "gs://", "az://", "dir://"]
102
        .iter()
103
        .any(|p| url.starts_with(p))
104
}
105
106
/// Percent-encode what would break a query parameter.
107
fn encode_param(v: &str) -> String {
108
    let mut out = String::with_capacity(v.len());
109
    for b in v.bytes() {
110
        match b {
111
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' | b':' => {
112
                out.push(b as char)
113
            }
114
            _ => out.push_str(&format!("%{b:02X}")),
115
        }
116
    }
117
    out
118
}
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`).
122
fn url_with_settings(url: &str, settings: &[(&str, Option<String>)]) -> Result<String> {
123
    let given: Vec<(&str, &str)> = settings
124
        .iter()
125
        .filter_map(|(k, v)| v.as_deref().map(|v| (*k, v)))
126
        .collect();
127
    if given.is_empty() {
128
        return Ok(url.to_string());
129
    }
130
    if !is_store_url(url) || url.starts_with("dir://") {
131
        let names: Vec<String> = given.iter().map(|(k, _)| format!("--{k}")).collect();
132
        anyhow::bail!(
133
            "{} apply to a store remote (s3://, gs://, az://), not to {url}",
134
            names.join(", ")
135
        );
136
    }
137
    let mut out = url.to_string();
138
    for (k, v) in given {
139
        out.push(if out.contains('?') { '&' } else { '?' });
140
        out.push_str(k);
141
        out.push('=');
142
        out.push_str(&encode_param(v));
143
    }
144
    Ok(out)
145
}
146
147
pub fn remote_add(name: &str, url: &str, settings: &[(&str, Option<String>)]) -> Result<i32> {
148
    let mut repo = open()?;
149
    let url = url_with_settings(url, settings)?;
150
    let url = url.as_str();
151
    repo.config.set(
152
        &format!("remote.{name}.url"),
153
        &oxy_core::protocol::stored_url(url),
154
    )?;
155
    repo.save_config()?;
156
    println!(
157
        "{} remote {} {} {url}",
158
        ui::done("Added"),
159
        ui::bookmark(name),
160
        ui::dim(ui::glyph("→", "->"))
161
    );
162
    Ok(0)
163
}
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).
168
pub fn remote_check(name: &str) -> Result<i32> {
169
    let repo = open()?;
170
    let Some(url) = repo.config.remotes.get(name).cloned() else {
171
        anyhow::bail!("no remote {name:?}; oxy remote list shows the remotes there are");
172
    };
173
    let options = repo.options_for_url(&url);
174
    let mine = repo.id()?;
175
    let started = std::time::Instant::now();
176
    let sp = ui::spinner(&format!("Checking {name}…"));
177
    let Some(store) = oxy_core::protocol::open_store(&url, &options) else {
178
        // A hub or another repository: reach it and read its references.
179
        let (_, remote) = repo.open_remote_at(&url)?;
180
        let id = remote.repo_id()?;
181
        let refs = remote.refs()?;
182
        sp.done(&format!(
183
            "{} {} {}",
184
            ui::done("Reachable"),
185
            ui::bookmark(name),
186
            ui::dim(format!("({url}, {} ms)", started.elapsed().as_millis()))
187
        ));
188
        describe_holding(id, mine, refs.refs.len(), refs.tags.len(), None);
189
        return Ok(0);
190
    };
191
    let store = store.with_context(|| format!("opening the store of {name}"))?;
192
    // What it holds, in one listing and two reads.
193
    let marker = match store.get("oxygen.toml") {
194
        Ok(b) => Some(b),
195
        Err(oxy_core::strata::Error::NotFound(_)) => None,
196
        Err(e) => {
197
            sp.clear();
198
            return Err(anyhow::anyhow!("{e}"))
199
                .with_context(|| format!("reaching the store of {name}"));
200
        }
201
    };
202
    let reached = started.elapsed();
203
    let bundles = store.list("bundles/")?.len();
204
    let record = store.read_ref("refs")?;
205
    sp.done(&format!(
206
        "{} {} {}",
207
        ui::done("Reachable"),
208
        ui::bookmark(name),
209
        ui::dim(format!("({url}, {} ms)", reached.as_millis()))
210
    ));
211
    match marker {
212
        None => println!(
213
            "  {} {}",
214
            ui::note(),
215
            ui::dim("holds no repository yet: oxy push NAME binds it to this one")
216
        ),
217
        Some(_) => {
218
            let (id, bookmarks, tags) = match record {
219
                Some((bytes, _)) => {
220
                    let (id, resp) = oxy_core::protocol::wire::decode_refs(&bytes)?;
221
                    (id, resp.refs.len(), resp.tags.len())
222
                }
223
                None => (mine, 0, 0),
224
            };
225
            describe_holding(id, mine, bookmarks, tags, Some(bundles));
226
        }
227
    }
228
    // Then the behaviour a repository depends on, under a prefix of its own.
229
    let sp = ui::spinner("Checking that the store behaves…");
230
    let probe = format!("oxy-check-{}", std::process::id());
231
    let began = std::time::Instant::now();
232
    match oxy_core::strata::conformance(store.as_ref(), &probe) {
233
        Ok(passed) => {
234
            sp.clear();
235
            for p in &passed {
236
                println!("  {} {}", ui::ok(ui::glyph("✔", "*")), p);
237
            }
238
            println!(
239
                "{} {}",
240
                ui::done("Behaves"),
241
                ui::dim(format!(
242
                    "({} checks in {} ms; nothing left behind)",
243
                    passed.len(),
244
                    began.elapsed().as_millis()
245
                ))
246
            );
247
            Ok(0)
248
        }
249
        Err(e) => {
250
            sp.clear();
251
            // Leave nothing behind, even after a failed check.
252
            if let Ok(left) = store.list(&probe) {
253
                for entry in left {
254
                    let _ = store.delete(&entry.key);
255
                }
256
            }
257
            println!("{} {}", ui::err(ui::glyph("✘", "x")), e);
258
            println!(
259
                "  {} {}",
260
                ui::note(),
261
                ui::dim("a store that fails this cannot keep a repository safely; check the service and the credentials' permissions")
262
            );
263
            Ok(1)
264
        }
265
    }
266
}
267
268
fn describe_holding(
269
    id: [u8; 16],
270
    mine: [u8; 16],
271
    bookmarks: usize,
272
    tags: usize,
273
    bundles: Option<usize>,
274
) {
275
    let short: String = id[..6].iter().map(|b| format!("{b:02x}")).collect();
276
    let mut what = format!(
277
        "repository {short}: {} and {}",
278
        plural(bookmarks, "bookmark"),
279
        plural(tags, "tag")
280
    );
281
    if let Some(b) = bundles {
282
        what.push_str(&format!(" in {}", plural(b, "bundle")));
283
    }
284
    if id == mine {
285
        println!("  {} {}", ui::note(), ui::dim(format!("holds this {what}")));
286
    } else if id == oxy_core::protocol::UNBOUND_ID {
287
        println!("  {} {}", ui::note(), ui::dim("holds no repository yet"));
288
    } else {
289
        println!(
290
            "  {} {}",
291
            ui::caution(),
292
            ui::warn(format!("holds another {what}; a push would be refused"))
293
        );
294
    }
295
}
296
297
pub fn remote_remove(name: &str) -> Result<i32> {
298
    let mut repo = open()?;
299
    repo.remove_remote(name)?;
300
    println!("{} remote {}", ui::done("Removed"), ui::bookmark(name));
301
    Ok(0)
302
}
303
304
pub fn remote_list(as_json: bool) -> Result<i32> {
305
    let repo = open()?;
306
    let view = repo.view()?;
307
    if as_json {
308
        let items = repo.config.remotes.iter().map(|(name, url)| {
309
            let bms = view.remotes.get(name).map(|b| {
310
                json::arr(b.iter().map(|(bm, st)| {
311
                    let heads = repo
312
                        .store()
313
                        .get_state(st)
314
                        .map(|s| s.heads)
315
                        .unwrap_or_default();
316
                    json::obj([("name", json::s(bm)), ("heads", json::hashes(&heads))])
317
                }))
318
            });
319
            json::obj([
320
                ("name", json::s(name)),
321
                ("url", json::s(url)),
322
                // The CA file `remote.NAME.ca` names, for tools that talk to
323
                // the same hub (an editor's forge view, `oh`).
324
                (
325
                    "ca",
326
                    json::opt(repo.config.remote_cas.get(name), |c| json::s(c)),
327
                ),
328
                ("bookmarks", bms.unwrap_or_else(|| "[]".into())),
329
            ])
330
        });
331
        println!("{}", json::arr(items));
332
        return Ok(0);
333
    }
334
    if repo.config.remotes.is_empty() {
335
        println!(
336
            "{}",
337
            ui::dim("No remotes; add one with oxy remote add <name> <url>.")
338
        );
339
    }
340
    for (name, url) in &repo.config.remotes {
341
        println!(
342
            "{} {}{}{}",
343
            ui::ok(ui::glyph("⇄", "<>")),
344
            ui::bookmark(name),
345
            ui::sep(),
346
            ui::dim(url)
347
        );
348
        if let Some(bms) = view.remotes.get(name) {
349
            for (bm, st) in bms {
350
                let heads = repo
351
                    .store()
352
                    .get_state(st)
353
                    .map(|s| s.heads.len())
354
                    .unwrap_or(0);
355
                println!(
356
                    "    {} {}{}{}",
357
                    ui::dim(ui::glyph("↳", "->")),
358
                    ui::id(format!("{name}/{bm}")),
359
                    ui::sep(),
360
                    ui::dim(plural(heads, "head"))
361
                );
362
            }
363
        }
364
    }
365
    Ok(0)
366
}
367
368
/// The remote named, else `origin`, else the only remote there is.
369
fn remote_name(repo: &oxy_core::repo::Repo, remote: Option<&str>) -> String {
370
    remote.map_or_else(|| repo.default_remote(), str::to_string)
371
}
372
373
pub fn fetch(remote: Option<&str>, as_json: bool) -> Result<i32> {
374
    let repo = open()?;
375
    let remote = remote_name(&repo, remote);
376
    let sp = ui::spinner(&format!("Fetching from {remote}…"));
377
    let report = repo.fetch(&remote)?;
378
    sp.clear();
379
    if as_json {
380
        println!(
381
            "{}",
382
            json::obj([
383
                ("remote", json::s(&remote)),
384
                (
385
                    "refs",
386
                    json::arr(report.refs.iter().map(|(name, heads, n)| {
387
                        let t = repo.tracking(&remote, name).ok().flatten();
388
                        json::obj([
389
                            ("name", json::s(name)),
390
                            ("heads", json::hashes(heads)),
391
                            ("new", json::n(*n)),
392
                            (
393
                                "ahead",
394
                                t.map_or_else(|| "null".into(), |(a, _)| json::n(a)),
395
                            ),
396
                            (
397
                                "behind",
398
                                t.map_or_else(|| "null".into(), |(_, b)| json::n(b)),
399
                            ),
400
                        ])
401
                    }))
402
                ),
403
                ("new_tags", json::n(report.new_tags)),
404
                ("unverified", json::b(report.unverified)),
405
            ])
406
        );
407
        return Ok(0);
408
    }
409
    if report.refs.is_empty() {
410
        println!(
411
            "{} {}",
412
            ui::done("Fetched"),
413
            ui::dim(format!("nothing new from {remote}"))
414
        );
415
    }
416
    for (name, heads, n) in &report.refs {
417
        // What was fetched, then how the local bookmark stands against it:
418
        // "up to date" only when the two are the same (oxygen#56).
419
        let fetched =
420
            (*n > 0).then(|| format!("{}{}", ui::ok(plural(*n, "new change")), ui::sep()));
421
        let them = |k: usize| if k == 1 { "it" } else { "them" };
422
        let standing = match repo.tracking(&remote, name).ok().flatten() {
423
            None => ui::dim(format!("no local bookmark {name}")),
424
            Some((0, 0)) => ui::dim(format!("{name} up to date")),
425
            Some((0, b)) if *name == repo.config.bookmark => ui::warn(format!(
426
                "{name} is {} behind: oxy pull to take {}",
427
                plural(b, "change"),
428
                them(b)
429
            )),
430
            Some((0, b)) => ui::warn(format!(
431
                "{name} is {} behind: oxy bookmark switch {name} then oxy pull to take {}",
432
                plural(b, "change"),
433
                them(b)
434
            )),
435
            Some((a, 0)) => ui::dim(format!(
436
                "{name} is {} ahead: oxy push to send {}",
437
                plural(a, "change"),
438
                them(a)
439
            )),
440
            Some((a, b)) => ui::warn(format!(
441
                "{name} and {remote}/{name} have diverged ({a} here, {b} there): oxy pull to merge them"
442
            )),
443
        };
444
        let what = format!("{}{standing}", fetched.unwrap_or_default());
445
        println!(
446
            "{} {}{}{}{}{what}",
447
            ui::done("Fetched"),
448
            ui::id(format!("{remote}/{name}")),
449
            ui::sep(),
450
            ui::dim(plural(heads.len(), "head")),
451
            ui::sep()
452
        );
453
    }
454
    if report.new_tags > 0 {
455
        println!(
456
            "  {} {}",
457
            ui::note(),
458
            ui::dim(format!("{} adopted", plural(report.new_tags, "tag")))
459
        );
460
    }
461
    if report.unverified {
462
        eprintln!(
463
            "{} {remote} has no trust policy; nothing fetched from it was verified",
464
            ui::caution()
465
        );
466
    }
467
    Ok(0)
468
}
469
470
/// Pull acts on the current bookmark only: name the others the fetch
471
/// found behind their remote, which is easy to take for the current one
472
/// (oxygen#29).
473
fn others_behind(repo: &oxy_core::repo::Repo, remote: &str) {
474
    let Ok(bookmarks) = repo.bookmarks() else {
475
        return;
476
    };
477
    for b in bookmarks {
478
        let Some(n) = b.behind.filter(|n| *n > 0) else {
479
            continue;
480
        };
481
        if b.current {
482
            continue;
483
        }
484
        println!(
485
            "  {} {}",
486
            ui::note(),
487
            ui::dim(format!(
488
                "{} is {} behind {remote}/{}: oxy bookmark switch {} then oxy pull to take {}",
489
                b.name,
490
                plural(n, "change"),
491
                b.name,
492
                b.name,
493
                if n == 1 { "it" } else { "them" }
494
            ))
495
        );
496
    }
497
}
498
499
pub fn pull(remote: Option<&str>, as_json: bool) -> Result<i32> {
500
    let repo = open()?;
501
    let remote = remote_name(&repo, remote);
502
    let sp = ui::spinner(&format!("Pulling from {remote}…"));
503
    let r = repo.pull(&remote)?;
504
    if as_json {
505
        sp.clear();
506
        let conflicted = repo
507
            .snapshot_status("oxy pull")?
508
            .base_snapshot
509
            .is_conflicted();
510
        println!(
511
            "{}",
512
            json::obj([
513
                ("remote", json::s(&remote)),
514
                ("bookmark", json::s(&repo.config.bookmark)),
515
                ("heads", json::hashes(&r.heads)),
516
                ("changed", json::b(r.changed)),
517
                ("checked_out", json::b(r.checked_out)),
518
                ("conflicted", json::b(conflicted)),
519
                ("others", json::arr(r.others.iter().map(|o| json::s(o))))
520
            ])
521
        );
522
        return Ok(0);
523
    }
524
    if !r.changed {
525
        sp.done(&format!(
526
            "{} {}{}",
527
            ui::ok(ui::glyph("✔", "*")),
528
            ui::dim(format!(
529
                "{} is up to date with {remote}.",
530
                repo.config.bookmark
531
            )),
532
            if r.checked_out {
533
                ui::dim(" The working copy had fallen behind it and is updated.")
534
            } else {
535
                String::new()
536
            }
537
        ));
538
        others_pulled(&r.others);
539
        others_behind(&repo, &remote);
540
        if r.checked_out {
541
            super::workspace::where_now(&repo);
542
        }
543
        return Ok(0);
544
    }
545
    sp.done(&format!(
546
        "{} {} now has {}{}",
547
        ui::done("Pulled:"),
548
        ui::bookmark(&repo.config.bookmark),
549
        plural(r.heads.len(), "head"),
550
        ui::dim(if r.checked_out {
551
            "; working copy updated"
552
        } else {
553
            "; run oxy checkout to update the working copy"
554
        })
555
    ));
556
    let snap = repo.snapshot("oxy pull")?;
557
    if snap.base_snapshot.is_conflicted() {
558
        println!(
559
            "  {} {}",
560
            ui::caution(),
561
            ui::warn("the result has conflicts; see oxy status")
562
        );
563
    }
564
    others_pulled(&r.others);
565
    others_behind(&repo, &remote);
566
    subrepos_behind(&repo);
567
    super::workspace::where_now(&repo);
568
    Ok(0)
569
}
570
571
/// The other bookmarks a pull moved.
572
fn others_pulled(others: &[String]) {
573
    if others.is_empty() {
574
        return;
575
    }
576
    let shown: Vec<String> = others.iter().take(8).map(ui::bookmark).collect();
577
    let more = others.len().saturating_sub(8);
578
    println!(
579
        "  {} {}{}",
580
        ui::done("Also updated"),
581
        shown.join(", "),
582
        if more > 0 {
583
            ui::dim(format!(" and {more} more"))
584
        } else {
585
            String::new()
586
        }
587
    );
588
}
589
590
/// `oxy push [REMOTE] --delete NAME`.
591
pub fn push_delete(remote: Option<&str>, name: &str, as_json: bool) -> Result<i32> {
592
    let repo = open()?;
593
    let remote = remote_name(&repo, remote);
594
    let sp = ui::spinner(&format!("Deleting {remote}/{name}…"));
595
    let results = repo.push_delete(&remote, name)?;
596
    sp.clear();
597
    if as_json {
598
        println!(
599
            "{}",
600
            json::arr(results.iter().map(|r| {
601
                json::obj([
602
                    ("name", json::s(&r.name)),
603
                    ("ok", json::b(r.ok)),
604
                    ("reason", json::s(&r.reason)),
605
                    ("state", json::s("")),
606
                ])
607
            }))
608
        );
609
        return Ok(if results.iter().all(|r| r.ok) { 0 } else { 1 });
610
    }
611
    let mut code = 0;
612
    for r in results {
613
        if r.ok {
614
            println!(
615
                "{} {}",
616
                ui::done("Deleted"),
617
                ui::id(format!("{remote}/{}", r.name))
618
            );
619
        } else {
620
            println!(
621
                "{} {} {}{}{}",
622
                ui::err(ui::glyph("✖", "x")),
623
                ui::err("Rejected"),
624
                ui::id(format!("{remote}/{}", r.name)),
625
                ui::sep(),
626
                r.reason
627
            );
628
            code = 1;
629
        }
630
    }
631
    Ok(code)
632
}
633
634
pub fn push(
635
    remote: Option<&str>,
636
    force: bool,
637
    bookmark: Option<&str>,
638
    as_json: bool,
639
) -> Result<i32> {
640
    let repo = open()?;
641
    let remote = remote_name(&repo, remote);
642
    let sp = ui::spinner(&format!("Pushing to {remote}…"));
643
    let bookmark_name = bookmark.map_or_else(|| repo.config.bookmark.clone(), String::from);
644
    // A long push goes in parts: the spinner says which.
645
    let results = repo.push_bookmark_with(&remote, &bookmark_name, force, &mut |m| {
646
        sp.set(&format!("Pushing to {remote}… {m}"))
647
    })?;
648
    sp.clear();
649
    if as_json {
650
        // The state each accepted bookmark now holds on the remote (its local
651
        // state object), so a caller can look up what the push started, such
652
        // as the checks a forge runs on it.
653
        let view = repo.view()?;
654
        println!(
655
            "{}",
656
            json::arr(results.iter().map(|r| {
657
                let state = view
658
                    .bookmarks
659
                    .get(&r.name)
660
                    .filter(|_| r.ok)
661
                    .map(|st| st.to_hex())
662
                    .unwrap_or_default();
663
                json::obj([
664
                    ("name", json::s(&r.name)),
665
                    ("ok", json::b(r.ok)),
666
                    ("reason", json::s(&r.reason)),
667
                    ("state", json::s(&state)),
668
                ])
669
            }))
670
        );
671
        return Ok(if results.iter().all(|r| r.ok) { 0 } else { 1 });
672
    }
673
    let mut code = 0;
674
    for r in results {
675
        if r.ok {
676
            println!(
677
                "{} {}{}{}",
678
                ui::done("Pushed"),
679
                ui::id(format!("{remote}/{}", r.name)),
680
                ui::sep(),
681
                ui::dim(if r.reason.is_empty() {
682
                    "updated"
683
                } else {
684
                    r.reason.as_str()
685
                })
686
            );
687
        } else {
688
            println!(
689
                "{} {} {}{}{}",
690
                ui::err(ui::glyph("✖", "x")),
691
                ui::err("Rejected"),
692
                ui::id(format!("{remote}/{}", r.name)),
693
                ui::sep(),
694
                r.reason
695
            );
696
            code = 1;
697
        }
698
    }
699
    Ok(code)
700
}
701
702
pub fn serve(
703
    root: PathBuf,
704
    bind: &str,
705
    tokens: Vec<String>,
706
    tls: Option<(PathBuf, PathBuf)>,
707
) -> Result<i32> {
708
    let listener = std::net::TcpListener::bind(bind).with_context(|| format!("binding {bind}"))?;
709
    let root = root.canonicalize()?;
710
    let tls = tls.map(|(cert, key)| oxy_server::TlsFiles { cert, key });
711
    println!(
712
        "Serving repositories under {} on {}://{bind}/<repo>/oxy/v1/ ({})",
713
        root.display(),
714
        if tls.is_some() { "https" } else { "http" },
715
        if tokens.is_empty() {
716
            "open: no push tokens configured"
717
        } else {
718
            "push requires a token"
719
        }
720
    );
721
    if tls.is_none()
722
        && !bind.starts_with("127.")
723
        && !bind.starts_with("localhost")
724
        && !bind.starts_with("[::1]")
725
    {
726
        eprintln!("warning: serving plain HTTP on a non-loopback address; put a TLS terminator in front or pass --tls-cert/--tls-key");
727
    }
728
    oxy_server::run_blocking(listener, oxy_server::ServerConfig { root, tokens, tls })?;
729
    Ok(0)
730
}
731
732
pub fn git_export(git_dir: &std::path::Path, branch: Option<&str>) -> Result<i32> {
733
    let repo = open()?;
734
    let sp = ui::spinner("Exporting to Git…");
735
    let r = match branch {
736
        Some(b) => repo.git_export_as(git_dir, b)?,
737
        None => repo.git_export(git_dir)?,
738
    };
739
    sp.clear();
740
    println!(
741
        "{} {} to {} as branch {} {}",
742
        ui::done("Exported"),
743
        plural(r.exported, "new state"),
744
        ui::path(git_dir.display()),
745
        ui::bookmark(&r.branch),
746
        ui::dim(format!(
747
            "(currently {}; {} already exported)",
748
            plural(r.heads, "head"),
749
            r.skipped
750
        ))
751
    );
752
    Ok(0)
753
}
754
755
pub fn git_recover() -> Result<i32> {
756
    let repo = open()?;
757
    let sp = ui::spinner("Reading the store…");
758
    let (changes, heads) = repo.recover_git_import(&|m| sp.set(m))?;
759
    sp.done(&format!(
760
        "{} {} from imported Git commits: {} now has {}",
761
        ui::done("Recovered"),
762
        plural(changes, "change"),
763
        ui::bookmark(&repo.config.bookmark),
764
        plural(heads, "head")
765
    ));
766
    println!(
767
        "  {} {}",
768
        ui::note(),
769
        ui::dim("carry on with oxy git fetch GIT_DIR --branch BRANCH")
770
    );
771
    Ok(0)
772
}
773
774
/// `--claim` (oxygen#97): record `git.claim`, so this import and every
775
/// later fetch author the identity's own commits with its key.
776
fn claim_commits(repo: &mut Repo) -> Result<()> {
777
    repo.config.set("git.claim", "true")?;
778
    repo.save_config()?;
779
    Ok(())
780
}
781
782
pub fn git_fetch(url: &str, branch: &str, claim: bool) -> Result<i32> {
783
    let mut repo = open()?;
784
    if claim {
785
        claim_commits(&mut repo)?;
786
    }
787
    let sp = ui::spinner(&format!("Fetching {url} {branch}…"));
788
    let r = repo.git_fetch(url, branch)?;
789
    sp.clear();
790
    if r.commits == 0 {
791
        println!(
792
            "{} {}",
793
            ui::done("Fetched"),
794
            ui::dim(format!("nothing new from {url} {branch}"))
795
        );
796
    } else {
797
        println!(
798
            "{} {} ({} merges) from {} {}{}{} now has {}",
799
            ui::done("Fetched"),
800
            plural(r.commits, "new commit"),
801
            r.merges,
802
            ui::path(url),
803
            ui::bookmark(branch),
804
            ui::sep(),
805
            ui::bookmark(&repo.config.bookmark),
806
            plural(r.heads, "head")
807
        );
808
        if !repo.snapshot("oxy git fetch")?.changed {
809
            println!("  {} {}", ui::note(), ui::dim("working copy updated"));
810
        } else {
811
            println!(
812
                "  {} {}",
813
                ui::note(),
814
                ui::dim("run oxy checkout to update the working copy")
815
            );
816
        }
817
    }
818
    if r.submodules > 0 {
819
        println!(
820
            "  {} {}",
821
            ui::note(),
822
            ui::dim(format!(
823
                "{} submodule {} imported as subrepos with Git pins",
824
                r.submodules,
825
                if r.submodules == 1 {
826
                    "entry"
827
                } else {
828
                    "entries"
829
                }
830
            ))
831
        );
832
    }
833
    Ok(0)
834
}
835
836
pub fn git_push(url: &str, branch: &str) -> Result<i32> {
837
    let repo = open()?;
838
    let sp = ui::spinner(&format!("Pushing to {url} {branch}…"));
839
    let r = repo.git_push(url, branch)?;
840
    sp.clear();
841
    println!(
842
        "{} {} to {} {} {}",
843
        ui::done("Pushed"),
844
        plural(r.exported, "new commit"),
845
        ui::path(url),
846
        ui::bookmark(&r.branch),
847
        ui::dim(format!("({} already there)", r.skipped))
848
    );
849
    Ok(0)
850
}
851
852
/// `oxy git verify`: exit 1 if any commit's tree is not reproduced.
853
pub fn git_verify(
854
    git_dir: &std::path::Path,
855
    branch: &str,
856
    last: Option<usize>,
857
    max: usize,
858
) -> Result<i32> {
859
    let repo = open()?;
860
    let started = std::time::Instant::now();
861
    let sp = ui::spinner(&format!(
862
        "Rebuilding every commit of {} {branch}…",
863
        git_dir.display()
864
    ));
865
    let r = repo.verify_git_import_last(git_dir, branch, last, max)?;
866
    sp.clear();
867
    for (_, what) in &r.mismatches {
868
        println!("{} {what}", ui::err(ui::glyph("✖", "x")));
869
    }
870
    if r.not_yet > 0 {
871
        println!(
872
            "  {} {}",
873
            ui::note(),
874
            ui::dim(format!(
875
                "{} not imported yet, after the last imported commit: not checked",
876
                plural(r.not_yet, "commit")
877
            ))
878
        );
879
    }
880
    if r.mismatches.is_empty() {
881
        println!(
882
            "{}",
883
            ui::done(if r.skipped > 0 {
884
                format!(
885
                    "The last {} commits reproduced ({} followed), {} files compared, in {:.1}s",
886
                    r.commits - r.skipped,
887
                    r.skipped,
888
                    r.files_compared,
889
                    started.elapsed().as_secs_f64()
890
                )
891
            } else {
892
                format!(
893
                    "Every commit reproduced: {} commits, {} files compared, in {:.1}s",
894
                    r.commits,
895
                    r.files_compared,
896
                    started.elapsed().as_secs_f64()
897
                )
898
            })
899
        );
900
        Ok(0)
901
    } else {
902
        // What differs, by kind, the commit taken off: one difference
903
        // carried through history reads as one line.
904
        let mut kinds: std::collections::BTreeMap<String, usize> = Default::default();
905
        for (_, what) in &r.mismatches {
906
            let kind = what.split_once(": ").map_or(what.as_str(), |(_, k)| k);
907
            *kinds.entry(kind.to_string()).or_default() += 1;
908
        }
909
        let mut kinds: Vec<_> = kinds.into_iter().collect();
910
        kinds.sort_by_key(|k| std::cmp::Reverse(k.1));
911
        for (kind, n) in kinds.iter().take(10) {
912
            println!("  {} {}", ui::dim(format!("{n:>6} ×")), kind);
913
        }
914
        println!(
915
            "{} differences in {} commits checked{}",
916
            r.mismatches.len(),
917
            r.commits,
918
            if max > 0 && r.mismatches.len() >= max {
919
                format!(" (stopped at {max}; --max-differences 0 checks every commit)")
920
            } else {
921
                String::new()
922
            }
923
        );
924
        Ok(1)
925
    }
926
}
927
928
pub fn git_import(
929
    git_dir: &std::path::Path,
930
    dest: &std::path::Path,
931
    branch: &str,
932
    claim: bool,
933
) -> Result<i32> {
934
    let mut repo = Repo::init(dest)?;
935
    if claim {
936
        claim_commits(&mut repo)?;
937
    }
938
    let started = std::time::Instant::now();
939
    let sp = ui::spinner(&format!("Importing {} {branch}…", git_dir.display()));
940
    let r = repo.import_git_with(git_dir, branch, &mut |where_| sp.set(where_))?;
941
    sp.clear();
942
    println!(
943
        "{} {} ({} merges) from {} {} into {} {}",
944
        ui::done("Imported"),
945
        plural(r.commits, "commit"),
946
        r.merges,
947
        ui::path(git_dir.display()),
948
        ui::bookmark(branch),
949
        ui::path(repo.root().display()),
950
        ui::dim(format!(
951
            "in {:.1?}; {} now has {}",
952
            started.elapsed(),
953
            repo.config.bookmark,
954
            plural(r.heads, "head")
955
        ))
956
    );
957
    if r.submodules > 0 {
958
        println!(
959
            "  {} {}",
960
            ui::note(),
961
            ui::dim(format!(
962
                "{} submodule {} imported as subrepos with Git pins",
963
                r.submodules,
964
                if r.submodules == 1 {
965
                    "entry"
966
                } else {
967
                    "entries"
968
                }
969
            ))
970
        );
971
    }
972
    Ok(0)
973
}
974
975
pub fn submodule_add(url: &str, path: &str, bookmark: Option<&str>) -> Result<i32> {
976
    let repo = open()?;
977
    let sp = ui::spinner(&format!("Cloning {url} into {path}…"));
978
    let pin = repo.submodule_add(url, path, bookmark)?;
979
    sp.done(&format!(
980
        "{} subrepo {} {} {}",
981
        ui::done("Added"),
982
        ui::path(path),
983
        ui::dim(ui::glyph("→", "->")),
984
        ui::dim(pin.summary())
985
    ));
986
    println!(
987
        "  {} {}",
988
        ui::note(),
989
        ui::dim("recorded in .oxymodules; commit to pin it")
990
    );
991
    Ok(0)
992
}
993
994
pub fn submodule_update(init: bool, paths: &[String]) -> Result<i32> {
995
    let repo = open()?;
996
    let sp = ui::spinner("Updating subrepos…");
997
    let results = repo.submodule_update(init, paths)?;
998
    let unpinned: Vec<_> = repo
999
        .unpinned_modules()?
1000
        .into_iter()
1001
        .filter(|(p, _)| paths.is_empty() || paths.iter().any(|q| q.trim_end_matches('/') == p))
1002
        .collect();
1003
    sp.clear();
1004
    if results.is_empty() && unpinned.is_empty() {
1005
        println!("{}", ui::dim("No subrepos."));
1006
    }
1007
    let code = print_subrepo_results(results);
1008
    print_unpinned(&unpinned);
1009
    Ok(if unpinned.is_empty() { code } else { 1 })
1010
}
1011
1012
/// `.oxymodules` entries never added: nothing to clone, so say how to add
1013
/// them (oxygen#72).
1014
fn print_unpinned(unpinned: &[(String, oxy_core::subrepo::Module)]) {
1015
    for (path, m) in unpinned {
1016
        let url = if m.url.is_empty() { "<url>" } else { &m.url };
1017
        println!(
1018
            "{} {}",
1019
            ui::warn(format!(
1020
                "{} in .oxymodules but never added, so no pin",
1021
                ui::glyph("⚠", "!")
1022
            )),
1023
            ui::path(path)
1024
        );
1025
        println!(
1026
            "  {}",
1027
            ui::dim(format!("add it with: oxy submodule add {url} {path}"))
1028
        );
1029
    }
1030
}
1031
1032
fn print_subrepo_results(results: Vec<(String, oxy_core::repo::SubrepoSync)>) -> i32 {
1033
    let mut code = 0;
1034
    for (path, r) in results {
1035
        use oxy_core::repo::SubrepoSync::*;
1036
        let line = match r {
1037
            Updated => ui::done("Updated"),
1038
            UpToDate => ui::ok(format!("{} up to date", ui::glyph("✔", "*"))),
1039
            Missing => {
1040
                code = 1;
1041
                ui::warn(format!(
1042
                    "{} missing (pass --init to clone)",
1043
                    ui::glyph("⚠", "!")
1044
                ))
1045
            }
1046
            Dirty => {
1047
                code = 1;
1048
                ui::warn(format!(
1049
                    "{} has uncommitted changes; left as is",
1050
                    ui::glyph("⚠", "!")
1051
                ))
1052
            }
1053
            KeptBookmark { bookmark, newer } => ui::warn(format!(
1054
                "{} checked out at the pin; its bookmark {bookmark} keeps {} the pin lacks",
1055
                ui::glyph("⚠", "!"),
1056
                plural(newer, "newer change")
1057
            )),
1058
            Failed(e) => {
1059
                code = 1;
1060
                ui::err(format!("{} {e}", ui::glyph("✖", "x")))
1061
            }
1062
        };
1063
        println!("{line} {}", ui::path(path));
1064
    }
1065
    code
1066
}
1067
1068
fn pin_json(p: &oxy_core::subrepo::Pin) -> String {
1069
    match p {
1070
        oxy_core::subrepo::Pin::Oxy {
1071
            repo,
1072
            heads,
1073
            bookmark,
1074
        } => json::obj([
1075
            ("kind", json::s("oxy")),
1076
            (
1077
                "repo",
1078
                json::s(&repo.iter().map(|b| format!("{b:02x}")).collect::<String>()),
1079
            ),
1080
            ("heads", json::hashes(heads)),
1081
            ("bookmark", json::s(bookmark)),
1082
        ]),
1083
        oxy_core::subrepo::Pin::Git { sha, branch } => json::obj([
1084
            ("kind", json::s("git")),
1085
            ("sha", json::s(sha)),
1086
            ("branch", json::s(branch)),
1087
        ]),
1088
    }
1089
}
1090
1091
pub fn submodule_status(as_json: bool) -> Result<i32> {
1092
    let repo = open()?;
1093
    let subs = repo.subrepos()?;
1094
    let unpinned = repo.unpinned_modules()?;
1095
    if as_json {
1096
        let pinned = subs.iter().map(|s| {
1097
            json::obj([
1098
                ("path", json::s(&s.path)),
1099
                ("pin", pin_json(&s.pin)),
1100
                ("actual", json::opt(s.actual.as_ref(), pin_json)),
1101
                ("at_pin", json::b(s.actual.as_ref() == Some(&s.pin))),
1102
                ("dirty", json::b(s.dirty)),
1103
                ("committed", json::b(s.committed)),
1104
                ("url", json::opt(s.url.as_deref(), json::s)),
1105
            ])
1106
        });
1107
        // Listed in .oxymodules but never added: no pin at all.
1108
        let unpinned_json = unpinned.iter().map(|(path, m)| {
1109
            json::obj([
1110
                ("path", json::s(path)),
1111
                ("pin", "null".to_string()),
1112
                ("actual", "null".to_string()),
1113
                ("at_pin", json::b(false)),
1114
                ("dirty", json::b(false)),
1115
                ("committed", json::b(false)),
1116
                ("url", json::s(&m.url)),
1117
            ])
1118
        });
1119
        println!("{}", json::arr(pinned.chain(unpinned_json)));
1120
        return Ok(0);
1121
    }
1122
    if subs.is_empty() && unpinned.is_empty() {
1123
        println!("{}", ui::dim("No subrepos."));
1124
    }
1125
    for s in subs {
1126
        let state = match (&s.actual, s.dirty) {
1127
            _ if !s.committed => {
1128
                ui::warn(format!("{} added, not committed yet", ui::glyph("+", "+")))
1129
            }
1130
            (None, _) => ui::warn(format!("{} missing", ui::glyph("⚠", "!"))),
1131
            (Some(a), dirty) if *a == s.pin => {
1132
                if dirty {
1133
                    ui::warn(format!(
1134
                        "{} at pin, uncommitted changes",
1135
                        ui::glyph("✎", "~")
1136
                    ))
1137
                } else {
1138
                    ui::ok(format!("{} at pin", ui::glyph("✔", "*")))
1139
                }
1140
            }
1141
            (Some(a), _) => ui::warn(format!("{} at {}", ui::glyph("↕", "<>"), a.summary())),
1142
        };
1143
        println!(
1144
            "{} {}{}{}{}{state}",
1145
            ui::ok(ui::glyph("⧉", "#")),
1146
            ui::path(&s.path),
1147
            ui::sep(),
1148
            ui::dim(s.pin.summary()),
1149
            ui::sep()
1150
        );
1151
        if let Some(u) = s.url {
1152
            println!("    {} {}", ui::dim(ui::glyph("↳", "->")), ui::dim(u));
1153
        }
1154
    }
1155
    print_unpinned(&unpinned);
1156
    Ok(0)
1157
}
1158
1159
pub fn submodule_remove(path: &str) -> Result<i32> {
1160
    let repo = open()?;
1161
    repo.submodule_remove(path)?;
1162
    println!(
1163
        "{} subrepo {} {}",
1164
        ui::done("Removed"),
1165
        ui::path(path),
1166
        ui::dim("(directory left in place; commit to record the removal)")
1167
    );
1168
    Ok(0)
1169
}
1170
1171
pub fn deepen(remote: &str, depth: u32) -> Result<i32> {
1172
    let repo = open()?;
1173
    if !repo.is_shallow() {
1174
        println!(
1175
            "{}",
1176
            ui::dim("This repository is not shallow; nothing to deepen.")
1177
        );
1178
        return Ok(0);
1179
    }
1180
    let sp = ui::spinner(&format!("Fetching {depth} more levels from {remote}…"));
1181
    let n = repo.deepen(remote, depth)?;
1182
    sp.done(&format!(
1183
        "{} {}; {}",
1184
        ui::done("Deepened by"),
1185
        plural(n, "change"),
1186
        if repo.is_shallow() {
1187
            "still shallow".to_string()
1188
        } else {
1189
            ui::ok("history is now complete")
1190
        }
1191
    ));
1192
    Ok(0)
1193
}