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