OXYGENHUB
# 170bb436e1d5 oxygen / src / cli / sync.rs
28.1 KiB · Rust · last changed pull: bring a working copy that fell behind up to its bookmark 26 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
            if r.checked_out {
351
                ui::dim(" The working copy had fallen behind it and is updated.")
352
            } else {
353
                String::new()
354
            }
355
        ));
356
        others_pulled(&r.others);
357
        others_behind(&repo, &remote);
358
        if r.checked_out {
359
            super::workspace::where_now(&repo);
360
        }
361
        return Ok(0);
362
    }
363
    sp.done(&format!(
364
        "{} {} now has {}{}",
365
        ui::done("Pulled:"),
366
        ui::bookmark(&repo.config.bookmark),
367
        plural(r.heads.len(), "head"),
368
        ui::dim(if r.checked_out {
369
            "; working copy updated"
370
        } else {
371
            "; run oxy checkout to update the working copy"
372
        })
373
    ));
374
    let snap = repo.snapshot("oxy pull")?;
375
    if snap.base_snapshot.is_conflicted() {
376
        println!(
377
            "  {} {}",
378
            ui::caution(),
379
            ui::warn("the result has conflicts; see oxy status")
380
        );
381
    }
382
    others_pulled(&r.others);
383
    others_behind(&repo, &remote);
384
    subrepos_behind(&repo);
385
    super::workspace::where_now(&repo);
386
    Ok(0)
387
}
388
389
/// The other bookmarks a pull moved.
390
fn others_pulled(others: &[String]) {
391
    if others.is_empty() {
392
        return;
393
    }
394
    let shown: Vec<String> = others.iter().take(8).map(ui::bookmark).collect();
395
    let more = others.len().saturating_sub(8);
396
    println!(
397
        "  {} {}{}",
398
        ui::done("Also updated"),
399
        shown.join(", "),
400
        if more > 0 {
401
            ui::dim(format!(" and {more} more"))
402
        } else {
403
            String::new()
404
        }
405
    );
406
}
407
408
/// `oxy push [REMOTE] --delete NAME`.
409
pub fn push_delete(remote: Option<&str>, name: &str, as_json: bool) -> Result<i32> {
410
    let repo = open()?;
411
    let remote = remote_name(&repo, remote);
412
    let sp = ui::spinner(&format!("Deleting {remote}/{name}…"));
413
    let results = repo.push_delete(&remote, name)?;
414
    sp.clear();
415
    if as_json {
416
        println!(
417
            "{}",
418
            json::arr(results.iter().map(|r| {
419
                json::obj([
420
                    ("name", json::s(&r.name)),
421
                    ("ok", json::b(r.ok)),
422
                    ("reason", json::s(&r.reason)),
423
                    ("state", json::s("")),
424
                ])
425
            }))
426
        );
427
        return Ok(if results.iter().all(|r| r.ok) { 0 } else { 1 });
428
    }
429
    let mut code = 0;
430
    for r in results {
431
        if r.ok {
432
            println!(
433
                "{} {}",
434
                ui::done("Deleted"),
435
                ui::id(format!("{remote}/{}", r.name))
436
            );
437
        } else {
438
            println!(
439
                "{} {} {}{}{}",
440
                ui::err(ui::glyph("✖", "x")),
441
                ui::err("Rejected"),
442
                ui::id(format!("{remote}/{}", r.name)),
443
                ui::sep(),
444
                r.reason
445
            );
446
            code = 1;
447
        }
448
    }
449
    Ok(code)
450
}
451
452
pub fn push(
453
    remote: Option<&str>,
454
    force: bool,
455
    bookmark: Option<&str>,
456
    as_json: bool,
457
) -> Result<i32> {
458
    let repo = open()?;
459
    let remote = remote_name(&repo, remote);
460
    let sp = ui::spinner(&format!("Pushing to {remote}…"));
461
    let results = match bookmark {
462
        Some(b) => repo.push_bookmark(&remote, b, force)?,
463
        None => repo.push(&remote, force)?,
464
    };
465
    sp.clear();
466
    if as_json {
467
        println!(
468
            "{}",
469
            json::arr(results.iter().map(|r| json::obj([
470
                ("name", json::s(&r.name)),
471
                ("ok", json::b(r.ok)),
472
                ("reason", json::s(&r.reason))
473
            ])))
474
        );
475
        return Ok(if results.iter().all(|r| r.ok) { 0 } else { 1 });
476
    }
477
    let mut code = 0;
478
    for r in results {
479
        if r.ok {
480
            println!(
481
                "{} {}{}{}",
482
                ui::done("Pushed"),
483
                ui::id(format!("{remote}/{}", r.name)),
484
                ui::sep(),
485
                ui::dim(if r.reason.is_empty() {
486
                    "updated"
487
                } else {
488
                    r.reason.as_str()
489
                })
490
            );
491
        } else {
492
            println!(
493
                "{} {} {}{}{}",
494
                ui::err(ui::glyph("✖", "x")),
495
                ui::err("Rejected"),
496
                ui::id(format!("{remote}/{}", r.name)),
497
                ui::sep(),
498
                r.reason
499
            );
500
            code = 1;
501
        }
502
    }
503
    Ok(code)
504
}
505
506
pub fn serve(
507
    root: PathBuf,
508
    bind: &str,
509
    tokens: Vec<String>,
510
    tls: Option<(PathBuf, PathBuf)>,
511
) -> Result<i32> {
512
    let listener = std::net::TcpListener::bind(bind).with_context(|| format!("binding {bind}"))?;
513
    let root = root.canonicalize()?;
514
    let tls = tls.map(|(cert, key)| oxy_server::TlsFiles { cert, key });
515
    println!(
516
        "Serving repositories under {} on {}://{bind}/<repo>/oxy/v1/ ({})",
517
        root.display(),
518
        if tls.is_some() { "https" } else { "http" },
519
        if tokens.is_empty() {
520
            "open: no push tokens configured"
521
        } else {
522
            "push requires a token"
523
        }
524
    );
525
    if tls.is_none()
526
        && !bind.starts_with("127.")
527
        && !bind.starts_with("localhost")
528
        && !bind.starts_with("[::1]")
529
    {
530
        eprintln!("warning: serving plain HTTP on a non-loopback address; put a TLS terminator in front or pass --tls-cert/--tls-key");
531
    }
532
    oxy_server::run_blocking(listener, oxy_server::ServerConfig { root, tokens, tls })?;
533
    Ok(0)
534
}
535
536
pub fn git_export(git_dir: &std::path::Path, branch: Option<&str>) -> Result<i32> {
537
    let repo = open()?;
538
    let sp = ui::spinner("Exporting to Git…");
539
    let r = match branch {
540
        Some(b) => repo.git_export_as(git_dir, b)?,
541
        None => repo.git_export(git_dir)?,
542
    };
543
    sp.clear();
544
    println!(
545
        "{} {} to {} as branch {} {}",
546
        ui::done("Exported"),
547
        plural(r.exported, "new state"),
548
        ui::path(git_dir.display()),
549
        ui::bookmark(&r.branch),
550
        ui::dim(format!(
551
            "(currently {}; {} already exported)",
552
            plural(r.heads, "head"),
553
            r.skipped
554
        ))
555
    );
556
    Ok(0)
557
}
558
559
pub fn git_fetch(url: &str, branch: &str) -> Result<i32> {
560
    let repo = open()?;
561
    let sp = ui::spinner(&format!("Fetching {url} {branch}…"));
562
    let r = repo.git_fetch(url, branch)?;
563
    sp.clear();
564
    if r.commits == 0 {
565
        println!(
566
            "{} {}",
567
            ui::done("Fetched"),
568
            ui::dim(format!("nothing new from {url} {branch}"))
569
        );
570
    } else {
571
        println!(
572
            "{} {} ({} merges) from {} {}{}{} now has {}",
573
            ui::done("Fetched"),
574
            plural(r.commits, "new commit"),
575
            r.merges,
576
            ui::path(url),
577
            ui::bookmark(branch),
578
            ui::sep(),
579
            ui::bookmark(&repo.config.bookmark),
580
            plural(r.heads, "head")
581
        );
582
        if !repo.snapshot("oxy git fetch")?.changed {
583
            println!("  {} {}", ui::note(), ui::dim("working copy updated"));
584
        } else {
585
            println!(
586
                "  {} {}",
587
                ui::note(),
588
                ui::dim("run oxy checkout to update the working copy")
589
            );
590
        }
591
    }
592
    if r.submodules > 0 {
593
        println!(
594
            "  {} {}",
595
            ui::note(),
596
            ui::dim(format!(
597
                "{} submodule {} imported as subrepos with Git pins",
598
                r.submodules,
599
                if r.submodules == 1 {
600
                    "entry"
601
                } else {
602
                    "entries"
603
                }
604
            ))
605
        );
606
    }
607
    Ok(0)
608
}
609
610
pub fn git_push(url: &str, branch: &str) -> Result<i32> {
611
    let repo = open()?;
612
    let sp = ui::spinner(&format!("Pushing to {url} {branch}…"));
613
    let r = repo.git_push(url, branch)?;
614
    sp.clear();
615
    println!(
616
        "{} {} to {} {} {}",
617
        ui::done("Pushed"),
618
        plural(r.exported, "new commit"),
619
        ui::path(url),
620
        ui::bookmark(&r.branch),
621
        ui::dim(format!("({} already there)", r.skipped))
622
    );
623
    Ok(0)
624
}
625
626
/// `oxy git verify`: exit 1 if any commit's tree is not reproduced.
627
pub fn git_verify(git_dir: &std::path::Path, branch: &str) -> Result<i32> {
628
    let repo = open()?;
629
    let started = std::time::Instant::now();
630
    let sp = ui::spinner(&format!(
631
        "Rebuilding every commit of {} {branch}…",
632
        git_dir.display()
633
    ));
634
    let r = repo.verify_git_import(git_dir, branch)?;
635
    sp.clear();
636
    for (_, what) in &r.mismatches {
637
        println!("{} {what}", ui::err(ui::glyph("✖", "x")));
638
    }
639
    if r.mismatches.is_empty() {
640
        println!(
641
            "{}",
642
            ui::done(format!(
643
                "Every commit reproduced: {} commits, {} files compared, in {:.1}s",
644
                r.commits,
645
                r.files_compared,
646
                started.elapsed().as_secs_f64()
647
            ))
648
        );
649
        Ok(0)
650
    } else {
651
        println!(
652
            "{} differences in {} commits checked",
653
            r.mismatches.len(),
654
            r.commits
655
        );
656
        Ok(1)
657
    }
658
}
659
660
pub fn git_import(git_dir: &std::path::Path, dest: &std::path::Path, branch: &str) -> Result<i32> {
661
    let repo = Repo::init(dest)?;
662
    let started = std::time::Instant::now();
663
    let sp = ui::spinner(&format!("Importing {} {branch}…", git_dir.display()));
664
    let r = repo.import_git_with(git_dir, branch, &mut |where_| sp.set(where_))?;
665
    sp.clear();
666
    println!(
667
        "{} {} ({} merges) from {} {} into {} {}",
668
        ui::done("Imported"),
669
        plural(r.commits, "commit"),
670
        r.merges,
671
        ui::path(git_dir.display()),
672
        ui::bookmark(branch),
673
        ui::path(repo.root().display()),
674
        ui::dim(format!(
675
            "in {:.1?}; {} now has {}",
676
            started.elapsed(),
677
            repo.config.bookmark,
678
            plural(r.heads, "head")
679
        ))
680
    );
681
    if r.submodules > 0 {
682
        println!(
683
            "  {} {}",
684
            ui::note(),
685
            ui::dim(format!(
686
                "{} submodule {} imported as subrepos with Git pins",
687
                r.submodules,
688
                if r.submodules == 1 {
689
                    "entry"
690
                } else {
691
                    "entries"
692
                }
693
            ))
694
        );
695
    }
696
    Ok(0)
697
}
698
699
pub fn submodule_add(url: &str, path: &str, bookmark: Option<&str>) -> Result<i32> {
700
    let repo = open()?;
701
    let sp = ui::spinner(&format!("Cloning {url} into {path}…"));
702
    let pin = repo.submodule_add(url, path, bookmark)?;
703
    sp.done(&format!(
704
        "{} subrepo {} {} {}",
705
        ui::done("Added"),
706
        ui::path(path),
707
        ui::dim(ui::glyph("→", "->")),
708
        ui::dim(pin.summary())
709
    ));
710
    println!(
711
        "  {} {}",
712
        ui::note(),
713
        ui::dim("recorded in .oxymodules; commit to pin it")
714
    );
715
    Ok(0)
716
}
717
718
pub fn submodule_update(init: bool, paths: &[String]) -> Result<i32> {
719
    let repo = open()?;
720
    let sp = ui::spinner("Updating subrepos…");
721
    let results = repo.submodule_update(init, paths)?;
722
    let unpinned: Vec<_> = repo
723
        .unpinned_modules()?
724
        .into_iter()
725
        .filter(|(p, _)| paths.is_empty() || paths.iter().any(|q| q.trim_end_matches('/') == p))
726
        .collect();
727
    sp.clear();
728
    if results.is_empty() && unpinned.is_empty() {
729
        println!("{}", ui::dim("No subrepos."));
730
    }
731
    let code = print_subrepo_results(results);
732
    print_unpinned(&unpinned);
733
    Ok(if unpinned.is_empty() { code } else { 1 })
734
}
735
736
/// `.oxymodules` entries never added: nothing to clone, so say how to add
737
/// them (oxygen#72).
738
fn print_unpinned(unpinned: &[(String, oxy_core::subrepo::Module)]) {
739
    for (path, m) in unpinned {
740
        let url = if m.url.is_empty() { "<url>" } else { &m.url };
741
        println!(
742
            "{} {}",
743
            ui::warn(format!(
744
                "{} in .oxymodules but never added, so no pin",
745
                ui::glyph("⚠", "!")
746
            )),
747
            ui::path(path)
748
        );
749
        println!(
750
            "  {}",
751
            ui::dim(format!("add it with: oxy submodule add {url} {path}"))
752
        );
753
    }
754
}
755
756
fn print_subrepo_results(results: Vec<(String, oxy_core::repo::SubrepoSync)>) -> i32 {
757
    let mut code = 0;
758
    for (path, r) in results {
759
        use oxy_core::repo::SubrepoSync::*;
760
        let line = match r {
761
            Updated => ui::done("Updated"),
762
            UpToDate => ui::ok(format!("{} up to date", ui::glyph("✔", "*"))),
763
            Missing => {
764
                code = 1;
765
                ui::warn(format!(
766
                    "{} missing (pass --init to clone)",
767
                    ui::glyph("⚠", "!")
768
                ))
769
            }
770
            Dirty => {
771
                code = 1;
772
                ui::warn(format!(
773
                    "{} has uncommitted changes; left as is",
774
                    ui::glyph("⚠", "!")
775
                ))
776
            }
777
            KeptBookmark { bookmark, newer } => ui::warn(format!(
778
                "{} checked out at the pin; its bookmark {bookmark} keeps {} the pin lacks",
779
                ui::glyph("⚠", "!"),
780
                plural(newer, "newer change")
781
            )),
782
            Failed(e) => {
783
                code = 1;
784
                ui::err(format!("{} {e}", ui::glyph("✖", "x")))
785
            }
786
        };
787
        println!("{line} {}", ui::path(path));
788
    }
789
    code
790
}
791
792
fn pin_json(p: &oxy_core::subrepo::Pin) -> String {
793
    match p {
794
        oxy_core::subrepo::Pin::Oxy {
795
            repo,
796
            heads,
797
            bookmark,
798
        } => json::obj([
799
            ("kind", json::s("oxy")),
800
            (
801
                "repo",
802
                json::s(&repo.iter().map(|b| format!("{b:02x}")).collect::<String>()),
803
            ),
804
            ("heads", json::hashes(heads)),
805
            ("bookmark", json::s(bookmark)),
806
        ]),
807
        oxy_core::subrepo::Pin::Git { sha, branch } => json::obj([
808
            ("kind", json::s("git")),
809
            ("sha", json::s(sha)),
810
            ("branch", json::s(branch)),
811
        ]),
812
    }
813
}
814
815
pub fn submodule_status(as_json: bool) -> Result<i32> {
816
    let repo = open()?;
817
    let subs = repo.subrepos()?;
818
    let unpinned = repo.unpinned_modules()?;
819
    if as_json {
820
        let pinned = subs.iter().map(|s| {
821
            json::obj([
822
                ("path", json::s(&s.path)),
823
                ("pin", pin_json(&s.pin)),
824
                ("actual", json::opt(s.actual.as_ref(), pin_json)),
825
                ("at_pin", json::b(s.actual.as_ref() == Some(&s.pin))),
826
                ("dirty", json::b(s.dirty)),
827
                ("committed", json::b(s.committed)),
828
                ("url", json::opt(s.url.as_deref(), json::s)),
829
            ])
830
        });
831
        // Listed in .oxymodules but never added: no pin at all.
832
        let unpinned_json = unpinned.iter().map(|(path, m)| {
833
            json::obj([
834
                ("path", json::s(path)),
835
                ("pin", "null".to_string()),
836
                ("actual", "null".to_string()),
837
                ("at_pin", json::b(false)),
838
                ("dirty", json::b(false)),
839
                ("committed", json::b(false)),
840
                ("url", json::s(&m.url)),
841
            ])
842
        });
843
        println!("{}", json::arr(pinned.chain(unpinned_json)));
844
        return Ok(0);
845
    }
846
    if subs.is_empty() && unpinned.is_empty() {
847
        println!("{}", ui::dim("No subrepos."));
848
    }
849
    for s in subs {
850
        let state = match (&s.actual, s.dirty) {
851
            _ if !s.committed => {
852
                ui::warn(format!("{} added, not committed yet", ui::glyph("+", "+")))
853
            }
854
            (None, _) => ui::warn(format!("{} missing", ui::glyph("⚠", "!"))),
855
            (Some(a), dirty) if *a == s.pin => {
856
                if dirty {
857
                    ui::warn(format!(
858
                        "{} at pin, uncommitted changes",
859
                        ui::glyph("✎", "~")
860
                    ))
861
                } else {
862
                    ui::ok(format!("{} at pin", ui::glyph("✔", "*")))
863
                }
864
            }
865
            (Some(a), _) => ui::warn(format!("{} at {}", ui::glyph("↕", "<>"), a.summary())),
866
        };
867
        println!(
868
            "{} {}{}{}{}{state}",
869
            ui::ok(ui::glyph("⧉", "#")),
870
            ui::path(&s.path),
871
            ui::sep(),
872
            ui::dim(s.pin.summary()),
873
            ui::sep()
874
        );
875
        if let Some(u) = s.url {
876
            println!("    {} {}", ui::dim(ui::glyph("↳", "->")), ui::dim(u));
877
        }
878
    }
879
    print_unpinned(&unpinned);
880
    Ok(0)
881
}
882
883
pub fn submodule_remove(path: &str) -> Result<i32> {
884
    let repo = open()?;
885
    repo.submodule_remove(path)?;
886
    println!(
887
        "{} subrepo {} {}",
888
        ui::done("Removed"),
889
        ui::path(path),
890
        ui::dim("(directory left in place; commit to record the removal)")
891
    );
892
    Ok(0)
893
}
894
895
pub fn deepen(remote: &str, depth: u32) -> Result<i32> {
896
    let repo = open()?;
897
    if !repo.is_shallow() {
898
        println!(
899
            "{}",
900
            ui::dim("This repository is not shallow; nothing to deepen.")
901
        );
902
        return Ok(0);
903
    }
904
    let sp = ui::spinner(&format!("Fetching {depth} more levels from {remote}…"));
905
    let n = repo.deepen(remote, depth)?;
906
    sp.done(&format!(
907
        "{} {}; {}",
908
        ui::done("Deepened by"),
909
        plural(n, "change"),
910
        if repo.is_shallow() {
911
            "still shallow".to_string()
912
        } else {
913
            ui::ok("history is now complete")
914
        }
915
    ));
916
    Ok(0)
917
}