OXYGENHUB
# 827281eed2ed oxygen / src / cli / sync.rs
26.3 KiB · Rust · last changed Clones and remote add store a local path absolute 1 month 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
pub fn remote_add(name: &str, url: &str) -> Result<i32> {
99
    let mut repo = open()?;
100
    repo.config.set(
101
        &format!("remote.{name}.url"),
102
        &oxy_core::protocol::stored_url(url),
103
    )?;
104
    repo.save_config()?;
105
    println!(
106
        "{} remote {} {} {url}",
107
        ui::done("Added"),
108
        ui::bookmark(name),
109
        ui::dim(ui::glyph("→", "->"))
110
    );
111
    Ok(0)
112
}
113
114
pub fn remote_remove(name: &str) -> Result<i32> {
115
    let mut repo = open()?;
116
    repo.config.set(&format!("remote.{name}.url"), "")?;
117
    repo.save_config()?;
118
    println!("{} remote {}", ui::done("Removed"), ui::bookmark(name));
119
    Ok(0)
120
}
121
122
pub fn remote_list(as_json: bool) -> Result<i32> {
123
    let repo = open()?;
124
    let view = repo.view()?;
125
    if as_json {
126
        let items = repo.config.remotes.iter().map(|(name, url)| {
127
            let bms = view.remotes.get(name).map(|b| {
128
                json::arr(b.iter().map(|(bm, st)| {
129
                    let heads = repo
130
                        .store()
131
                        .get_state(st)
132
                        .map(|s| s.heads)
133
                        .unwrap_or_default();
134
                    json::obj([("name", json::s(bm)), ("heads", json::hashes(&heads))])
135
                }))
136
            });
137
            json::obj([
138
                ("name", json::s(name)),
139
                ("url", json::s(url)),
140
                // The CA file `remote.NAME.ca` names, for tools that talk to
141
                // the same hub (an editor's forge view, `oh`).
142
                (
143
                    "ca",
144
                    json::opt(repo.config.remote_cas.get(name), |c| json::s(c)),
145
                ),
146
                ("bookmarks", bms.unwrap_or_else(|| "[]".into())),
147
            ])
148
        });
149
        println!("{}", json::arr(items));
150
        return Ok(0);
151
    }
152
    if repo.config.remotes.is_empty() {
153
        println!(
154
            "{}",
155
            ui::dim("No remotes; add one with oxy remote add <name> <url>.")
156
        );
157
    }
158
    for (name, url) in &repo.config.remotes {
159
        println!(
160
            "{} {}{}{}",
161
            ui::ok(ui::glyph("⇄", "<>")),
162
            ui::bookmark(name),
163
            ui::sep(),
164
            ui::dim(url)
165
        );
166
        if let Some(bms) = view.remotes.get(name) {
167
            for (bm, st) in bms {
168
                let heads = repo
169
                    .store()
170
                    .get_state(st)
171
                    .map(|s| s.heads.len())
172
                    .unwrap_or(0);
173
                println!(
174
                    "    {} {}{}{}",
175
                    ui::dim(ui::glyph("↳", "->")),
176
                    ui::id(format!("{name}/{bm}")),
177
                    ui::sep(),
178
                    ui::dim(plural(heads, "head"))
179
                );
180
            }
181
        }
182
    }
183
    Ok(0)
184
}
185
186
/// The remote named, else `origin`, else the only remote there is.
187
fn remote_name(repo: &oxy_core::repo::Repo, remote: Option<&str>) -> String {
188
    remote.map_or_else(|| repo.default_remote(), str::to_string)
189
}
190
191
pub fn fetch(remote: Option<&str>, as_json: bool) -> Result<i32> {
192
    let repo = open()?;
193
    let remote = remote_name(&repo, remote);
194
    let sp = ui::spinner(&format!("Fetching from {remote}…"));
195
    let report = repo.fetch(&remote)?;
196
    sp.clear();
197
    if as_json {
198
        println!(
199
            "{}",
200
            json::obj([
201
                ("remote", json::s(&remote)),
202
                (
203
                    "refs",
204
                    json::arr(report.refs.iter().map(|(name, heads, n)| {
205
                        let t = repo.tracking(&remote, name).ok().flatten();
206
                        json::obj([
207
                            ("name", json::s(name)),
208
                            ("heads", json::hashes(heads)),
209
                            ("new", json::n(*n)),
210
                            (
211
                                "ahead",
212
                                t.map_or_else(|| "null".into(), |(a, _)| json::n(a)),
213
                            ),
214
                            (
215
                                "behind",
216
                                t.map_or_else(|| "null".into(), |(_, b)| json::n(b)),
217
                            ),
218
                        ])
219
                    }))
220
                ),
221
                ("new_tags", json::n(report.new_tags)),
222
                ("unverified", json::b(report.unverified)),
223
            ])
224
        );
225
        return Ok(0);
226
    }
227
    if report.refs.is_empty() {
228
        println!(
229
            "{} {}",
230
            ui::done("Fetched"),
231
            ui::dim(format!("nothing new from {remote}"))
232
        );
233
    }
234
    for (name, heads, n) in &report.refs {
235
        // What was fetched, then how the local bookmark stands against it:
236
        // "up to date" only when the two are the same (oxygen#56).
237
        let fetched =
238
            (*n > 0).then(|| format!("{}{}", ui::ok(plural(*n, "new change")), ui::sep()));
239
        let them = |k: usize| if k == 1 { "it" } else { "them" };
240
        let standing = match repo.tracking(&remote, name).ok().flatten() {
241
            None => ui::dim(format!("no local bookmark {name}")),
242
            Some((0, 0)) => ui::dim(format!("{name} up to date")),
243
            Some((0, b)) if *name == repo.config.bookmark => ui::warn(format!(
244
                "{name} is {} behind: oxy pull to take {}",
245
                plural(b, "change"),
246
                them(b)
247
            )),
248
            Some((0, b)) => ui::warn(format!(
249
                "{name} is {} behind: oxy bookmark switch {name} then oxy pull to take {}",
250
                plural(b, "change"),
251
                them(b)
252
            )),
253
            Some((a, 0)) => ui::dim(format!(
254
                "{name} is {} ahead: oxy push to send {}",
255
                plural(a, "change"),
256
                them(a)
257
            )),
258
            Some((a, b)) => ui::warn(format!(
259
                "{name} and {remote}/{name} have diverged ({a} here, {b} there): oxy pull to merge them"
260
            )),
261
        };
262
        let what = format!("{}{standing}", fetched.unwrap_or_default());
263
        println!(
264
            "{} {}{}{}{}{what}",
265
            ui::done("Fetched"),
266
            ui::id(format!("{remote}/{name}")),
267
            ui::sep(),
268
            ui::dim(plural(heads.len(), "head")),
269
            ui::sep()
270
        );
271
    }
272
    if report.new_tags > 0 {
273
        println!(
274
            "  {} {}",
275
            ui::note(),
276
            ui::dim(format!("{} adopted", plural(report.new_tags, "tag")))
277
        );
278
    }
279
    if report.unverified {
280
        eprintln!(
281
            "{} {remote} has no trust policy; nothing fetched from it was verified",
282
            ui::caution()
283
        );
284
    }
285
    Ok(0)
286
}
287
288
/// Pull acts on the current bookmark only: name the others the fetch
289
/// found behind their remote, which is easy to take for the current one
290
/// (oxygen#29).
291
fn others_behind(repo: &oxy_core::repo::Repo, remote: &str) {
292
    let Ok(bookmarks) = repo.bookmarks() else {
293
        return;
294
    };
295
    for b in bookmarks {
296
        let Some(n) = b.behind.filter(|n| *n > 0) else {
297
            continue;
298
        };
299
        if b.current {
300
            continue;
301
        }
302
        println!(
303
            "  {} {}",
304
            ui::note(),
305
            ui::dim(format!(
306
                "{} is {} behind {remote}/{}: oxy bookmark switch {} then oxy pull to take {}",
307
                b.name,
308
                plural(n, "change"),
309
                b.name,
310
                b.name,
311
                if n == 1 { "it" } else { "them" }
312
            ))
313
        );
314
    }
315
}
316
317
pub fn pull(remote: Option<&str>, as_json: bool) -> Result<i32> {
318
    let repo = open()?;
319
    let remote = remote_name(&repo, remote);
320
    let sp = ui::spinner(&format!("Pulling from {remote}…"));
321
    let r = repo.pull(&remote)?;
322
    if as_json {
323
        sp.clear();
324
        let conflicted = repo
325
            .snapshot_status("oxy pull")?
326
            .base_snapshot
327
            .is_conflicted();
328
        println!(
329
            "{}",
330
            json::obj([
331
                ("remote", json::s(&remote)),
332
                ("bookmark", json::s(&repo.config.bookmark)),
333
                ("heads", json::hashes(&r.heads)),
334
                ("changed", json::b(r.changed)),
335
                ("checked_out", json::b(r.checked_out)),
336
                ("conflicted", json::b(conflicted)),
337
                ("others", json::arr(r.others.iter().map(|o| json::s(o))))
338
            ])
339
        );
340
        return Ok(0);
341
    }
342
    if !r.changed {
343
        sp.done(&format!(
344
            "{} {}",
345
            ui::ok(ui::glyph("✔", "*")),
346
            ui::dim(format!(
347
                "{} is up to date with {remote}.",
348
                repo.config.bookmark
349
            ))
350
        ));
351
        others_pulled(&r.others);
352
        others_behind(&repo, &remote);
353
        return Ok(0);
354
    }
355
    sp.done(&format!(
356
        "{} {} now has {}{}",
357
        ui::done("Pulled:"),
358
        ui::bookmark(&repo.config.bookmark),
359
        plural(r.heads.len(), "head"),
360
        ui::dim(if r.checked_out {
361
            "; working copy updated"
362
        } else {
363
            "; run oxy checkout to update the working copy"
364
        })
365
    ));
366
    let snap = repo.snapshot("oxy pull")?;
367
    if snap.base_snapshot.is_conflicted() {
368
        println!(
369
            "  {} {}",
370
            ui::caution(),
371
            ui::warn("the result has conflicts; see oxy status")
372
        );
373
    }
374
    others_pulled(&r.others);
375
    others_behind(&repo, &remote);
376
    subrepos_behind(&repo);
377
    super::workspace::where_now(&repo);
378
    Ok(0)
379
}
380
381
/// The other bookmarks a pull moved.
382
fn others_pulled(others: &[String]) {
383
    if others.is_empty() {
384
        return;
385
    }
386
    let shown: Vec<String> = others.iter().take(8).map(ui::bookmark).collect();
387
    let more = others.len().saturating_sub(8);
388
    println!(
389
        "  {} {}{}",
390
        ui::done("Also updated"),
391
        shown.join(", "),
392
        if more > 0 {
393
            ui::dim(format!(" and {more} more"))
394
        } else {
395
            String::new()
396
        }
397
    );
398
}
399
400
/// `oxy push [REMOTE] --delete NAME`.
401
pub fn push_delete(remote: Option<&str>, name: &str, as_json: bool) -> Result<i32> {
402
    let repo = open()?;
403
    let remote = remote_name(&repo, remote);
404
    let sp = ui::spinner(&format!("Deleting {remote}/{name}…"));
405
    let results = repo.push_delete(&remote, name)?;
406
    sp.clear();
407
    if as_json {
408
        println!(
409
            "{}",
410
            json::arr(results.iter().map(|r| {
411
                json::obj([
412
                    ("name", json::s(&r.name)),
413
                    ("ok", json::b(r.ok)),
414
                    ("reason", json::s(&r.reason)),
415
                    ("state", json::s("")),
416
                ])
417
            }))
418
        );
419
        return Ok(if results.iter().all(|r| r.ok) { 0 } else { 1 });
420
    }
421
    let mut code = 0;
422
    for r in results {
423
        if r.ok {
424
            println!(
425
                "{} {}",
426
                ui::done("Deleted"),
427
                ui::id(format!("{remote}/{}", r.name))
428
            );
429
        } else {
430
            println!(
431
                "{} {} {}{}{}",
432
                ui::err(ui::glyph("✖", "x")),
433
                ui::err("Rejected"),
434
                ui::id(format!("{remote}/{}", r.name)),
435
                ui::sep(),
436
                r.reason
437
            );
438
            code = 1;
439
        }
440
    }
441
    Ok(code)
442
}
443
444
pub fn push(
445
    remote: Option<&str>,
446
    force: bool,
447
    bookmark: Option<&str>,
448
    as_json: bool,
449
) -> Result<i32> {
450
    let repo = open()?;
451
    let remote = remote_name(&repo, remote);
452
    let sp = ui::spinner(&format!("Pushing to {remote}…"));
453
    let results = match bookmark {
454
        Some(b) => repo.push_bookmark(&remote, b, force)?,
455
        None => repo.push(&remote, force)?,
456
    };
457
    sp.clear();
458
    if as_json {
459
        println!(
460
            "{}",
461
            json::arr(results.iter().map(|r| json::obj([
462
                ("name", json::s(&r.name)),
463
                ("ok", json::b(r.ok)),
464
                ("reason", json::s(&r.reason))
465
            ])))
466
        );
467
        return Ok(if results.iter().all(|r| r.ok) { 0 } else { 1 });
468
    }
469
    let mut code = 0;
470
    for r in results {
471
        if r.ok {
472
            println!(
473
                "{} {}{}{}",
474
                ui::done("Pushed"),
475
                ui::id(format!("{remote}/{}", r.name)),
476
                ui::sep(),
477
                ui::dim(if r.reason.is_empty() {
478
                    "updated"
479
                } else {
480
                    r.reason.as_str()
481
                })
482
            );
483
        } else {
484
            println!(
485
                "{} {} {}{}{}",
486
                ui::err(ui::glyph("✖", "x")),
487
                ui::err("Rejected"),
488
                ui::id(format!("{remote}/{}", r.name)),
489
                ui::sep(),
490
                r.reason
491
            );
492
            code = 1;
493
        }
494
    }
495
    Ok(code)
496
}
497
498
pub fn serve(
499
    root: PathBuf,
500
    bind: &str,
501
    tokens: Vec<String>,
502
    tls: Option<(PathBuf, PathBuf)>,
503
) -> Result<i32> {
504
    let listener = std::net::TcpListener::bind(bind).with_context(|| format!("binding {bind}"))?;
505
    let root = root.canonicalize()?;
506
    let tls = tls.map(|(cert, key)| oxy_server::TlsFiles { cert, key });
507
    println!(
508
        "Serving repositories under {} on {}://{bind}/<repo>/oxy/v1/ ({})",
509
        root.display(),
510
        if tls.is_some() { "https" } else { "http" },
511
        if tokens.is_empty() {
512
            "open: no push tokens configured"
513
        } else {
514
            "push requires a token"
515
        }
516
    );
517
    if tls.is_none()
518
        && !bind.starts_with("127.")
519
        && !bind.starts_with("localhost")
520
        && !bind.starts_with("[::1]")
521
    {
522
        eprintln!("warning: serving plain HTTP on a non-loopback address; put a TLS terminator in front or pass --tls-cert/--tls-key");
523
    }
524
    oxy_server::run_blocking(listener, oxy_server::ServerConfig { root, tokens, tls })?;
525
    Ok(0)
526
}
527
528
pub fn git_export(git_dir: &std::path::Path, branch: Option<&str>) -> Result<i32> {
529
    let repo = open()?;
530
    let sp = ui::spinner("Exporting to Git…");
531
    let r = match branch {
532
        Some(b) => repo.git_export_as(git_dir, b)?,
533
        None => repo.git_export(git_dir)?,
534
    };
535
    sp.clear();
536
    println!(
537
        "{} {} to {} as branch {} {}",
538
        ui::done("Exported"),
539
        plural(r.exported, "new state"),
540
        ui::path(git_dir.display()),
541
        ui::bookmark(&r.branch),
542
        ui::dim(format!(
543
            "(currently {}; {} already exported)",
544
            plural(r.heads, "head"),
545
            r.skipped
546
        ))
547
    );
548
    Ok(0)
549
}
550
551
pub fn git_fetch(url: &str, branch: &str) -> Result<i32> {
552
    let repo = open()?;
553
    let sp = ui::spinner(&format!("Fetching {url} {branch}…"));
554
    let r = repo.git_fetch(url, branch)?;
555
    sp.clear();
556
    if r.commits == 0 {
557
        println!(
558
            "{} {}",
559
            ui::done("Fetched"),
560
            ui::dim(format!("nothing new from {url} {branch}"))
561
        );
562
    } else {
563
        println!(
564
            "{} {} ({} merges) from {} {}{}{} now has {}",
565
            ui::done("Fetched"),
566
            plural(r.commits, "new commit"),
567
            r.merges,
568
            ui::path(url),
569
            ui::bookmark(branch),
570
            ui::sep(),
571
            ui::bookmark(&repo.config.bookmark),
572
            plural(r.heads, "head")
573
        );
574
        if !repo.snapshot("oxy git fetch")?.changed {
575
            println!("  {} {}", ui::note(), ui::dim("working copy updated"));
576
        } else {
577
            println!(
578
                "  {} {}",
579
                ui::note(),
580
                ui::dim("run oxy checkout to update the working copy")
581
            );
582
        }
583
    }
584
    if r.submodules > 0 {
585
        println!(
586
            "  {} {}",
587
            ui::note(),
588
            ui::dim(format!(
589
                "{} submodule {} imported as subrepos with Git pins",
590
                r.submodules,
591
                if r.submodules == 1 {
592
                    "entry"
593
                } else {
594
                    "entries"
595
                }
596
            ))
597
        );
598
    }
599
    Ok(0)
600
}
601
602
pub fn git_push(url: &str, branch: &str) -> Result<i32> {
603
    let repo = open()?;
604
    let sp = ui::spinner(&format!("Pushing to {url} {branch}…"));
605
    let r = repo.git_push(url, branch)?;
606
    sp.clear();
607
    println!(
608
        "{} {} to {} {} {}",
609
        ui::done("Pushed"),
610
        plural(r.exported, "new commit"),
611
        ui::path(url),
612
        ui::bookmark(&r.branch),
613
        ui::dim(format!("({} already there)", r.skipped))
614
    );
615
    Ok(0)
616
}
617
618
/// `oxy git verify`: exit 1 if any commit's tree is not reproduced.
619
pub fn git_verify(git_dir: &std::path::Path, branch: &str) -> Result<i32> {
620
    let repo = open()?;
621
    let started = std::time::Instant::now();
622
    let sp = ui::spinner(&format!(
623
        "Rebuilding every commit of {} {branch}…",
624
        git_dir.display()
625
    ));
626
    let r = repo.verify_git_import(git_dir, branch)?;
627
    sp.clear();
628
    for (_, what) in &r.mismatches {
629
        println!("{} {what}", ui::err(ui::glyph("✖", "x")));
630
    }
631
    if r.mismatches.is_empty() {
632
        println!(
633
            "{}",
634
            ui::done(format!(
635
                "Every commit reproduced: {} commits, {} files compared, in {:.1}s",
636
                r.commits,
637
                r.files_compared,
638
                started.elapsed().as_secs_f64()
639
            ))
640
        );
641
        Ok(0)
642
    } else {
643
        println!(
644
            "{} differences in {} commits checked",
645
            r.mismatches.len(),
646
            r.commits
647
        );
648
        Ok(1)
649
    }
650
}
651
652
pub fn git_import(git_dir: &std::path::Path, dest: &std::path::Path, branch: &str) -> Result<i32> {
653
    let repo = Repo::init(dest)?;
654
    let started = std::time::Instant::now();
655
    let sp = ui::spinner(&format!("Importing {} {branch}…", git_dir.display()));
656
    let r = repo.import_git(git_dir, branch)?;
657
    sp.clear();
658
    println!(
659
        "{} {} ({} merges) from {} {} into {} {}",
660
        ui::done("Imported"),
661
        plural(r.commits, "commit"),
662
        r.merges,
663
        ui::path(git_dir.display()),
664
        ui::bookmark(branch),
665
        ui::path(repo.root().display()),
666
        ui::dim(format!(
667
            "in {:.1?}; {} now has {}",
668
            started.elapsed(),
669
            repo.config.bookmark,
670
            plural(r.heads, "head")
671
        ))
672
    );
673
    if r.submodules > 0 {
674
        println!(
675
            "  {} {}",
676
            ui::note(),
677
            ui::dim(format!(
678
                "{} submodule {} imported as subrepos with Git pins",
679
                r.submodules,
680
                if r.submodules == 1 {
681
                    "entry"
682
                } else {
683
                    "entries"
684
                }
685
            ))
686
        );
687
    }
688
    Ok(0)
689
}
690
691
pub fn submodule_add(url: &str, path: &str, bookmark: Option<&str>) -> Result<i32> {
692
    let repo = open()?;
693
    let sp = ui::spinner(&format!("Cloning {url} into {path}…"));
694
    let pin = repo.submodule_add(url, path, bookmark)?;
695
    sp.done(&format!(
696
        "{} subrepo {} {} {}",
697
        ui::done("Added"),
698
        ui::path(path),
699
        ui::dim(ui::glyph("→", "->")),
700
        ui::dim(pin.summary())
701
    ));
702
    println!(
703
        "  {} {}",
704
        ui::note(),
705
        ui::dim("recorded in .oxymodules; commit to pin it")
706
    );
707
    Ok(0)
708
}
709
710
pub fn submodule_update(init: bool, paths: &[String]) -> Result<i32> {
711
    let repo = open()?;
712
    let sp = ui::spinner("Updating subrepos…");
713
    let results = repo.submodule_update(init, paths)?;
714
    sp.clear();
715
    Ok(print_subrepo_results(results))
716
}
717
718
fn print_subrepo_results(results: Vec<(String, oxy_core::repo::SubrepoSync)>) -> i32 {
719
    if results.is_empty() {
720
        println!("{}", ui::dim("No subrepos."));
721
    }
722
    let mut code = 0;
723
    for (path, r) in results {
724
        use oxy_core::repo::SubrepoSync::*;
725
        let line = match r {
726
            Updated => ui::done("Updated"),
727
            UpToDate => ui::ok(format!("{} up to date", ui::glyph("✔", "*"))),
728
            Missing => {
729
                code = 1;
730
                ui::warn(format!(
731
                    "{} missing (pass --init to clone)",
732
                    ui::glyph("⚠", "!")
733
                ))
734
            }
735
            Dirty => {
736
                code = 1;
737
                ui::warn(format!(
738
                    "{} has uncommitted changes; left as is",
739
                    ui::glyph("⚠", "!")
740
                ))
741
            }
742
            KeptBookmark { bookmark, newer } => ui::warn(format!(
743
                "{} checked out at the pin; its bookmark {bookmark} keeps {} the pin lacks",
744
                ui::glyph("⚠", "!"),
745
                plural(newer, "newer change")
746
            )),
747
            Failed(e) => {
748
                code = 1;
749
                ui::err(format!("{} {e}", ui::glyph("✖", "x")))
750
            }
751
        };
752
        println!("{line} {}", ui::path(path));
753
    }
754
    code
755
}
756
757
fn pin_json(p: &oxy_core::subrepo::Pin) -> String {
758
    match p {
759
        oxy_core::subrepo::Pin::Oxy {
760
            repo,
761
            heads,
762
            bookmark,
763
        } => json::obj([
764
            ("kind", json::s("oxy")),
765
            (
766
                "repo",
767
                json::s(&repo.iter().map(|b| format!("{b:02x}")).collect::<String>()),
768
            ),
769
            ("heads", json::hashes(heads)),
770
            ("bookmark", json::s(bookmark)),
771
        ]),
772
        oxy_core::subrepo::Pin::Git { sha, branch } => json::obj([
773
            ("kind", json::s("git")),
774
            ("sha", json::s(sha)),
775
            ("branch", json::s(branch)),
776
        ]),
777
    }
778
}
779
780
pub fn submodule_status(as_json: bool) -> Result<i32> {
781
    let repo = open()?;
782
    let subs = repo.subrepos()?;
783
    if as_json {
784
        println!(
785
            "{}",
786
            json::arr(subs.iter().map(|s| {
787
                json::obj([
788
                    ("path", json::s(&s.path)),
789
                    ("pin", pin_json(&s.pin)),
790
                    ("actual", json::opt(s.actual.as_ref(), pin_json)),
791
                    ("at_pin", json::b(s.actual.as_ref() == Some(&s.pin))),
792
                    ("dirty", json::b(s.dirty)),
793
                    ("committed", json::b(s.committed)),
794
                    ("url", json::opt(s.url.as_deref(), json::s)),
795
                ])
796
            }))
797
        );
798
        return Ok(0);
799
    }
800
    if subs.is_empty() {
801
        println!("{}", ui::dim("No subrepos."));
802
    }
803
    for s in subs {
804
        let state = match (&s.actual, s.dirty) {
805
            _ if !s.committed => {
806
                ui::warn(format!("{} added, not committed yet", ui::glyph("+", "+")))
807
            }
808
            (None, _) => ui::warn(format!("{} missing", ui::glyph("⚠", "!"))),
809
            (Some(a), dirty) if *a == s.pin => {
810
                if dirty {
811
                    ui::warn(format!(
812
                        "{} at pin, uncommitted changes",
813
                        ui::glyph("✎", "~")
814
                    ))
815
                } else {
816
                    ui::ok(format!("{} at pin", ui::glyph("✔", "*")))
817
                }
818
            }
819
            (Some(a), _) => ui::warn(format!("{} at {}", ui::glyph("↕", "<>"), a.summary())),
820
        };
821
        println!(
822
            "{} {}{}{}{}{state}",
823
            ui::ok(ui::glyph("⧉", "#")),
824
            ui::path(&s.path),
825
            ui::sep(),
826
            ui::dim(s.pin.summary()),
827
            ui::sep()
828
        );
829
        if let Some(u) = s.url {
830
            println!("    {} {}", ui::dim(ui::glyph("↳", "->")), ui::dim(u));
831
        }
832
    }
833
    Ok(0)
834
}
835
836
pub fn submodule_remove(path: &str) -> Result<i32> {
837
    let repo = open()?;
838
    repo.submodule_remove(path)?;
839
    println!(
840
        "{} subrepo {} {}",
841
        ui::done("Removed"),
842
        ui::path(path),
843
        ui::dim("(directory left in place; commit to record the removal)")
844
    );
845
    Ok(0)
846
}
847
848
pub fn deepen(remote: &str, depth: u32) -> Result<i32> {
849
    let repo = open()?;
850
    if !repo.is_shallow() {
851
        println!(
852
            "{}",
853
            ui::dim("This repository is not shallow; nothing to deepen.")
854
        );
855
        return Ok(0);
856
    }
857
    let sp = ui::spinner(&format!("Fetching {depth} more levels from {remote}…"));
858
    let n = repo.deepen(remote, depth)?;
859
    sp.done(&format!(
860
        "{} {}; {}",
861
        ui::done("Deepened by"),
862
        plural(n, "change"),
863
        if repo.is_shallow() {
864
            "still shallow".to_string()
865
        } else {
866
            ui::ok("history is now complete")
867
        }
868
    ));
869
    Ok(0)
870
}