OXYGENHUB
# 54e2e6309aa3 oxygen / src / cli / sync.rs
26.9 KiB · Rust · last changed git recover: rescue an import that stopped before it finished 29 days ago source blame history raw
1
//! Commands that talk to remotes, and the reference server.
2
3
use super::format::plural;
4
use super::json;
5
use super::open;
6
use super::ui;
7
use anyhow::{Context, Result};
8
use oxy_core::repo::Repo;
9
use std::path::PathBuf;
10
11
pub fn clone(
12
    url: &str,
13
    dest: Option<PathBuf>,
14
    max_blob: Option<&str>,
15
    sparse: &[String],
16
    depth: Option<u32>,
17
    recursive: bool,
18
) -> Result<i32> {
19
    let dest = dest.unwrap_or_else(|| {
20
        let base = url
21
            .trim_end_matches('/')
22
            .rsplit('/')
23
            .next()
24
            .unwrap_or("repo");
25
        PathBuf::from(base)
26
    });
27
    let max_blob = max_blob.map(oxy_core::repo::parse_size).transpose()?;
28
    let sp = ui::spinner(&format!("Cloning {url}…"));
29
    let repo = match depth {
30
        Some(d) => Repo::clone_shallow(url, &dest, d, max_blob, sparse)?,
31
        None => Repo::clone_with(url, &dest, max_blob, sparse)?,
32
    };
33
    let heads = repo.bookmark_heads()?;
34
    sp.done(&format!(
35
        "{} into {} {}",
36
        ui::done("Cloned"),
37
        ui::path(repo.root().display()),
38
        ui::dim(format!(
39
            "({url}, {} with {})",
40
            ui::bookmark(&repo.config.bookmark),
41
            plural(heads.len(), "head")
42
        ))
43
    ));
44
    let others = repo.remote_only_bookmarks()?.len();
45
    if others > 0 {
46
        println!(
47
            "  {} {}",
48
            ui::note(),
49
            ui::dim(format!(
50
                "origin has {} more: oxy bookmark list --all, then oxy bookmark switch NAME",
51
                plural(others, "bookmark")
52
            ))
53
        );
54
    }
55
    let subrepos = repo.subrepos()?.len();
56
    if subrepos == 0 {
57
        return Ok(0);
58
    }
59
    if recursive {
60
        let sp = ui::spinner("Cloning subrepos…");
61
        let results = repo.submodule_update(true, &[])?;
62
        sp.clear();
63
        return Ok(print_subrepo_results(results));
64
    }
65
    println!(
66
        "  {} {}",
67
        ui::note(),
68
        ui::dim(format!(
69
            "{} not cloned: oxy submodule update --init (or clone with --recursive)",
70
            plural(subrepos, "subrepo")
71
        ))
72
    );
73
    Ok(0)
74
}
75
76
/// After a switch or pull: say when subrepos are not at their pins.
77
pub fn subrepos_behind(repo: &Repo) {
78
    let Ok(subs) = repo.subrepos() else {
79
        return;
80
    };
81
    let stale = subs
82
        .iter()
83
        .filter(|s| s.committed && s.actual.as_ref() != Some(&s.pin))
84
        .count();
85
    if stale > 0 {
86
        println!(
87
            "  {} {}",
88
            ui::note(),
89
            ui::dim(format!(
90
                "{} not at {} pin: oxy submodule update --init",
91
                plural(stale, "subrepo"),
92
                if stale == 1 { "its" } else { "their" }
93
            ))
94
        );
95
    }
96
}
97
98
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_recover() -> Result<i32> {
552
    let repo = open()?;
553
    let sp = ui::spinner("Reading the store…");
554
    let (changes, heads) = repo.recover_git_import(&|m| sp.set(m))?;
555
    sp.done(&format!(
556
        "{} {} from imported Git commits: {} now has {}",
557
        ui::done("Recovered"),
558
        plural(changes, "change"),
559
        ui::bookmark(&repo.config.bookmark),
560
        plural(heads, "head")
561
    ));
562
    println!(
563
        "  {} {}",
564
        ui::note(),
565
        ui::dim("carry on with oxy git fetch GIT_DIR --branch BRANCH")
566
    );
567
    Ok(0)
568
}
569
570
pub fn git_fetch(url: &str, branch: &str) -> Result<i32> {
571
    let repo = open()?;
572
    let sp = ui::spinner(&format!("Fetching {url} {branch}…"));
573
    let r = repo.git_fetch(url, branch)?;
574
    sp.clear();
575
    if r.commits == 0 {
576
        println!(
577
            "{} {}",
578
            ui::done("Fetched"),
579
            ui::dim(format!("nothing new from {url} {branch}"))
580
        );
581
    } else {
582
        println!(
583
            "{} {} ({} merges) from {} {}{}{} now has {}",
584
            ui::done("Fetched"),
585
            plural(r.commits, "new commit"),
586
            r.merges,
587
            ui::path(url),
588
            ui::bookmark(branch),
589
            ui::sep(),
590
            ui::bookmark(&repo.config.bookmark),
591
            plural(r.heads, "head")
592
        );
593
        if !repo.snapshot("oxy git fetch")?.changed {
594
            println!("  {} {}", ui::note(), ui::dim("working copy updated"));
595
        } else {
596
            println!(
597
                "  {} {}",
598
                ui::note(),
599
                ui::dim("run oxy checkout to update the working copy")
600
            );
601
        }
602
    }
603
    if r.submodules > 0 {
604
        println!(
605
            "  {} {}",
606
            ui::note(),
607
            ui::dim(format!(
608
                "{} submodule {} imported as subrepos with Git pins",
609
                r.submodules,
610
                if r.submodules == 1 {
611
                    "entry"
612
                } else {
613
                    "entries"
614
                }
615
            ))
616
        );
617
    }
618
    Ok(0)
619
}
620
621
pub fn git_push(url: &str, branch: &str) -> Result<i32> {
622
    let repo = open()?;
623
    let sp = ui::spinner(&format!("Pushing to {url} {branch}…"));
624
    let r = repo.git_push(url, branch)?;
625
    sp.clear();
626
    println!(
627
        "{} {} to {} {} {}",
628
        ui::done("Pushed"),
629
        plural(r.exported, "new commit"),
630
        ui::path(url),
631
        ui::bookmark(&r.branch),
632
        ui::dim(format!("({} already there)", r.skipped))
633
    );
634
    Ok(0)
635
}
636
637
/// `oxy git verify`: exit 1 if any commit's tree is not reproduced.
638
pub fn git_verify(git_dir: &std::path::Path, branch: &str) -> Result<i32> {
639
    let repo = open()?;
640
    let started = std::time::Instant::now();
641
    let sp = ui::spinner(&format!(
642
        "Rebuilding every commit of {} {branch}…",
643
        git_dir.display()
644
    ));
645
    let r = repo.verify_git_import(git_dir, branch)?;
646
    sp.clear();
647
    for (_, what) in &r.mismatches {
648
        println!("{} {what}", ui::err(ui::glyph("✖", "x")));
649
    }
650
    if r.mismatches.is_empty() {
651
        println!(
652
            "{}",
653
            ui::done(format!(
654
                "Every commit reproduced: {} commits, {} files compared, in {:.1}s",
655
                r.commits,
656
                r.files_compared,
657
                started.elapsed().as_secs_f64()
658
            ))
659
        );
660
        Ok(0)
661
    } else {
662
        println!(
663
            "{} differences in {} commits checked",
664
            r.mismatches.len(),
665
            r.commits
666
        );
667
        Ok(1)
668
    }
669
}
670
671
pub fn git_import(git_dir: &std::path::Path, dest: &std::path::Path, branch: &str) -> Result<i32> {
672
    let repo = Repo::init(dest)?;
673
    let started = std::time::Instant::now();
674
    let sp = ui::spinner(&format!("Importing {} {branch}…", git_dir.display()));
675
    let r = repo.import_git_with(git_dir, branch, &mut |where_| sp.set(where_))?;
676
    sp.clear();
677
    println!(
678
        "{} {} ({} merges) from {} {} into {} {}",
679
        ui::done("Imported"),
680
        plural(r.commits, "commit"),
681
        r.merges,
682
        ui::path(git_dir.display()),
683
        ui::bookmark(branch),
684
        ui::path(repo.root().display()),
685
        ui::dim(format!(
686
            "in {:.1?}; {} now has {}",
687
            started.elapsed(),
688
            repo.config.bookmark,
689
            plural(r.heads, "head")
690
        ))
691
    );
692
    if r.submodules > 0 {
693
        println!(
694
            "  {} {}",
695
            ui::note(),
696
            ui::dim(format!(
697
                "{} submodule {} imported as subrepos with Git pins",
698
                r.submodules,
699
                if r.submodules == 1 {
700
                    "entry"
701
                } else {
702
                    "entries"
703
                }
704
            ))
705
        );
706
    }
707
    Ok(0)
708
}
709
710
pub fn submodule_add(url: &str, path: &str, bookmark: Option<&str>) -> Result<i32> {
711
    let repo = open()?;
712
    let sp = ui::spinner(&format!("Cloning {url} into {path}…"));
713
    let pin = repo.submodule_add(url, path, bookmark)?;
714
    sp.done(&format!(
715
        "{} subrepo {} {} {}",
716
        ui::done("Added"),
717
        ui::path(path),
718
        ui::dim(ui::glyph("→", "->")),
719
        ui::dim(pin.summary())
720
    ));
721
    println!(
722
        "  {} {}",
723
        ui::note(),
724
        ui::dim("recorded in .oxymodules; commit to pin it")
725
    );
726
    Ok(0)
727
}
728
729
pub fn submodule_update(init: bool, paths: &[String]) -> Result<i32> {
730
    let repo = open()?;
731
    let sp = ui::spinner("Updating subrepos…");
732
    let results = repo.submodule_update(init, paths)?;
733
    sp.clear();
734
    Ok(print_subrepo_results(results))
735
}
736
737
fn print_subrepo_results(results: Vec<(String, oxy_core::repo::SubrepoSync)>) -> i32 {
738
    if results.is_empty() {
739
        println!("{}", ui::dim("No subrepos."));
740
    }
741
    let mut code = 0;
742
    for (path, r) in results {
743
        use oxy_core::repo::SubrepoSync::*;
744
        let line = match r {
745
            Updated => ui::done("Updated"),
746
            UpToDate => ui::ok(format!("{} up to date", ui::glyph("✔", "*"))),
747
            Missing => {
748
                code = 1;
749
                ui::warn(format!(
750
                    "{} missing (pass --init to clone)",
751
                    ui::glyph("⚠", "!")
752
                ))
753
            }
754
            Dirty => {
755
                code = 1;
756
                ui::warn(format!(
757
                    "{} has uncommitted changes; left as is",
758
                    ui::glyph("⚠", "!")
759
                ))
760
            }
761
            KeptBookmark { bookmark, newer } => ui::warn(format!(
762
                "{} checked out at the pin; its bookmark {bookmark} keeps {} the pin lacks",
763
                ui::glyph("⚠", "!"),
764
                plural(newer, "newer change")
765
            )),
766
            Failed(e) => {
767
                code = 1;
768
                ui::err(format!("{} {e}", ui::glyph("✖", "x")))
769
            }
770
        };
771
        println!("{line} {}", ui::path(path));
772
    }
773
    code
774
}
775
776
fn pin_json(p: &oxy_core::subrepo::Pin) -> String {
777
    match p {
778
        oxy_core::subrepo::Pin::Oxy {
779
            repo,
780
            heads,
781
            bookmark,
782
        } => json::obj([
783
            ("kind", json::s("oxy")),
784
            (
785
                "repo",
786
                json::s(&repo.iter().map(|b| format!("{b:02x}")).collect::<String>()),
787
            ),
788
            ("heads", json::hashes(heads)),
789
            ("bookmark", json::s(bookmark)),
790
        ]),
791
        oxy_core::subrepo::Pin::Git { sha, branch } => json::obj([
792
            ("kind", json::s("git")),
793
            ("sha", json::s(sha)),
794
            ("branch", json::s(branch)),
795
        ]),
796
    }
797
}
798
799
pub fn submodule_status(as_json: bool) -> Result<i32> {
800
    let repo = open()?;
801
    let subs = repo.subrepos()?;
802
    if as_json {
803
        println!(
804
            "{}",
805
            json::arr(subs.iter().map(|s| {
806
                json::obj([
807
                    ("path", json::s(&s.path)),
808
                    ("pin", pin_json(&s.pin)),
809
                    ("actual", json::opt(s.actual.as_ref(), pin_json)),
810
                    ("at_pin", json::b(s.actual.as_ref() == Some(&s.pin))),
811
                    ("dirty", json::b(s.dirty)),
812
                    ("committed", json::b(s.committed)),
813
                    ("url", json::opt(s.url.as_deref(), json::s)),
814
                ])
815
            }))
816
        );
817
        return Ok(0);
818
    }
819
    if subs.is_empty() {
820
        println!("{}", ui::dim("No subrepos."));
821
    }
822
    for s in subs {
823
        let state = match (&s.actual, s.dirty) {
824
            _ if !s.committed => {
825
                ui::warn(format!("{} added, not committed yet", ui::glyph("+", "+")))
826
            }
827
            (None, _) => ui::warn(format!("{} missing", ui::glyph("⚠", "!"))),
828
            (Some(a), dirty) if *a == s.pin => {
829
                if dirty {
830
                    ui::warn(format!(
831
                        "{} at pin, uncommitted changes",
832
                        ui::glyph("✎", "~")
833
                    ))
834
                } else {
835
                    ui::ok(format!("{} at pin", ui::glyph("✔", "*")))
836
                }
837
            }
838
            (Some(a), _) => ui::warn(format!("{} at {}", ui::glyph("↕", "<>"), a.summary())),
839
        };
840
        println!(
841
            "{} {}{}{}{}{state}",
842
            ui::ok(ui::glyph("⧉", "#")),
843
            ui::path(&s.path),
844
            ui::sep(),
845
            ui::dim(s.pin.summary()),
846
            ui::sep()
847
        );
848
        if let Some(u) = s.url {
849
            println!("    {} {}", ui::dim(ui::glyph("↳", "->")), ui::dim(u));
850
        }
851
    }
852
    Ok(0)
853
}
854
855
pub fn submodule_remove(path: &str) -> Result<i32> {
856
    let repo = open()?;
857
    repo.submodule_remove(path)?;
858
    println!(
859
        "{} subrepo {} {}",
860
        ui::done("Removed"),
861
        ui::path(path),
862
        ui::dim("(directory left in place; commit to record the removal)")
863
    );
864
    Ok(0)
865
}
866
867
pub fn deepen(remote: &str, depth: u32) -> Result<i32> {
868
    let repo = open()?;
869
    if !repo.is_shallow() {
870
        println!(
871
            "{}",
872
            ui::dim("This repository is not shallow; nothing to deepen.")
873
        );
874
        return Ok(0);
875
    }
876
    let sp = ui::spinner(&format!("Fetching {depth} more levels from {remote}…"));
877
    let n = repo.deepen(remote, depth)?;
878
    sp.done(&format!(
879
        "{} {}; {}",
880
        ui::done("Deepened by"),
881
        plural(n, "change"),
882
        if repo.is_shallow() {
883
            "still shallow".to_string()
884
        } else {
885
            ui::ok("history is now complete")
886
        }
887
    ));
888
    Ok(0)
889
}