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