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