OXYGENHUB
◆ v0.1.0 oxygen / src / cli / sync.rs
23.1 KiB · Rust · last changed A kept order takes no line that arrives deleted 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 {
60a1223c Andy McCall ↶ 345
        // The state each accepted bookmark now holds on the remote (its local
346
        // state object), so a caller can look up what the push started, such
347
        // as the checks a forge runs on it.
348
        let view = repo.view()?;
75167672 Andy McCall 349
        println!(
350
            "{}",
60a1223c Andy McCall ↶ 351
            json::arr(results.iter().map(|r| {
352
                let state = view
353
                    .bookmarks
354
                    .get(&r.name)
355
                    .filter(|_| r.ok)
356
                    .map(|st| st.to_hex())
357
                    .unwrap_or_default();
358
                json::obj([
359
                    ("name", json::s(&r.name)),
360
                    ("ok", json::b(r.ok)),
361
                    ("reason", json::s(&r.reason)),
362
                    ("state", json::s(&state)),
363
                ])
364
            }))
75167672 Andy McCall 365
        );
c6aa5bd9 Andy McCall ↶ 366
        return Ok(if results.iter().all(|r| r.ok) { 0 } else { 1 });
367
    }
fce44ae9 Andy McCall ↶ 368
    let mut code = 0;
135212de Andy McCall ↶ 369
    for r in results {
fce44ae9 Andy McCall ↶ 370
        if r.ok {
75167672 Andy McCall 371
            println!(
372
                "{} {}{}{}",
373
                ui::done("Pushed"),
374
                ui::id(format!("{remote}/{}", r.name)),
375
                ui::sep(),
376
                ui::dim(if r.reason.is_empty() {
377
                    "updated"
378
                } else {
379
                    r.reason.as_str()
380
                })
381
            );
fce44ae9 Andy McCall ↶ 382
        } else {
75167672 Andy McCall 383
            println!(
384
                "{} {} {}{}{}",
385
                ui::err(ui::glyph("✖", "x")),
386
                ui::err("Rejected"),
387
                ui::id(format!("{remote}/{}", r.name)),
388
                ui::sep(),
389
                r.reason
390
            );
fce44ae9 Andy McCall ↶ 391
            code = 1;
392
        }
393
    }
394
    Ok(code)
395
}
396
75167672 Andy McCall 397
pub fn serve(
398
    root: PathBuf,
399
    bind: &str,
400
    tokens: Vec<String>,
401
    tls: Option<(PathBuf, PathBuf)>,
402
) -> Result<i32> {
fce44ae9 Andy McCall ↶ 403
    let listener = std::net::TcpListener::bind(bind).with_context(|| format!("binding {bind}"))?;
404
    let root = root.canonicalize()?;
2b5ee371 Andy McCall ↶ 405
    let tls = tls.map(|(cert, key)| oxy_server::TlsFiles { cert, key });
fce44ae9 Andy McCall ↶ 406
    println!(
2b5ee371 Andy McCall ↶ 407
        "Serving repositories under {} on {}://{bind}/<repo>/oxy/v1/ ({})",
fce44ae9 Andy McCall ↶ 408
        root.display(),
2b5ee371 Andy McCall ↶ 409
        if tls.is_some() { "https" } else { "http" },
75167672 Andy McCall 410
        if tokens.is_empty() {
411
            "open: no push tokens configured"
412
        } else {
413
            "push requires a token"
414
        }
fce44ae9 Andy McCall ↶ 415
    );
75167672 Andy McCall 416
    if tls.is_none()
417
        && !bind.starts_with("127.")
418
        && !bind.starts_with("localhost")
419
        && !bind.starts_with("[::1]")
420
    {
2b5ee371 Andy McCall ↶ 421
        eprintln!("warning: serving plain HTTP on a non-loopback address; put a TLS terminator in front or pass --tls-cert/--tls-key");
422
    }
423
    oxy_server::run_blocking(listener, oxy_server::ServerConfig { root, tokens, tls })?;
fce44ae9 Andy McCall ↶ 424
    Ok(0)
425
}
79ab8528 Andy McCall ↶ 426
30ea9c1e Andy McCall ↶ 427
pub fn git_export(git_dir: &std::path::Path, branch: Option<&str>) -> Result<i32> {
79ab8528 Andy McCall ↶ 428
    let repo = open()?;
135212de Andy McCall ↶ 429
    let sp = ui::spinner("Exporting to Git…");
30ea9c1e Andy McCall ↶ 430
    let r = match branch {
431
        Some(b) => repo.git_export_as(git_dir, b)?,
432
        None => repo.git_export(git_dir)?,
433
    };
135212de Andy McCall ↶ 434
    sp.clear();
79ab8528 Andy McCall ↶ 435
    println!(
94084087 Andy McCall ↶ 436
        "{} {} to {} as branch {} {}",
437
        ui::done("Exported"),
e8b4e156 Andy McCall ↶ 438
        plural(r.exported, "new state"),
94084087 Andy McCall ↶ 439
        ui::path(git_dir.display()),
440
        ui::bookmark(&r.branch),
75167672 Andy McCall 441
        ui::dim(format!(
442
            "(currently {}; {} already exported)",
443
            plural(r.heads, "head"),
444
            r.skipped
445
        ))
79ab8528 Andy McCall ↶ 446
    );
447
    Ok(0)
448
}
c3069537 Andy McCall ↶ 449
30ea9c1e Andy McCall ↶ 450
pub fn git_fetch(url: &str, branch: &str) -> Result<i32> {
451
    let repo = open()?;
452
    let sp = ui::spinner(&format!("Fetching {url} {branch}…"));
453
    let r = repo.git_fetch(url, branch)?;
454
    sp.clear();
455
    if r.commits == 0 {
75167672 Andy McCall 456
        println!(
457
            "{} {}",
458
            ui::done("Fetched"),
459
            ui::dim(format!("nothing new from {url} {branch}"))
460
        );
30ea9c1e Andy McCall ↶ 461
    } else {
462
        println!(
463
            "{} {} ({} merges) from {} {}{}{} now has {}",
464
            ui::done("Fetched"),
465
            plural(r.commits, "new commit"),
466
            r.merges,
467
            ui::path(url),
468
            ui::bookmark(branch),
469
            ui::sep(),
470
            ui::bookmark(&repo.config.bookmark),
471
            plural(r.heads, "head")
472
        );
473
        if !repo.snapshot("oxy git fetch")?.changed {
474
            println!("  {} {}", ui::note(), ui::dim("working copy updated"));
475
        } else {
75167672 Andy McCall 476
            println!(
477
                "  {} {}",
478
                ui::note(),
479
                ui::dim("run oxy checkout to update the working copy")
480
            );
30ea9c1e Andy McCall ↶ 481
        }
482
    }
4dee277c Andy McCall ↶ 483
    if r.submodules > 0 {
75167672 Andy McCall 484
        println!(
485
            "  {} {}",
486
            ui::note(),
487
            ui::dim(format!(
488
                "{} submodule {} imported as subrepos with Git pins",
489
                r.submodules,
490
                if r.submodules == 1 {
491
                    "entry"
492
                } else {
493
                    "entries"
494
                }
495
            ))
496
        );
30ea9c1e Andy McCall ↶ 497
    }
498
    Ok(0)
499
}
500
501
pub fn git_push(url: &str, branch: &str) -> Result<i32> {
502
    let repo = open()?;
503
    let sp = ui::spinner(&format!("Pushing to {url} {branch}…"));
504
    let r = repo.git_push(url, branch)?;
505
    sp.clear();
506
    println!(
507
        "{} {} to {} {} {}",
508
        ui::done("Pushed"),
509
        plural(r.exported, "new commit"),
510
        ui::path(url),
511
        ui::bookmark(&r.branch),
512
        ui::dim(format!("({} already there)", r.skipped))
513
    );
514
    Ok(0)
515
}
516
62794ecc Andy McCall ↶ 517
/// `oxy git verify`: exit 1 if any commit's tree is not reproduced.
7eac74ab Andy McCall ↶ 518
pub fn git_verify(git_dir: &std::path::Path, branch: &str, last: Option<usize>) -> Result<i32> {
62794ecc Andy McCall ↶ 519
    let repo = open()?;
520
    let started = std::time::Instant::now();
521
    let sp = ui::spinner(&format!(
522
        "Rebuilding every commit of {} {branch}…",
523
        git_dir.display()
524
    ));
7eac74ab Andy McCall ↶ 525
    let r = repo.verify_git_import_last(git_dir, branch, last)?;
62794ecc Andy McCall ↶ 526
    sp.clear();
527
    for (_, what) in &r.mismatches {
528
        println!("{} {what}", ui::err(ui::glyph("✖", "x")));
529
    }
530
    if r.mismatches.is_empty() {
531
        println!(
532
            "{}",
7eac74ab Andy McCall ↶ 533
            ui::done(if r.skipped > 0 {
534
                format!(
535
                    "The last {} commits reproduced ({} followed), {} files compared, in {:.1}s",
536
                    r.commits - r.skipped,
537
                    r.skipped,
538
                    r.files_compared,
539
                    started.elapsed().as_secs_f64()
540
                )
541
            } else {
542
                format!(
543
                    "Every commit reproduced: {} commits, {} files compared, in {:.1}s",
544
                    r.commits,
545
                    r.files_compared,
546
                    started.elapsed().as_secs_f64()
547
                )
548
            })
62794ecc Andy McCall ↶ 549
        );
550
        Ok(0)
551
    } else {
552
        println!(
553
            "{} differences in {} commits checked",
554
            r.mismatches.len(),
555
            r.commits
556
        );
557
        Ok(1)
558
    }
559
}
560
c3069537 Andy McCall ↶ 561
pub fn git_import(git_dir: &std::path::Path, dest: &std::path::Path, branch: &str) -> Result<i32> {
562
    let repo = Repo::init(dest)?;
563
    let started = std::time::Instant::now();
135212de Andy McCall ↶ 564
    let sp = ui::spinner(&format!("Importing {} {branch}…", git_dir.display()));
c3069537 Andy McCall ↶ 565
    let r = repo.import_git(git_dir, branch)?;
135212de Andy McCall ↶ 566
    sp.clear();
c3069537 Andy McCall ↶ 567
    println!(
94084087 Andy McCall ↶ 568
        "{} {} ({} merges) from {} {} into {} {}",
569
        ui::done("Imported"),
c3069537 Andy McCall ↶ 570
        plural(r.commits, "commit"),
571
        r.merges,
94084087 Andy McCall ↶ 572
        ui::path(git_dir.display()),
573
        ui::bookmark(branch),
574
        ui::path(repo.root().display()),
75167672 Andy McCall 575
        ui::dim(format!(
576
            "in {:.1?}; {} now has {}",
577
            started.elapsed(),
578
            repo.config.bookmark,
579
            plural(r.heads, "head")
580
        ))
c3069537 Andy McCall ↶ 581
    );
4dee277c Andy McCall ↶ 582
    if r.submodules > 0 {
75167672 Andy McCall 583
        println!(
584
            "  {} {}",
585
            ui::note(),
586
            ui::dim(format!(
587
                "{} submodule {} imported as subrepos with Git pins",
588
                r.submodules,
589
                if r.submodules == 1 {
590
                    "entry"
591
                } else {
592
                    "entries"
593
                }
594
            ))
595
        );
4dee277c Andy McCall ↶ 596
    }
597
    Ok(0)
598
}
599
600
pub fn submodule_add(url: &str, path: &str, bookmark: Option<&str>) -> Result<i32> {
601
    let repo = open()?;
602
    let sp = ui::spinner(&format!("Cloning {url} into {path}…"));
603
    let pin = repo.submodule_add(url, path, bookmark)?;
75167672 Andy McCall 604
    sp.done(&format!(
605
        "{} subrepo {} {} {}",
606
        ui::done("Added"),
607
        ui::path(path),
608
        ui::dim(ui::glyph("→", "->")),
609
        ui::dim(pin.summary())
610
    ));
611
    println!(
612
        "  {} {}",
613
        ui::note(),
614
        ui::dim("recorded in .oxymodules; commit to pin it")
615
    );
4dee277c Andy McCall ↶ 616
    Ok(0)
617
}
618
619
pub fn submodule_update(init: bool, paths: &[String]) -> Result<i32> {
620
    let repo = open()?;
621
    let sp = ui::spinner("Updating subrepos…");
622
    let results = repo.submodule_update(init, paths)?;
623
    sp.clear();
624
    if results.is_empty() {
625
        println!("{}", ui::dim("No subrepos."));
626
    }
627
    let mut code = 0;
628
    for (path, r) in results {
629
        use oxy_core::repo::SubrepoSync::*;
630
        let line = match r {
631
            Updated => ui::done("Updated"),
632
            UpToDate => ui::ok(format!("{} up to date", ui::glyph("✔", "*"))),
633
            Missing => {
634
                code = 1;
75167672 Andy McCall 635
                ui::warn(format!(
636
                    "{} missing (pass --init to clone)",
637
                    ui::glyph("⚠", "!")
638
                ))
4dee277c Andy McCall ↶ 639
            }
640
            Dirty => {
641
                code = 1;
75167672 Andy McCall 642
                ui::warn(format!(
643
                    "{} has uncommitted changes; left as is",
644
                    ui::glyph("⚠", "!")
645
                ))
4dee277c Andy McCall ↶ 646
            }
1a3b6203 Andy McCall ↶ 647
            KeptBookmark { bookmark, newer } => ui::warn(format!(
648
                "{} checked out at the pin; its bookmark {bookmark} keeps {} the pin lacks",
649
                ui::glyph("⚠", "!"),
650
                plural(newer, "newer change")
651
            )),
4dee277c Andy McCall ↶ 652
            Failed(e) => {
653
                code = 1;
654
                ui::err(format!("{} {e}", ui::glyph("✖", "x")))
655
            }
656
        };
657
        println!("{line} {}", ui::path(path));
658
    }
659
    Ok(code)
660
}
661
c6aa5bd9 Andy McCall ↶ 662
fn pin_json(p: &oxy_core::subrepo::Pin) -> String {
663
    match p {
75167672 Andy McCall 664
        oxy_core::subrepo::Pin::Oxy {
665
            repo,
666
            heads,
667
            bookmark,
668
        } => json::obj([
669
            ("kind", json::s("oxy")),
670
            (
671
                "repo",
672
                json::s(&repo.iter().map(|b| format!("{b:02x}")).collect::<String>()),
673
            ),
674
            ("heads", json::hashes(heads)),
675
            ("bookmark", json::s(bookmark)),
676
        ]),
677
        oxy_core::subrepo::Pin::Git { sha, branch } => json::obj([
678
            ("kind", json::s("git")),
679
            ("sha", json::s(sha)),
680
            ("branch", json::s(branch)),
681
        ]),
c6aa5bd9 Andy McCall ↶ 682
    }
683
}
684
685
pub fn submodule_status(as_json: bool) -> Result<i32> {
4dee277c Andy McCall ↶ 686
    let repo = open()?;
687
    let subs = repo.subrepos()?;
c6aa5bd9 Andy McCall ↶ 688
    if as_json {
689
        println!(
690
            "{}",
691
            json::arr(subs.iter().map(|s| {
692
                json::obj([
693
                    ("path", json::s(&s.path)),
694
                    ("pin", pin_json(&s.pin)),
695
                    ("actual", json::opt(s.actual.as_ref(), pin_json)),
696
                    ("at_pin", json::b(s.actual.as_ref() == Some(&s.pin))),
697
                    ("dirty", json::b(s.dirty)),
e7ac6c2e Andy McCall ↶ 698
                    ("committed", json::b(s.committed)),
c6aa5bd9 Andy McCall ↶ 699
                    ("url", json::opt(s.url.as_deref(), json::s)),
700
                ])
701
            }))
702
        );
703
        return Ok(0);
704
    }
4dee277c Andy McCall ↶ 705
    if subs.is_empty() {
706
        println!("{}", ui::dim("No subrepos."));
94084087 Andy McCall ↶ 707
    }
4dee277c Andy McCall ↶ 708
    for s in subs {
709
        let state = match (&s.actual, s.dirty) {
e7ac6c2e Andy McCall ↶ 710
            _ if !s.committed => {
711
                ui::warn(format!("{} added, not committed yet", ui::glyph("+", "+")))
712
            }
4dee277c Andy McCall ↶ 713
            (None, _) => ui::warn(format!("{} missing", ui::glyph("⚠", "!"))),
714
            (Some(a), dirty) if *a == s.pin => {
75167672 Andy McCall 715
                if dirty {
716
                    ui::warn(format!(
717
                        "{} at pin, uncommitted changes",
718
                        ui::glyph("✎", "~")
719
                    ))
720
                } else {
721
                    ui::ok(format!("{} at pin", ui::glyph("✔", "*")))
722
                }
4dee277c Andy McCall ↶ 723
            }
724
            (Some(a), _) => ui::warn(format!("{} at {}", ui::glyph("↕", "<>"), a.summary())),
725
        };
75167672 Andy McCall 726
        println!(
727
            "{} {}{}{}{}{state}",
728
            ui::ok(ui::glyph("⧉", "#")),
729
            ui::path(&s.path),
730
            ui::sep(),
731
            ui::dim(s.pin.summary()),
732
            ui::sep()
733
        );
4dee277c Andy McCall ↶ 734
        if let Some(u) = s.url {
735
            println!("    {} {}", ui::dim(ui::glyph("↳", "->")), ui::dim(u));
736
        }
737
    }
738
    Ok(0)
739
}
740
741
pub fn submodule_remove(path: &str) -> Result<i32> {
742
    let repo = open()?;
743
    repo.submodule_remove(path)?;
75167672 Andy McCall 744
    println!(
745
        "{} subrepo {} {}",
746
        ui::done("Removed"),
747
        ui::path(path),
748
        ui::dim("(directory left in place; commit to record the removal)")
749
    );
c3069537 Andy McCall ↶ 750
    Ok(0)
751
}
2863456a Andy McCall ↶ 752
753
pub fn deepen(remote: &str, depth: u32) -> Result<i32> {
754
    let repo = open()?;
755
    if !repo.is_shallow() {
75167672 Andy McCall 756
        println!(
757
            "{}",
758
            ui::dim("This repository is not shallow; nothing to deepen.")
759
        );
2863456a Andy McCall ↶ 760
        return Ok(0);
761
    }
762
    let sp = ui::spinner(&format!("Fetching {depth} more levels from {remote}…"));
763
    let n = repo.deepen(remote, depth)?;
75167672 Andy McCall 764
    sp.done(&format!(
765
        "{} {}; {}",
766
        ui::ok("Deepened by"),
767
        plural(n, "change"),
768
        if repo.is_shallow() {
769
            "still shallow".to_string()
770
        } else {
771
            ui::ok("history is now complete")
772
        }
773
    ));
2863456a Andy McCall ↶ 774
    Ok(0)
775
}