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