OXYGENHUB
# 01a47cd7f0c8 oxygen / src / cli / workspace.rs
56.2 KiB · Rust · last changed Log, blame and fsck at the scale of the Linux tree 1 month ago source blame history raw
fce44ae9 Andy McCall ↶ 1
//! Commands that act on the local repository and working copy.
2
75167672 Andy McCall 3
use super::format::{
4
    author_name, deps_line, deps_of, plural, short_id, short_meta_id, signature_line,
5
    signature_mark, subject_of, when,
6
};
c6aa5bd9 Andy McCall ↶ 7
use super::json;
fce44ae9 Andy McCall ↶ 8
use super::open;
135212de Andy McCall ↶ 9
use super::ui;
fce44ae9 Andy McCall ↶ 10
use anyhow::Result;
94084087 Andy McCall ↶ 11
use oxy_core::objects::ChangeKind;
75167672 Andy McCall 12
use oxy_core::repo::SignatureStatus;
fce44ae9 Andy McCall ↶ 13
use oxy_core::repo::{render_change, ChangeStatus, Repo};
14
use std::path::PathBuf;
15
e02bf0cd Andy McCall ↶ 16
pub fn init(path: Option<PathBuf>, bare: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 17
    let path = path.unwrap_or(std::env::current_dir()?);
75167672 Andy McCall 18
    let repo = if bare {
19
        Repo::init_bare(&path)?
20
    } else {
21
        Repo::init(&path)?
22
    };
23
    println!(
24
        "{} {}oxy repository in {}",
25
        ui::done("Initialized"),
26
        if bare { "bare " } else { "" },
27
        ui::path(repo.root().display())
28
    );
29
    println!(
30
        "{}",
31
        ui::kv("bookmark", ui::bookmark(&repo.config.bookmark))
32
    );
33
    println!(
34
        "{}",
35
        ui::kv(
36
            "author",
37
            format!(
38
                "{} <{}>",
39
                ui::author(&repo.config.author_name),
40
                repo.config.author_email
41
            )
42
        )
43
    );
fce44ae9 Andy McCall ↶ 44
    Ok(0)
45
}
46
47
fn status_tag(s: ChangeStatus) -> &'static str {
48
    match s {
49
        ChangeStatus::Added => "A",
50
        ChangeStatus::Modified => "M",
51
        ChangeStatus::Removed => "D",
6e723b81 Andy McCall ↶ 52
        ChangeStatus::Renamed => "R",
fce44ae9 Andy McCall ↶ 53
        ChangeStatus::ModeChanged => "X",
54
        ChangeStatus::ConflictEdited => "C!",
6e723b81 Andy McCall ↶ 55
        ChangeStatus::Resolved => "V",
fce44ae9 Andy McCall ↶ 56
    }
57
}
58
50a046e4 Andy McCall ↶ 59
pub fn status(json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 60
    let repo = open()?;
135212de Andy McCall ↶ 61
    let sp = ui::spinner("Snapshotting the working copy…");
cc7a0056 Andy McCall ↶ 62
    let snap = repo.snapshot_status("oxy status")?;
fce44ae9 Andy McCall ↶ 63
    let heads = repo.bookmark_heads()?;
135212de Andy McCall ↶ 64
    sp.clear();
50a046e4 Andy McCall ↶ 65
    if json {
66
        println!("{}", repo.status_json(&snap)?);
75167672 Andy McCall 67
        return Ok(if snap.base_snapshot.is_conflicted() {
68
            2
69
        } else {
70
            0
71
        });
50a046e4 Andy McCall ↶ 72
    }
135212de Andy McCall ↶ 73
    println!(
94084087 Andy McCall ↶ 74
        "{} {}{}working copy {}{}{}",
75
        ui::dim("On"),
76
        ui::bookmark(&repo.config.bookmark),
77
        ui::sep(),
135212de Andy McCall ↶ 78
        ui::id(snap.wc.change_id.short(8)),
94084087 Andy McCall ↶ 79
        ui::sep(),
80
        ui::dim(plural(heads.len(), "head"))
135212de Andy McCall ↶ 81
    );
fce44ae9 Andy McCall ↶ 82
    if snap.statuses.is_empty() {
75167672 Andy McCall 83
        println!(
84
            "  {} {}",
85
            ui::ok(ui::glyph("✔", "*")),
86
            ui::dim("nothing to commit, working copy clean")
87
        );
94084087 Andy McCall ↶ 88
    } else {
89
        println!();
90
        for s in &snap.statuses {
75167672 Andy McCall 91
            println!(
92
                "  {} {}",
93
                ui::status_mark(status_tag(s.status)),
94
                ui::path(&s.path)
95
            );
94084087 Andy McCall ↶ 96
        }
fce44ae9 Andy McCall ↶ 97
    }
98
    if !snap.base_snapshot.is_conflicted() {
99
        return Ok(0);
100
    }
135212de Andy McCall ↶ 101
    println!();
75167672 Andy McCall 102
    println!(
103
        "{} {}",
104
        ui::section(ui::err("Conflicts")),
105
        ui::dim("edit the marked files, or the .oxy-conflict-N candidates, then commit")
106
    );
fce44ae9 Andy McCall ↶ 107
    for c in &snap.base_snapshot.tree.conflicts {
94084087 Andy McCall ↶ 108
        println!("  {} tree: {c:?}", ui::err(ui::glyph("✱", "!")));
fce44ae9 Andy McCall ↶ 109
    }
110
    for (p, f) in &snap.base_snapshot.files {
111
        if f.is_conflicted() {
75167672 Andy McCall 112
            let state = match snap
113
                .statuses
114
                .iter()
115
                .find(|s| s.path == *p)
116
                .map(|s| s.status)
117
            {
118
                Some(ChangeStatus::Resolved) => {
119
                    ui::ok(format!("{} resolved in working copy", ui::glyph("✔", "*")))
120
                }
121
                Some(ChangeStatus::ConflictEdited) => {
122
                    ui::warn(format!("{} markers remain", ui::glyph("‼", "!")))
123
                }
94084087 Andy McCall ↶ 124
                _ => ui::err(format!("{} unresolved", ui::glyph("✱", "!"))),
fce44ae9 Andy McCall ↶ 125
            };
135212de Andy McCall ↶ 126
            println!("  {}  {state}", ui::path(p));
fce44ae9 Andy McCall ↶ 127
        }
128
    }
129
    Ok(2)
130
}
131
75167672 Andy McCall 132
pub fn commit(
133
    message: &str,
134
    depends_on: &[String],
135
    paths: &[String],
136
    interactive: bool,
137
    hunks: &[usize],
138
) -> Result<i32> {
fce44ae9 Andy McCall ↶ 139
    let repo = open()?;
140
    let mut deps = Vec::new();
141
    for d in depends_on {
142
        deps.push(repo.resolve_change(d)?);
143
    }
c6aa5bd9 Andy McCall ↶ 144
    let selection = if !hunks.is_empty() {
145
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
146
    } else if interactive {
957fee30 Andy McCall ↶ 147
        let (_, hunks) = repo.hunks()?;
148
        if hunks.is_empty() {
149
            anyhow::bail!("nothing to commit: the working copy matches its base");
150
        }
75167672 Andy McCall 151
        let hunks: Vec<_> = hunks
152
            .into_iter()
153
            .filter(|h| {
154
                paths.is_empty()
155
                    || paths.iter().any(|p| {
156
                        h.path == *p || h.path.starts_with(&format!("{}/", p.trim_end_matches('/')))
157
                    })
158
            })
159
            .collect();
957fee30 Andy McCall ↶ 160
        let mut chosen = Vec::new();
161
        let stdin = std::io::stdin();
162
        let mut take_rest = false;
163
        for (n, h) in hunks.iter().enumerate() {
164
            if take_rest {
165
                chosen.push(h.index);
166
                continue;
167
            }
75167672 Andy McCall 168
            println!(
169
                "{} {} {}",
170
                ui::section(format!("hunk {} of {}", n + 1, hunks.len())),
171
                ui::path(&h.path),
172
                ui::dim(format!("(#{})", h.index))
173
            );
957fee30 Andy McCall ↶ 174
            for line in h.text.lines() {
75167672 Andy McCall 175
                let styled = if line.starts_with('+') {
176
                    ui::ok(line)
177
                } else if line.starts_with('-') {
178
                    ui::err(line)
179
                } else {
180
                    ui::dim(line)
181
                };
957fee30 Andy McCall ↶ 182
                println!("  {styled}");
183
            }
184
            loop {
75167672 Andy McCall 185
                print!(
186
                    "{} ",
187
                    ui::warn("Commit this hunk? [y]es [n]o [a]ll remaining [q]uit:")
188
                );
957fee30 Andy McCall ↶ 189
                use std::io::Write as _;
190
                std::io::stdout().flush()?;
191
                let mut answer = String::new();
192
                if stdin.read_line(&mut answer)? == 0 {
193
                    anyhow::bail!("aborted");
194
                }
195
                match answer.trim() {
196
                    "y" | "Y" => {
197
                        chosen.push(h.index);
198
                        break;
199
                    }
200
                    "n" | "N" | "" => break,
201
                    "a" | "A" => {
202
                        chosen.push(h.index);
203
                        take_rest = true;
204
                        break;
205
                    }
206
                    "q" | "Q" => anyhow::bail!("aborted; nothing committed"),
207
                    _ => continue,
208
                }
209
            }
210
        }
211
        if chosen.is_empty() {
212
            anyhow::bail!("no hunks chosen; nothing committed");
213
        }
214
        oxy_core::repo::Selection::Hunks(chosen)
215
    } else if paths.is_empty() {
216
        oxy_core::repo::Selection::All
217
    } else {
218
        oxy_core::repo::Selection::Paths(paths.to_vec())
219
    };
135212de Andy McCall ↶ 220
    let sp = ui::spinner("Committing…");
957fee30 Andy McCall ↶ 221
    let h = repo.commit_selection(message, &deps, &selection)?;
fce44ae9 Andy McCall ↶ 222
    let c = repo.store().get_change(&h)?;
75167672 Andy McCall 223
    sp.done(&format!(
224
        "{} {} {}  {}",
225
        ui::done("Committed"),
226
        ui::id(short_id(&c)),
227
        ui::hash(format!("#{}", h.short(12))),
228
        ui::subject(subject_of(message))
229
    ));
957fee30 Andy McCall ↶ 230
    if !matches!(selection, oxy_core::repo::Selection::All) {
8ab265dc Andy McCall ↶ 231
        let rest = repo.snapshot_status("oxy commit")?;
957fee30 Andy McCall ↶ 232
        if !rest.statuses.is_empty() {
75167672 Andy McCall 233
            println!(
234
                "  {} {}",
235
                ui::note(),
236
                ui::dim(format!(
237
                    "{} left uncommitted",
238
                    plural(rest.statuses.len(), "path")
239
                ))
240
            );
957fee30 Andy McCall ↶ 241
        }
242
    }
243
    Ok(0)
244
}
245
246
pub fn blame(path: &str, json: bool) -> Result<i32> {
247
    let repo = open()?;
248
    let lines = repo.blame(path)?;
249
    if json {
250
        let items = lines.iter().map(|l| {
251
            format!(
252
                "{{\"line\":{},\"change_id\":{},\"hash\":{},\"index\":{},\"author\":{},\"when_ms\":{}}}",
253
                l.line,
254
                oxy_core::repo::json_str(&l.change_id.to_hex()),
255
                oxy_core::repo::json_str(&l.hash.to_hex()),
256
                l.index,
257
                oxy_core::repo::json_str(&l.author),
258
                l.when_ms
259
            )
260
        });
261
        println!("{}", oxy_core::repo::json_array(items));
262
        return Ok(0);
263
    }
75167672 Andy McCall 264
    let width = lines
265
        .iter()
266
        .map(|l| l.author.chars().count())
267
        .max()
268
        .unwrap_or(0)
269
        .min(20);
957fee30 Andy McCall ↶ 270
    let digits = lines.len().to_string().len();
271
    for l in &lines {
272
        let author: String = l.author.chars().take(20).collect();
273
        let text = String::from_utf8_lossy(&l.text);
274
        println!(
275
            "{} {} {} {:>digits$}{} {}",
276
            ui::id(l.change_id.short(8)),
277
            ui::author(format!("{author:<width$}")),
278
            ui::dim(ui::ago(l.when_ms)),
279
            l.line,
280
            ui::dim(ui::glyph("│", "|")),
281
            text.trim_end_matches('\n')
282
        );
283
    }
284
    Ok(0)
285
}
286
287
fn bisect_report(repo: &Repo, step: &oxy_core::repo::BisectStep) -> Result<i32> {
288
    use oxy_core::repo::BisectStep::*;
289
    match step {
290
        NeedMarks { good, bad } => {
75167672 Andy McCall 291
            println!(
292
                "{} {} {}",
293
                ui::note(),
294
                ui::dim(format!("{good} good, {bad} bad;")),
295
                ui::dim(if *good == 0 {
296
                    "mark a known-good change or bookmark: oxy bisect good CHANGE"
297
                } else {
298
                    "mark a known-bad change or bookmark: oxy bisect bad CHANGE"
299
                })
300
            );
957fee30 Andy McCall ↶ 301
            Ok(0)
302
        }
75167672 Andy McCall 303
        Testing {
304
            heads,
305
            remaining,
306
            steps_left,
307
        } => {
308
            println!(
309
                "{} {} {}",
310
                ui::done("Testing"),
311
                ui::dim(format!(
312
                    "{} in the state under test;",
313
                    plural(heads.len(), "head")
314
                )),
315
                ui::dim(format!(
316
                    "{remaining} candidates left, about {steps_left} more steps"
317
                ))
318
            );
319
            println!(
320
                "  {} {}",
321
                ui::note(),
322
                ui::dim("run your test, then oxy bisect good | bad | skip")
323
            );
957fee30 Andy McCall ↶ 324
            Ok(0)
325
        }
326
        Found { culprit } => {
327
            let c = repo.store().get_change(culprit)?;
75167672 Andy McCall 328
            println!(
329
                "{} {} {}  {}",
330
                ui::done("Found"),
331
                ui::id(short_id(&c)),
332
                ui::hash(format!("#{}", culprit.short(12))),
333
                ui::subject(subject_of(&c.message))
334
            );
957fee30 Andy McCall ↶ 335
            println!("  {} {}", ui::note(), ui::dim("the first change whose inclusion makes the state bad; oxy bisect reset to return"));
336
            Ok(0)
337
        }
338
        Inconclusive { candidates } => {
75167672 Andy McCall 339
            println!(
340
                "{} {}",
341
                ui::caution(),
342
                ui::warn(format!(
343
                    "every remaining candidate was skipped ({}); oxy bisect reset to return",
344
                    plural(candidates.len(), "change")
345
                ))
346
            );
957fee30 Andy McCall ↶ 347
            Ok(1)
348
        }
349
    }
350
}
351
352
pub fn bisect_start() -> Result<i32> {
353
    let repo = open()?;
354
    repo.bisect_start()?;
75167672 Andy McCall 355
    println!(
356
        "{} bisect; {}",
357
        ui::done("Started"),
358
        ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE")
359
    );
957fee30 Andy McCall ↶ 360
    Ok(0)
361
}
362
363
pub fn bisect_mark(good: Option<bool>, changes: &[String]) -> Result<i32> {
364
    let repo = open()?;
365
    let mut heads = Vec::new();
366
    for c in changes {
367
        heads.extend(repo.resolve_heads(c)?);
368
    }
369
    let step = repo.bisect_mark(good, &heads)?;
370
    bisect_report(&repo, &step)
371
}
372
373
pub fn bisect_run(command: &[String]) -> Result<i32> {
374
    let repo = open()?;
375
    let step = repo.bisect_run(command)?;
376
    bisect_report(&repo, &step)
377
}
378
c6aa5bd9 Andy McCall ↶ 379
pub fn bisect_status(as_json: bool) -> Result<i32> {
957fee30 Andy McCall ↶ 380
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 381
    if as_json {
382
        use oxy_core::repo::BisectStep::*;
383
        let v = match repo.bisect_status()? {
384
            None => "null".to_string(),
75167672 Andy McCall 385
            Some(NeedMarks { good, bad }) => json::obj([
386
                ("state", json::s("need-marks")),
387
                ("good", json::n(good)),
388
                ("bad", json::n(bad)),
389
            ]),
390
            Some(Testing {
391
                heads,
392
                remaining,
393
                steps_left,
394
            }) => json::obj([
395
                ("state", json::s("testing")),
396
                ("heads", json::hashes(&heads)),
397
                ("remaining", json::n(remaining)),
398
                ("steps_left", json::n(steps_left)),
399
            ]),
400
            Some(Found { culprit }) => json::obj([
401
                ("state", json::s("found")),
402
                ("culprit", json::s(&culprit.to_hex())),
403
            ]),
404
            Some(Inconclusive { candidates }) => json::obj([
405
                ("state", json::s("inconclusive")),
406
                ("candidates", json::hashes(&candidates)),
407
            ]),
c6aa5bd9 Andy McCall ↶ 408
        };
409
        println!("{v}");
410
        return Ok(0);
411
    }
957fee30 Andy McCall ↶ 412
    match repo.bisect_status()? {
413
        None => {
414
            println!("{}", ui::dim("No bisect in progress."));
415
            Ok(0)
416
        }
417
        Some(step) => bisect_report(&repo, &step),
418
    }
419
}
420
421
pub fn bisect_reset() -> Result<i32> {
422
    let repo = open()?;
423
    repo.bisect_reset()?;
424
    println!("{} bisect; working copy restored", ui::done("Reset"));
fce44ae9 Andy McCall ↶ 425
    Ok(0)
426
}
427
94084087 Andy McCall ↶ 428
/// The log: one entry per change, newest first, joined by a rail. The
429
/// default view is the subject and a metadata line; `verbose` adds the full
430
/// message, dependencies, and the authenticating key.
c6aa5bd9 Andy McCall ↶ 431
fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
432
    Ok(match repo.authenticate_change(h)? {
433
        SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]),
75167672 Andy McCall 434
        SignatureStatus::Valid {
435
            key,
436
            name,
437
            email,
438
            sealed,
439
            revoked,
440
        } => json::obj([
c6aa5bd9 Andy McCall ↶ 441
            ("status", json::s(if sealed { "sealed" } else { "signed" })),
442
            ("key", json::s(&key.to_hex())),
443
            ("name", json::s(&name)),
444
            ("email", json::s(&email)),
445
            ("revoked", json::b(revoked)),
446
        ]),
75167672 Andy McCall 447
        SignatureStatus::Invalid(why) => {
448
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
449
        }
c6aa5bd9 Andy McCall ↶ 450
    })
451
}
452
453
fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result<String> {
454
    let c = &e.change;
455
    Ok(json::obj([
456
        ("hash", json::s(&e.hash.to_hex())),
457
        ("change_id", json::s(&c.change_id.to_hex())),
458
        ("author", json::s(&author_name(repo, c))),
459
        ("author_key", json::s(&c.author.to_hex())),
460
        ("when_ms", json::n(c.hlc.wall_ms)),
461
        ("message", json::s(&c.message)),
462
        ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())),
463
        ("deps", json::hashes(&c.deps)),
464
        ("head", json::b(e.is_head)),
465
        ("working_copy", json::b(e.is_working_copy)),
75167672 Andy McCall 466
        (
467
            "signature",
468
            if e.is_working_copy {
469
                "null".into()
470
            } else {
471
                signature_json(repo, &e.hash)?
472
            },
473
        ),
c6aa5bd9 Andy McCall ↶ 474
    ]))
475
}
476
83d61e80 Andy McCall ↶ 477
/// `START,END:PATH` for `oxy log -L`.
478
fn parse_line_range(spec: &str) -> Result<(usize, usize, &str)> {
479
    let bad = || anyhow::anyhow!("-L {spec}: expected START,END:PATH, as 10,24:src/lib.rs");
480
    let (range, path) = spec.split_once(':').ok_or_else(bad)?;
481
    let (a, b) = range.split_once(',').ok_or_else(bad)?;
482
    Ok((
483
        a.trim().parse().map_err(|_| bad())?,
484
        b.trim().parse().map_err(|_| bad())?,
485
        path,
486
    ))
487
}
488
489
pub fn log(
490
    limit: Option<usize>,
491
    verbose: bool,
492
    path: Option<&str>,
493
    lines: Option<&str>,
494
    as_json: bool,
495
) -> Result<i32> {
fce44ae9 Andy McCall ↶ 496
    let repo = open()?;
69816d68 Andy McCall ↶ 497
    // Whether the working copy is clean and conflicted: from the manifest
498
    // when it proves the working copy clean, else from a snapshot.
499
    let (conflicted, clean) = if repo.clean_by_manifest()? {
500
        (false, true)
501
    } else {
502
        let snap = repo.snapshot_status("oxy log")?;
503
        (snap.base_snapshot.is_conflicted(), snap.statuses.is_empty())
504
    };
83d61e80 Andy McCall ↶ 505
    let entries = match (path, lines) {
506
        (_, Some(spec)) => {
507
            let (first, last, p) = parse_line_range(spec)?;
69816d68 Andy McCall ↶ 508
            let (_, wc) = repo.working_copy()?;
509
            let base = repo.load_state_history(&wc.deps)?.maximal(&wc.deps);
510
            repo.line_history(&base, p, first, last)?
83d61e80 Andy McCall ↶ 511
        }
512
        (Some(p), None) => repo.log_for_path(p)?,
513
        (None, None) => repo.log()?,
c6aa5bd9 Andy McCall ↶ 514
    };
515
    if as_json {
516
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
517
        let mut items = Vec::new();
518
        for e in entries.iter().take(shown) {
519
            items.push(log_entry_json(&repo, e)?);
520
        }
75167672 Andy McCall 521
        println!(
522
            "{}",
523
            json::obj([
524
                ("bookmark", json::s(&repo.config.bookmark)),
525
                ("total", json::n(entries.len())),
526
                ("changes", json::arr(items))
527
            ])
528
        );
c6aa5bd9 Andy McCall ↶ 529
        return Ok(0);
530
    }
94084087 Andy McCall ↶ 531
    let total = entries.len();
532
    let shown = limit.unwrap_or(total).min(total);
533
    let rail = ui::rail();
534
    for (i, e) in entries.iter().take(shown).enumerate() {
fce44ae9 Andy McCall ↶ 535
        let c = &e.change;
75167672 Andy McCall 536
        let bullet = ui::log_bullet(
537
            e.is_working_copy,
538
            e.is_head,
539
            e.is_working_copy && conflicted,
540
        );
94084087 Andy McCall ↶ 541
        let mut labels = Vec::new();
fce44ae9 Andy McCall ↶ 542
        if e.is_working_copy {
94084087 Andy McCall ↶ 543
            labels.push(ui::warn("working copy"));
fce44ae9 Andy McCall ↶ 544
        }
94084087 Andy McCall ↶ 545
        if c.kind == ChangeKind::Resolution {
546
            labels.push(ui::warn("resolution"));
fce44ae9 Andy McCall ↶ 547
        }
75167672 Andy McCall 548
        let labels = if labels.is_empty() {
549
            String::new()
550
        } else {
551
            format!(
552
                " {}{}{}",
553
                ui::dim("("),
554
                labels.join(ui::dim(", ").as_str()),
555
                ui::dim(")")
556
            )
557
        };
94084087 Andy McCall ↶ 558
        let subject = if e.is_working_copy && c.message.is_empty() {
69816d68 Andy McCall ↶ 559
            ui::dim(if clean {
75167672 Andy McCall 560
                "(clean)"
561
            } else {
562
                "(uncommitted changes)"
563
            })
94084087 Andy McCall ↶ 564
        } else {
565
            ui::subject(subject_of(&c.message))
566
        };
567
        println!("{bullet} {}{labels}  {subject}", ui::id(short_meta_id(c)));
568
        let meta = format!(
569
            "{}{}{}{}{}{}{}",
570
            ui::hash(format!("#{}", e.hash.short(12))),
571
            ui::sep(),
572
            ui::author(author_name(&repo, c)),
573
            ui::sep(),
574
            ui::dim(ui::ago(c.hlc.wall_ms)),
575
            ui::sep(),
75167672 Andy McCall 576
            if e.is_working_copy {
577
                ui::dim("not yet committed")
578
            } else {
579
                signature_mark(&repo, &e.hash)?
580
            }
94084087 Andy McCall ↶ 581
        );
582
        println!("{rail} {meta}");
583
        if verbose {
584
            if !e.is_working_copy {
75167672 Andy McCall 585
                println!(
586
                    "{rail} {}",
587
                    ui::dim(format!(
588
                        "{} {}",
589
                        when(c.hlc.wall_ms),
590
                        signature_line(&repo, &e.hash)?
591
                    ))
592
                );
94084087 Andy McCall ↶ 593
            }
594
            if !c.deps.is_empty() {
75167672 Andy McCall 595
                println!(
596
                    "{rail} {} {}",
597
                    ui::dim(ui::glyph("↳", "->")),
598
                    ui::dim(deps_of(&c.deps))
599
                );
94084087 Andy McCall ↶ 600
            }
75167672 Andy McCall 601
            let body: Vec<&str> = c
602
                .message
603
                .lines()
604
                .skip(1)
605
                .skip_while(|l| l.trim().is_empty())
606
                .collect();
94084087 Andy McCall ↶ 607
            if !body.is_empty() {
608
                println!("{rail}");
609
                for line in body {
610
                    println!("{rail}   {line}");
611
                }
612
            }
fce44ae9 Andy McCall ↶ 613
        }
94084087 Andy McCall ↶ 614
        if i + 1 < shown {
615
            println!("{rail}");
fce44ae9 Andy McCall ↶ 616
        }
617
    }
94084087 Andy McCall ↶ 618
    if shown < total {
75167672 Andy McCall 619
        println!(
620
            "{}",
621
            ui::dim(format!(
622
                "{} {} more; pass -n to see them",
623
                ui::glyph("…", "..."),
624
                total - shown
625
            ))
626
        );
94084087 Andy McCall ↶ 627
    }
fce44ae9 Andy McCall ↶ 628
    Ok(0)
629
}
630
c6aa5bd9 Andy McCall ↶ 631
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
632
    let repo = open()?;
633
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
634
    if as_json {
635
        let files = repo.diff_files(hash.as_ref())?;
636
        let items = files.iter().map(|f| {
637
            json::obj([
638
                ("path", json::s(&f.path)),
639
                ("kind", json::s(&f.kind)),
640
                ("from", json::opt(f.from.as_deref(), json::s)),
641
                (
642
                    "hunks",
643
                    json::arr(f.hunks.iter().map(|h| {
644
                        json::obj([
645
                            ("base_line", json::n(h.base_line)),
75167672 Andy McCall 646
                            (
647
                                "added",
648
                                json::arr(
649
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
650
                                ),
651
                            ),
652
                            (
653
                                "removed",
654
                                json::arr(h.removed.iter().map(|(n, l)| {
655
                                    json::obj([
656
                                        ("line", json::n(*n)),
657
                                        ("text", json::s(&String::from_utf8_lossy(l))),
658
                                    ])
659
                                })),
660
                            ),
c6aa5bd9 Andy McCall ↶ 661
                        ])
662
                    })),
663
                ),
664
            ])
665
        });
75167672 Andy McCall 666
        println!(
667
            "{}",
668
            json::obj([
669
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
670
                ("files", json::arr(items))
671
            ])
672
        );
c6aa5bd9 Andy McCall ↶ 673
        return Ok(0);
674
    }
675
    match hash {
676
        Some(h) => {
677
            let c = repo.store().get_change(&h)?;
8ab265dc Andy McCall ↶ 678
            let (base, snapshot) = repo.change_base(&c)?;
c6aa5bd9 Andy McCall ↶ 679
            print!("{}", render_change(&c, &base, &snapshot));
680
        }
681
        None => {
8ab265dc Andy McCall ↶ 682
            let snap = repo.snapshot_status("oxy diff")?;
75167672 Andy McCall 683
            print!(
684
                "{}",
685
                render_change(&snap.wc, &snap.base, &snap.base_snapshot)
686
            );
c6aa5bd9 Andy McCall ↶ 687
        }
688
    }
689
    Ok(0)
690
}
691
692
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
693
    let repo = open()?;
694
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
695
    let bytes = repo.file_at(path, heads.as_deref())?;
696
    use std::io::Write as _;
697
    std::io::stdout().write_all(&bytes)?;
698
    Ok(0)
699
}
700
701
pub fn root(as_json: bool) -> Result<i32> {
702
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
703
        if as_json {
704
            println!("null");
705
        }
706
        return Ok(1);
707
    };
708
    if as_json {
75167672 Andy McCall 709
        println!(
710
            "{}",
711
            json::obj([
712
                ("root", json::s(&repo.root().to_string_lossy())),
713
                ("workspace", json::s(&repo.workspace().to_hex())),
714
                ("bookmark", json::s(&repo.config.bookmark))
715
            ])
716
        );
c6aa5bd9 Andy McCall ↶ 717
    } else {
718
        println!("{}", repo.root().display());
719
    }
720
    Ok(0)
721
}
722
723
pub fn version(as_json: bool) -> Result<i32> {
724
    if as_json {
75167672 Andy McCall 725
        println!(
726
            "{}",
727
            json::obj([
728
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
729
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
730
                ("format", json::n(2))
731
            ])
732
        );
c6aa5bd9 Andy McCall ↶ 733
    } else {
75167672 Andy McCall 734
        println!(
735
            "oxy {} (repository format 2, protocol {})",
736
            env!("CARGO_PKG_VERSION"),
737
            oxy_core::protocol::PROTOCOL_VERSION
738
        );
c6aa5bd9 Andy McCall ↶ 739
    }
740
    Ok(0)
741
}
742
743
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
744
    let repo = open()?;
745
    if paths.is_empty() && hunks.is_empty() {
746
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
747
    }
748
    let mut n = 0;
749
    if !hunks.is_empty() {
750
        n += repo.discard_hunks(hunks)?;
751
    }
752
    if !paths.is_empty() {
753
        n += repo.discard(paths)?;
754
    }
75167672 Andy McCall 755
    println!(
756
        "{} {} restored to the working copy's base",
757
        ui::done("Discarded"),
758
        plural(n, "path")
759
    );
c6aa5bd9 Andy McCall ↶ 760
    Ok(0)
761
}
762
763
pub fn hunks(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 764
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 765
    let (_, hunks) = repo.hunks()?;
766
    if as_json {
75167672 Andy McCall 767
        println!(
768
            "{}",
769
            json::arr(hunks.iter().map(|h| json::obj([
770
                ("index", json::n(h.index)),
771
                ("path", json::s(&h.path)),
772
                ("text", json::s(&h.text))
773
            ])))
774
        );
c6aa5bd9 Andy McCall ↶ 775
        return Ok(0);
776
    }
777
    if hunks.is_empty() {
75167672 Andy McCall 778
        println!(
779
            "{}",
780
            ui::dim("No hunks: the working copy matches its base.")
781
        );
c6aa5bd9 Andy McCall ↶ 782
    }
783
    for h in &hunks {
75167672 Andy McCall 784
        println!(
785
            "{} {}",
786
            ui::section(format!("hunk {}", h.index)),
787
            ui::path(&h.path)
788
        );
c6aa5bd9 Andy McCall ↶ 789
        for line in h.text.lines() {
75167672 Andy McCall 790
            let styled = if line.starts_with('+') {
791
                ui::ok(line)
792
            } else if line.starts_with('-') {
793
                ui::err(line)
794
            } else {
795
                ui::dim(line)
796
            };
c6aa5bd9 Andy McCall ↶ 797
            println!("  {styled}");
798
        }
799
    }
fce44ae9 Andy McCall ↶ 800
    Ok(0)
801
}
802
c6aa5bd9 Andy McCall ↶ 803
pub fn show(change: &str, as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 804
    let repo = open()?;
cc7a0056 Andy McCall ↶ 805
    repo.snapshot_status("oxy show")?;
fce44ae9 Andy McCall ↶ 806
    let h = repo.resolve_change(change)?;
807
    let c = repo.store().get_change(&h)?;
c6aa5bd9 Andy McCall ↶ 808
    if as_json {
809
        let files = repo.diff_files(Some(&h))?;
810
        let heads = repo.bookmark_heads()?;
75167672 Andy McCall 811
        let entry = oxy_core::repo::LogEntry {
812
            hash: h,
813
            change: oxy_core::state::ChangeMeta::of(&c),
814
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
815
            is_head: heads.contains(&h),
816
        };
c6aa5bd9 Andy McCall ↶ 817
        let mut body = log_entry_json(&repo, &entry)?;
818
        body.pop();
75167672 Andy McCall 819
        body.push_str(&format!(
820
            ",{}:{}}}",
821
            json::s("files"),
822
            json::arr(files.iter().map(|f| json::obj([
823
                ("path", json::s(&f.path)),
824
                ("kind", json::s(&f.kind)),
825
                ("from", json::opt(f.from.as_deref(), json::s))
826
            ])))
827
        ));
c6aa5bd9 Andy McCall ↶ 828
        println!("{body}");
829
        return Ok(0);
830
    }
75167672 Andy McCall 831
    println!(
832
        "{} {} {}",
833
        ui::section("change"),
834
        ui::id(short_id(&c)),
835
        ui::hash(format!("#{h}"))
836
    );
94084087 Andy McCall ↶ 837
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
75167672 Andy McCall 838
    println!(
839
        "{}",
840
        ui::kv(
841
            "author",
842
            ui::author(author_name(&repo, &oxy_core::state::ChangeMeta::of(&c)))
843
        )
844
    );
845
    println!(
846
        "{}",
847
        ui::kv(
848
            "date",
849
            format!(
850
                "{} {}",
851
                when(c.hlc.wall_ms),
852
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
853
            )
854
        )
855
    );
94084087 Andy McCall ↶ 856
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
857
    println!("{}", ui::kv("sig", signature_line(&repo, &h)?));
858
    println!();
75167672 Andy McCall 859
    for line in (if c.message.is_empty() {
860
        "(no description)"
861
    } else {
862
        &c.message
863
    })
864
    .lines()
865
    {
94084087 Andy McCall ↶ 866
        println!("    {line}");
867
    }
868
    println!();
fce44ae9 Andy McCall ↶ 869
    print!("{}", repo.describe_change(&h)?);
870
    Ok(0)
871
}
872
1c2bd9ab Andy McCall ↶ 873
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 874
    let repo = open()?;
875
    let heads = if changes.is_empty() {
876
        repo.bookmark_heads()?
877
    } else {
132b884b Andy McCall ↶ 878
        let mut heads = Vec::new();
879
        for c in changes {
880
            heads.extend(repo.resolve_heads(c)?);
881
        }
882
        heads
fce44ae9 Andy McCall ↶ 883
    };
75167672 Andy McCall 884
    let spec = if changes.is_empty() {
885
        repo.config.bookmark.clone()
886
    } else {
887
        changes.join(" ")
888
    };
135212de Andy McCall ↶ 889
    let sp = ui::spinner(&format!("Checking out {spec}…"));
1c2bd9ab Andy McCall ↶ 890
    let command = format!("oxy checkout {spec}");
891
    let (r, carried) = if carry {
892
        repo.checkout_carry(&heads, &spec, &command)?
893
    } else {
894
        (repo.checkout(&heads, discard, &command)?, vec![])
895
    };
75167672 Andy McCall 896
    sp.done(&format!(
1c2bd9ab Andy McCall ↶ 897
        "{} on {}: {} written, {} removed{}",
75167672 Andy McCall 898
        ui::done("Working copy"),
899
        ui::bookmark(&spec),
900
        plural(r.written, "file"),
1c2bd9ab Andy McCall ↶ 901
        r.removed,
902
        if carried.is_empty() {
903
            String::new()
904
        } else {
905
            format!("; carried {}", plural(carried.len(), "changed path"))
906
        }
75167672 Andy McCall 907
    ));
4dee277c Andy McCall ↶ 908
    for n in &r.notes {
909
        println!("  {} {n}", ui::note());
910
    }
fce44ae9 Andy McCall ↶ 911
    if r.conflicted {
75167672 Andy McCall 912
        println!(
913
            "  {} {}",
914
            ui::caution(),
915
            ui::warn("this state has conflicts; see oxy status")
916
        );
fce44ae9 Andy McCall ↶ 917
    }
918
    Ok(0)
919
}
920
c6aa5bd9 Andy McCall ↶ 921
pub fn resolve(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 922
    let repo = open()?;
923
    let snap = repo.snapshot("oxy resolve")?;
c6aa5bd9 Andy McCall ↶ 924
    if as_json {
925
        println!("{}", repo.status_json(&snap)?);
75167672 Andy McCall 926
        return Ok(if snap.base_snapshot.is_conflicted() {
927
            2
928
        } else {
929
            0
930
        });
c6aa5bd9 Andy McCall ↶ 931
    }
fce44ae9 Andy McCall ↶ 932
    if !snap.base_snapshot.is_conflicted() {
933
        println!("The working copy's base has no conflicts.");
934
        return Ok(0);
935
    }
936
    let mut remaining = 0;
937
    for (p, f) in &snap.base_snapshot.files {
938
        if !f.is_conflicted() {
939
            continue;
940
        }
75167672 Andy McCall 941
        match snap
942
            .statuses
943
            .iter()
944
            .find(|s| s.path == *p)
945
            .map(|s| s.status)
946
        {
fce44ae9 Andy McCall ↶ 947
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
948
            Some(ChangeStatus::ConflictEdited) => {
949
                remaining += 1;
950
                println!("markers    {p}");
951
            }
952
            _ => {
953
                remaining += 1;
954
                println!("unresolved {p}");
955
            }
956
        }
957
    }
958
    for c in &snap.base_snapshot.tree.conflicts {
959
        remaining += 1;
960
        println!("tree       {c:?}");
961
    }
962
    if remaining == 0 {
963
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
964
        Ok(0)
965
    } else {
966
        Ok(2)
967
    }
968
}
969
970
pub fn undo() -> Result<i32> {
971
    let repo = open()?;
972
    let op = repo.undo()?;
94084087 Andy McCall ↶ 973
    println!("{} now at: {}", ui::done("Undone;"), ui::dim(&op.command));
fce44ae9 Andy McCall ↶ 974
    Ok(0)
975
}
976
c6aa5bd9 Andy McCall ↶ 977
pub fn op_log(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 978
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 979
    if as_json {
980
        let ops = repo.op_log()?;
981
        println!(
982
            "{}",
983
            json::arr(ops.iter().enumerate().map(|(i, (r, op))| {
984
                json::obj([
985
                    ("id", json::s(&r.to_hex())),
986
                    ("when_ms", json::n(op.hlc.wall_ms)),
987
                    ("command", json::s(&op.command)),
988
                    ("snapshot", json::b(op.command.ends_with("(snapshot)"))),
989
                    ("current", json::b(i == 0)),
990
                ])
991
            }))
992
        );
993
        return Ok(0);
994
    }
fce44ae9 Andy McCall ↶ 995
    for (i, (r, op)) in repo.op_log()?.into_iter().enumerate() {
75167672 Andy McCall 996
        let bullet = if i == 0 {
997
            ui::ok(ui::glyph("●", "@"))
998
        } else {
999
            ui::dim(ui::glyph("○", "o"))
1000
        };
94084087 Andy McCall ↶ 1001
        let cmd = subject_of(&op.command).split("\\n").next().unwrap_or("");
75167672 Andy McCall 1002
        println!(
1003
            "{bullet} {}{}{}  {}",
1004
            ui::hash(r.short(12)),
1005
            ui::sep(),
1006
            ui::dim(format!("{:<16}", ui::ago(op.hlc.wall_ms))),
1007
            if i == 0 {
1008
                ui::subject(cmd)
1009
            } else {
1010
                cmd.to_string()
1011
            }
1012
        );
fce44ae9 Andy McCall ↶ 1013
    }
1014
    Ok(0)
1015
}
d02e545d Andy McCall ↶ 1016
ba160f60 Andy McCall ↶ 1017
pub fn gc(now: bool) -> Result<i32> {
d02e545d Andy McCall ↶ 1018
    let repo = open()?;
135212de Andy McCall ↶ 1019
    let sp = ui::spinner("Packing and pruning…");
ba160f60 Andy McCall ↶ 1020
    let r = repo.gc(now)?;
135212de Andy McCall ↶ 1021
    sp.clear();
ba160f60 Andy McCall ↶ 1022
    if r.packed.objects > 0 {
d02e545d Andy McCall ↶ 1023
        println!(
ba160f60 Andy McCall ↶ 1024
            "Packed {}: {} bytes -> {} bytes ({:.0}%).",
1025
            plural(r.packed.objects, "loose object"),
1026
            r.packed.raw_bytes,
1027
            r.packed.packed_bytes,
1028
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
d02e545d Andy McCall ↶ 1029
        );
1030
    }
75167672 Andy McCall 1031
    println!(
1032
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
ba160f60 Andy McCall ↶ 1033
        plural(r.reachable, "object"),
1034
        plural(r.pruned.objects, "unreachable object"),
1035
        r.pruned.bytes,
75167672 Andy McCall 1036
        if r.pruned.deferred > 0 {
1037
            format!(
1038
                "; {} deferred by the grace period (use --now)",
1039
                plural(r.pruned.deferred, "object")
1040
            )
1041
        } else {
1042
            String::new()
1043
        },
1044
        if r.merged_packs > 0 {
1045
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1046
        } else {
1047
            String::new()
1048
        },
ba160f60 Andy McCall ↶ 1049
        plural(repo.store().pack_count(), "pack")
1050
    );
d02e545d Andy McCall ↶ 1051
    Ok(0)
1052
}
614541c3 Andy McCall ↶ 1053
3e5772cc Andy McCall ↶ 1054
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
1055
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1056
    use oxy_core::repo::Health;
1057
    let repo = open()?;
1058
    let sp = ui::spinner(if offline {
1059
        "Checking…"
1060
    } else {
1061
        "Checking, and contacting remotes…"
1062
    });
1063
    let r = repo.doctor(!offline);
1064
    sp.clear();
1065
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
1066
    let word = |h: Health| match h {
1067
        Health::Ok => "ok",
1068
        Health::Warn => "warning",
1069
        Health::Fail => "fail",
1070
    };
1071
    if as_json {
1072
        let checks: Vec<String> = r
1073
            .checks
1074
            .iter()
1075
            .map(|c| {
1076
                json::obj([
1077
                    ("area", json::s(&c.area)),
1078
                    ("health", json::s(word(c.health))),
1079
                    ("message", json::s(&c.message)),
1080
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
1081
                ])
1082
            })
1083
            .collect();
1084
        println!(
1085
            "{}",
1086
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1087
        );
1088
        return Ok(code);
1089
    }
1090
    let mut last = "";
1091
    for c in &r.checks {
1092
        if c.area != last {
1093
            println!("{}", ui::section(&c.area));
1094
            last = &c.area;
1095
        }
1096
        let mark = match c.health {
1097
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
1098
            Health::Warn => ui::caution(),
1099
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1100
        };
1101
        println!("  {mark} {}", c.message);
1102
        if let Some(h) = &c.hint {
1103
            println!("    {} {}", ui::dim("→"), ui::dim(h));
1104
        }
1105
    }
1106
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
1107
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
1108
    if fails + warns == 0 {
1109
        println!("{}", ui::done("Everything looks right."));
1110
    } else {
1111
        println!(
1112
            "{} {}, {}.",
1113
            if fails > 0 {
1114
                ui::err(ui::glyph("✖", "x"))
1115
            } else {
1116
                ui::caution()
1117
            },
1118
            plural(fails, "problem"),
1119
            plural(warns, "warning")
1120
        );
1121
    }
1122
    Ok(code)
1123
}
1124
387335ff Andy McCall ↶ 1125
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
1126
pub fn fsck(as_json: bool) -> Result<i32> {
1127
    use oxy_core::repo::Severity;
1128
    let repo = open()?;
1129
    let sp = ui::spinner("Checking every object…");
1130
    let r = repo.fsck()?;
1131
    sp.clear();
1132
    let code = if r.errors() > 0 { 1 } else { 0 };
1133
    if as_json {
1134
        let problems: Vec<String> = r
1135
            .problems
1136
            .iter()
1137
            .map(|p| {
1138
                json::obj([
1139
                    (
1140
                        "severity",
1141
                        json::s(match p.severity {
1142
                            Severity::Error => "error",
1143
                            Severity::Warning => "warning",
1144
                        }),
1145
                    ),
1146
                    (
1147
                        "object",
1148
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1149
                    ),
1150
                    ("what", json::s(&p.what)),
1151
                ])
1152
            })
1153
            .collect();
1154
        println!(
1155
            "{}",
1156
            json::obj([
1157
                ("ok", json::b(code == 0)),
1158
                ("objects", json::n(r.objects)),
1159
                ("ops", json::n(r.ops)),
1160
                ("changes", json::n(r.changes)),
1161
                ("signed", json::n(r.signed)),
1162
                ("unsigned", json::n(r.unsigned)),
1163
                ("checkpoints", json::n(r.checkpoints)),
1164
                ("attestations", json::n(r.attestations)),
1165
                ("errors", json::n(r.errors())),
1166
                ("warnings", json::n(r.warnings())),
1167
                ("problems", json::arr(problems)),
1168
            ])
1169
        );
1170
        return Ok(code);
1171
    }
1172
    println!(
1173
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
1174
        plural(r.objects, "object"),
1175
        plural(r.ops, "operation"),
1176
        plural(r.changes, "change"),
1177
        r.signed,
1178
        r.unsigned,
1179
        plural(r.checkpoints, "checkpoint"),
1180
        plural(r.attestations, "attestation"),
1181
    );
1182
    for p in &r.problems {
1183
        let obj = p
1184
            .object
1185
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
1186
            .unwrap_or_default();
1187
        match p.severity {
1188
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
1189
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1190
        }
1191
    }
1192
    if r.problems.is_empty() {
1193
        println!("{}", ui::done("No problems found."));
1194
    } else if code == 0 {
1195
        println!(
1196
            "{}",
1197
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
1198
        );
1199
    } else {
1200
        println!(
1201
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
1202
            ui::err(ui::glyph("✖", "x")),
1203
            plural(r.errors(), "error"),
1204
            plural(r.warnings(), "warning")
1205
        );
1206
    }
1207
    Ok(code)
1208
}
1209
79d03f82 Andy McCall ↶ 1210
/// The head the working copy sits on, for commands that default to it. With
1211
/// several heads beneath the working copy, the most recently made one is
1212
/// chosen and announced.
614541c3 Andy McCall ↶ 1213
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
cc7a0056 Andy McCall ↶ 1214
    let snap = repo.snapshot_status("oxy")?;
614541c3 Andy McCall ↶ 1215
    let base = snap.base.maximal(&snap.wc.deps);
1216
    match base.as_slice() {
79d03f82 Andy McCall ↶ 1217
        [] => anyhow::bail!("the working copy sits on no change yet"),
614541c3 Andy McCall ↶ 1218
        [h] => Ok(*h),
79d03f82 Andy McCall ↶ 1219
        many => {
1220
            let latest = many
1221
                .iter()
1222
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
1223
                .copied()
1224
                .unwrap();
1225
            let c = repo.store().get_change(&latest)?;
75167672 Andy McCall 1226
            println!(
1227
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
1228
                short_id(&c),
1229
                latest.short(12),
1230
                many.len()
1231
            );
79d03f82 Andy McCall ↶ 1232
            Ok(latest)
1233
        }
614541c3 Andy McCall ↶ 1234
    }
1235
}
1236
6a81dbab Andy McCall ↶ 1237
/// `oxy describe` without -m: the working copy's name for a build.
1238
pub fn describe_name(as_json: bool) -> Result<i32> {
1239
    let repo = open()?;
1240
    let d = repo.describe_working_copy()?;
1241
    if as_json {
1242
        println!(
1243
            "{}",
1244
            json::obj([
1245
                ("describe", json::s(&d.line())),
1246
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
1247
                ("distance", json::n(d.distance)),
1248
                ("bookmark", json::s(&d.bookmark)),
1249
                ("change", json::s(&d.change.to_hex())),
1250
                ("hash", json::s(&d.hash.to_hex())),
1251
                ("dirty", json::b(d.dirty)),
1252
            ])
1253
        );
1254
    } else {
1255
        println!("{}", d.line());
1256
    }
1257
    Ok(0)
1258
}
1259
614541c3 Andy McCall ↶ 1260
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
1261
    let repo = open()?;
1262
    let h = match change {
1263
        Some(c) => repo.resolve_change(c)?,
1264
        None => current_head(&repo)?,
1265
    };
1266
    let new = repo.describe(&h, message)?;
1267
    let c = repo.store().get_change(&new)?;
75167672 Andy McCall 1268
    println!(
1269
        "{} {} {}  {}",
1270
        ui::done("Described"),
1271
        ui::id(short_id(&c)),
1272
        ui::hash(format!("#{}", new.short(12))),
1273
        ui::subject(subject_of(message))
1274
    );
614541c3 Andy McCall ↶ 1275
    Ok(0)
1276
}
1277
23b217d7 Andy McCall ↶ 1278
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
614541c3 Andy McCall ↶ 1279
    let repo = open()?;
23b217d7 Andy McCall ↶ 1280
    let new = match into {
1281
        Some(spec) => {
1282
            let target = repo.resolve_change(spec)?;
1283
            repo.amend_into(&target, message)?
1284
        }
1285
        None => repo.amend(message)?,
1286
    };
614541c3 Andy McCall ↶ 1287
    let c = repo.store().get_change(&new)?;
75167672 Andy McCall 1288
    println!(
1289
        "{} {} {}  {}",
1290
        ui::done("Amended"),
1291
        ui::id(short_id(&c)),
1292
        ui::hash(format!("#{}", new.short(12))),
1293
        ui::subject(subject_of(&c.message))
1294
    );
614541c3 Andy McCall ↶ 1295
    Ok(0)
1296
}
1297
1298
pub fn abandon(change: &str) -> Result<i32> {
1299
    let repo = open()?;
1300
    let h = repo.resolve_change(change)?;
1301
    let c = repo.store().get_change(&h)?;
6706bdcf Andy McCall ↶ 1302
    let notes = repo.abandon(&h)?;
75167672 Andy McCall 1303
    println!(
1304
        "{} {} {}  {}",
1305
        ui::done("Abandoned"),
1306
        ui::id(short_id(&c)),
1307
        ui::hash(format!("#{}", h.short(12))),
1308
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
1309
    );
6706bdcf Andy McCall ↶ 1310
    for n in notes {
94084087 Andy McCall ↶ 1311
        println!("  {} {n}", ui::note());
6706bdcf Andy McCall ↶ 1312
    }
614541c3 Andy McCall ↶ 1313
    Ok(0)
1314
}
252e8cb2 Andy McCall ↶ 1315
1316
pub fn checkpoint() -> Result<i32> {
1317
    let repo = open()?;
135212de Andy McCall ↶ 1318
    let sp = ui::spinner("Writing checkpoint…");
252e8cb2 Andy McCall ↶ 1319
    let (r, changes, bytes) = repo.checkpoint()?;
75167672 Andy McCall 1320
    sp.done(&format!(
1321
        "{} {} of {} ({} bytes) for {}",
1322
        ui::done("Checkpoint"),
1323
        ui::hash(format!("#{}", r.short(12))),
1324
        plural(changes, "change"),
1325
        bytes,
1326
        ui::id(&repo.config.bookmark)
1327
    ));
135212de Andy McCall ↶ 1328
    Ok(0)
1329
}
1330
1331
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
694805cc Andy McCall ↶ 1332
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
75167672 Andy McCall 1333
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
1334
        return Ok(1);
1335
    };
135212de Andy McCall ↶ 1336
    let info = repo.quick_status()?;
75167672 Andy McCall 1337
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
1338
        oxy_core::repo::GLYPH_PROMPT_FORMAT
1339
    } else {
1340
        format
1341
    };
694805cc Andy McCall ↶ 1342
    let line = match color {
1343
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
1344
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
1345
        Some(_) => info.format_colored(fmt, ("", "")),
1346
        None => info.format(fmt),
1347
    };
1348
    println!("{line}");
252e8cb2 Andy McCall ↶ 1349
    Ok(0)
1350
}
7421309f Andy McCall ↶ 1351
1352
pub fn sparse(paths: &[String]) -> Result<i32> {
1353
    let mut repo = open()?;
1354
    if paths.is_empty() {
1355
        if repo.config.sparse_paths.is_empty() {
1356
            println!("No sparse filter: the whole tree is materialized.");
1357
        } else {
1358
            println!("{}", ui::heading("Sparse filter"));
1359
            for p in &repo.config.sparse_paths {
1360
                println!("  {}", ui::path(p));
1361
            }
1362
        }
1363
        return Ok(0);
1364
    }
1365
    let snap = repo.snapshot("oxy sparse")?;
1366
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
75167672 Andy McCall 1367
        anyhow::bail!(
1368
            "the working copy has changes; commit them before changing the sparse filter"
1369
        );
7421309f Andy McCall ↶ 1370
    }
1371
    repo.config.set("filter.paths", &paths.join(","))?;
1372
    repo.save_config()?;
1373
    let heads = repo.bookmark_heads()?;
1374
    let sp = ui::spinner("Re-checking out with the new filter…");
1375
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
75167672 Andy McCall 1376
    sp.done(&format!(
1377
        "{} {}: {} written, {} removed",
1378
        ui::ok("Sparse filter set to"),
1379
        ui::path(paths.join(",")),
1380
        plural(r.written, "file"),
1381
        r.removed
1382
    ));
7421309f Andy McCall ↶ 1383
    Ok(0)
1384
}
132b884b Andy McCall ↶ 1385
1386
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
1387
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1388
    repo.snapshot_status("oxy tag")?;
132b884b Andy McCall ↶ 1389
    let heads = if changes.is_empty() {
1390
        repo.bookmark_heads()?
1391
    } else {
1392
        let mut heads = Vec::new();
1393
        for c in changes {
1394
            heads.extend(repo.resolve_heads(c)?);
1395
        }
1396
        heads
1397
    };
1398
    let t = repo.tag_create(name, &heads, message)?;
1399
    println!(
94084087 Andy McCall ↶ 1400
        "{} {} {} {} ({}){}",
1401
        ui::done("Tagged"),
1402
        ui::bookmark(&t.name),
1403
        ui::dim(ui::glyph("→", "->")),
132b884b Andy McCall ↶ 1404
        ui::hash(format!("#{}", t.state.short(12))),
1405
        plural(t.heads.len(), "head"),
75167672 Andy McCall 1406
        t.signer
1407
            .map(|s| format!(", signed by {s}"))
1408
            .unwrap_or_else(|| ui::dim(", unsigned"))
132b884b Andy McCall ↶ 1409
    );
1410
    Ok(0)
1411
}
1412
1196b29b Andy McCall ↶ 1413
pub fn tag_list(as_json: bool) -> Result<i32> {
132b884b Andy McCall ↶ 1414
    let repo = open()?;
1415
    let tags = repo.tags()?;
1196b29b Andy McCall ↶ 1416
    if as_json {
1417
        println!(
1418
            "{}",
1419
            json::arr(tags.iter().map(|t| {
1420
                json::obj([
1421
                    ("name", json::s(&t.name)),
1422
                    ("state", json::s(&t.state.to_hex())),
1423
                    ("heads", json::hashes(&t.heads)),
1424
                    ("message", json::s(&t.message)),
75167672 Andy McCall 1425
                    (
1426
                        "signer",
1427
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
1428
                    ),
1196b29b Andy McCall ↶ 1429
                ])
1430
            }))
1431
        );
1432
        return Ok(0);
1433
    }
132b884b Andy McCall ↶ 1434
    if tags.is_empty() {
1435
        println!("{}", ui::dim("No tags."));
1436
    }
1437
    for t in tags {
1438
        println!(
94084087 Andy McCall ↶ 1439
            "{} {} {}{}{}{}",
1440
            ui::ok(ui::glyph("⚑", "#")),
1441
            ui::bookmark(&t.name),
6a81dbab Andy McCall ↶ 1442
            // The heads, as `oxy log` shows changes, not the state hash.
1443
            ui::hash(
1444
                t.heads
1445
                    .iter()
1446
                    .map(|h| format!("#{}", h.short(12)))
1447
                    .collect::<Vec<_>>()
1448
                    .join(" ")
1449
            ),
94084087 Andy McCall ↶ 1450
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
75167672 Andy McCall 1451
            if t.message.is_empty() {
1452
                String::new()
1453
            } else {
1454
                format!("  {}", ui::subject(subject_of(&t.message)))
1455
            },
1456
            t.signer
1457
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
1458
                .unwrap_or_default()
132b884b Andy McCall ↶ 1459
        );
1460
    }
1461
    Ok(0)
1462
}
4e88e774 Andy McCall ↶ 1463
1464
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
1465
    let repo = open()?;
1466
    let heads = if changes.is_empty() {
1467
        None
1468
    } else {
1469
        let mut heads = Vec::new();
1470
        for c in changes {
1471
            heads.extend(repo.resolve_heads(c)?);
1472
        }
1473
        Some(heads)
1474
    };
1475
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
1476
    let ws = repo.workspace_add(path, heads.as_deref())?;
75167672 Andy McCall 1477
    sp.done(&format!(
1478
        "{} {} (workspace {})",
1479
        ui::done("Workspace created at"),
1480
        ui::path(ws.root().display()),
1481
        ui::id(ws.workspace().short(8))
1482
    ));
4e88e774 Andy McCall ↶ 1483
    Ok(0)
1484
}
1485
1196b29b Andy McCall ↶ 1486
pub fn workspace_list(as_json: bool) -> Result<i32> {
4e88e774 Andy McCall ↶ 1487
    let repo = open()?;
1196b29b Andy McCall ↶ 1488
    if as_json {
1489
        println!(
1490
            "{}",
1491
            json::arr(repo.workspaces()?.iter().map(|w| {
1492
                json::obj([
1493
                    ("id", json::s(&w.id.to_hex())),
1494
                    ("path", json::s(&w.path.to_string_lossy())),
1495
                    ("current", json::b(w.current)),
75167672 Andy McCall 1496
                    (
1497
                        "working_copy",
1498
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
1499
                    ),
1196b29b Andy McCall ↶ 1500
                ])
1501
            }))
1502
        );
1503
        return Ok(0);
1504
    }
4e88e774 Andy McCall ↶ 1505
    for w in repo.workspaces()? {
1506
        println!(
1507
            "{} {} {}{}",
75167672 Andy McCall 1508
            if w.current {
1509
                ui::ok(ui::glyph("●", "*"))
1510
            } else {
1511
                ui::dim(ui::glyph("○", "o"))
1512
            },
4e88e774 Andy McCall ↶ 1513
            ui::id(w.id.short(8)),
1514
            ui::path(w.path.display()),
75167672 Andy McCall 1515
            w.working_copy
1516
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
1517
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
4e88e774 Andy McCall ↶ 1518
        );
1519
    }
1520
    Ok(0)
1521
}
1522
1523
pub fn workspace_forget(spec: &str) -> Result<i32> {
1524
    let repo = open()?;
1525
    let all = repo.workspaces()?;
1526
    let target = std::fs::canonicalize(spec).ok();
75167672 Andy McCall 1527
    let matches: Vec<_> = all
1528
        .iter()
1529
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
1530
        .collect();
4e88e774 Andy McCall ↶ 1531
    let w = match matches.as_slice() {
1532
        [w] => *w,
1533
        [] => anyhow::bail!("no workspace matches {spec:?}"),
1534
        _ => anyhow::bail!("{spec:?} is ambiguous"),
1535
    };
1536
    repo.workspace_forget(&w.id)?;
75167672 Andy McCall 1537
    println!(
1538
        "{} workspace {} at {}; its files were left in place.",
1539
        ui::done("Forgot"),
1540
        ui::id(w.id.short(8)),
1541
        ui::path(w.path.display())
1542
    );
4e88e774 Andy McCall ↶ 1543
    Ok(0)
1544
}
cdb5beba Andy McCall ↶ 1545
1546
pub fn lock(path: &str) -> Result<i32> {
1547
    let repo = open()?;
1548
    repo.lock_path(path)?;
75167672 Andy McCall 1549
    println!(
1550
        "{} {} {}",
1551
        ui::done("Locked"),
1552
        ui::path(path),
1553
        ui::dim("(advisory, local)")
1554
    );
cdb5beba Andy McCall ↶ 1555
    Ok(0)
1556
}
1557
1558
pub fn unlock(path: &str) -> Result<i32> {
1559
    let repo = open()?;
1560
    repo.unlock_path(path)?;
94084087 Andy McCall ↶ 1561
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
cdb5beba Andy McCall ↶ 1562
    Ok(0)
1563
}
23b217d7 Andy McCall ↶ 1564
1565
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
1566
    let repo = open()?;
1567
    let h = repo.resolve_change(change)?;
1568
    let (h1, h2) = repo.split(&h, paths)?;
1569
    let c1 = repo.store().get_change(&h1)?;
1570
    let c2 = repo.store().get_change(&h2)?;
75167672 Andy McCall 1571
    println!(
1572
        "{} into {} {} and {} {}",
1573
        ui::done("Split"),
1574
        ui::id(short_id(&c1)),
1575
        ui::hash(format!("#{}", h1.short(12))),
1576
        ui::id(short_id(&c2)),
1577
        ui::hash(format!("#{}", h2.short(12)))
1578
    );
23b217d7 Andy McCall ↶ 1579
    Ok(0)
1580
}
7b9809e6 Andy McCall ↶ 1581
1582
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
1583
    let mut heads = Vec::new();
1584
    for c in changes {
1585
        heads.extend(repo.resolve_heads(c)?);
1586
    }
1587
    Ok(heads)
1588
}
1589
4fe7d604 Andy McCall ↶ 1590
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 1591
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1592
    repo.snapshot_status("oxy bookmark create")?;
75167672 Andy McCall 1593
    let heads = if changes.is_empty() {
1594
        None
1595
    } else {
4fe7d604 Andy McCall ↶ 1596
        let named = heads_from(&repo, changes)?;
1597
        let (_, wc) = repo.working_copy()?;
1598
        let gap = repo.state_gap(&wc.deps, &named)?;
1599
        if upto {
1600
            Some(gap.upto)
1601
        } else if only || gap.earlier.is_empty() {
1602
            Some(named)
1603
        } else {
1604
            anyhow::bail!(
1605
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
1606
                 A state is its heads and what they depend on, not everything recorded before them.\n\
1607
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
1608
                 or --only for just {0} and what it depends on.",
1609
                changes.join(" "),
1610
                plural(gap.earlier.len(), "change"),
1611
                listed_changes(&repo, &gap.earlier)
1612
            );
1613
        }
75167672 Andy McCall 1614
    };
7b9809e6 Andy McCall ↶ 1615
    let heads = repo.bookmark_create(name, heads.as_deref())?;
75167672 Andy McCall 1616
    println!(
1617
        "{} bookmark {} {} {}",
1618
        ui::done("Created"),
1619
        ui::bookmark(name),
1620
        ui::dim(ui::glyph("→", "->")),
1621
        ui::dim(plural(heads.len(), "head"))
1622
    );
1623
    println!(
1624
        "  {} {}",
1625
        ui::note(),
1626
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
1627
    );
7b9809e6 Andy McCall ↶ 1628
    Ok(0)
1629
}
1630
4fe7d604 Andy McCall ↶ 1631
/// Up to five changes, newest last, as `  #hash subject` lines.
1632
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
1633
    let shown = changes.len().min(5);
1634
    let mut lines: Vec<String> = changes[changes.len() - shown..]
1635
        .iter()
1636
        .map(|h| {
1637
            let subject = repo
1638
                .store()
1639
                .get_change(h)
1640
                .map(|c| subject_of(&c.message).to_string())
1641
                .unwrap_or_default();
1642
            format!("  #{} {subject}", h.short(12))
1643
        })
1644
        .collect();
1645
    if changes.len() > shown {
1646
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
1647
    }
1648
    lines.join("\n")
1649
}
1650
7b9809e6 Andy McCall ↶ 1651
pub fn bookmark_set(name: &str, changes: &[String]) -> Result<i32> {
1652
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1653
    repo.snapshot_status("oxy bookmark set")?;
7b9809e6 Andy McCall ↶ 1654
    let heads = heads_from(&repo, changes)?;
1655
    let heads = repo.bookmark_set(name, &heads)?;
75167672 Andy McCall 1656
    println!(
1657
        "{} bookmark {} {} {}",
1658
        ui::done("Moved"),
1659
        ui::bookmark(name),
1660
        ui::dim(ui::glyph("→", "->")),
1661
        ui::dim(plural(heads.len(), "head"))
1662
    );
7b9809e6 Andy McCall ↶ 1663
    Ok(0)
1664
}
1665
1666
pub fn bookmark_delete(name: &str) -> Result<i32> {
1667
    let repo = open()?;
1668
    repo.bookmark_delete(name)?;
75167672 Andy McCall 1669
    println!(
1670
        "{} bookmark {} {}",
1671
        ui::done("Deleted"),
1672
        ui::bookmark(name),
1673
        ui::dim("(its changes stay until unreachable)")
1674
    );
7b9809e6 Andy McCall ↶ 1675
    Ok(0)
1676
}
1677
c6aa5bd9 Andy McCall ↶ 1678
pub fn bookmark_list(as_json: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 1679
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 1680
    if as_json {
1681
        let items = repo.bookmarks()?.into_iter().map(|b| {
1682
            json::obj([
1683
                ("name", json::s(&b.name)),
1684
                ("heads", json::hashes(&b.heads)),
1685
                ("current", json::b(b.current)),
1686
                ("ahead", json::opt(b.ahead, json::n)),
1687
                ("behind", json::opt(b.behind, json::n)),
1688
            ])
1689
        });
1690
        println!("{}", json::arr(items));
1691
        return Ok(0);
1692
    }
7b9809e6 Andy McCall ↶ 1693
    for b in repo.bookmarks()? {
75167672 Andy McCall 1694
        let mark = if b.current {
1695
            ui::ok(ui::glyph("●", "*"))
1696
        } else {
1697
            ui::dim(ui::glyph("○", "o"))
1698
        };
7b9809e6 Andy McCall ↶ 1699
        let mut tail = String::new();
1700
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
1701
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
1702
        }
1703
        if let Some(n) = b.behind.filter(|n| *n > 0) {
1704
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
1705
        }
75167672 Andy McCall 1706
        let head = b
1707
            .heads
1708
            .first()
1709
            .map(|h| {
1710
                repo.store()
1711
                    .get_change(h)
1712
                    .map(|c| ui::subject(subject_of(&c.message)))
1713
                    .unwrap_or_default()
1714
            })
1715
            .unwrap_or_else(|| ui::dim("(empty)"));
1716
        println!(
1717
            "{mark} {}{}{}{tail}  {head}",
1718
            ui::bookmark(&b.name),
1719
            ui::sep(),
1720
            ui::dim(plural(b.heads.len(), "head"))
1721
        );
7b9809e6 Andy McCall ↶ 1722
    }
1723
    Ok(0)
1724
}
1725
61e3bce7 Andy McCall ↶ 1726
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 1727
    let mut repo = open()?;
4fe7d604 Andy McCall ↶ 1728
    let from = repo.config.bookmark.clone();
1729
    let before = repo
1730
        .working_copy()
1731
        .map(|(_, wc)| wc.deps)
1732
        .unwrap_or_default();
7b9809e6 Andy McCall ↶ 1733
    let sp = ui::spinner(&format!("Switching to {name}…"));
61e3bce7 Andy McCall ↶ 1734
    let (r, carried) = if carry {
1735
        repo.bookmark_switch_carry(name)?
1736
    } else {
1737
        (repo.bookmark_switch(name, discard)?, vec![])
1738
    };
75167672 Andy McCall 1739
    sp.done(&format!(
61e3bce7 Andy McCall ↶ 1740
        "{} to {}: {} written, {} removed{}",
75167672 Andy McCall 1741
        ui::done("Switched"),
1742
        ui::bookmark(name),
1743
        plural(r.written, "file"),
61e3bce7 Andy McCall ↶ 1744
        r.removed,
1745
        if carried.is_empty() {
1746
            String::new()
1747
        } else {
1748
            format!("; carried {}", plural(carried.len(), "changed path"))
1749
        }
75167672 Andy McCall 1750
    ));
7b9809e6 Andy McCall ↶ 1751
    if r.conflicted {
75167672 Andy McCall 1752
        println!(
1753
            "  {} {}",
1754
            ui::caution(),
1755
            ui::warn("this state has conflicts; see oxy status")
1756
        );
4fe7d604 Andy McCall ↶ 1757
    }
1758
    // Say when the new state leaves out work the old one had: a state is
1759
    // its heads and what they depend on, which can be far less than a Git
1760
    // user expects.
1761
    let after = repo
1762
        .working_copy()
1763
        .map(|(_, wc)| wc.deps)
1764
        .unwrap_or_default();
1765
    if let Ok(gap) = repo.state_gap(&before, &after) {
1766
        if gap.lacks > 0 {
1767
            println!(
1768
                "  {} {}",
1769
                ui::note(),
1770
                ui::dim(format!(
1771
                    "{name} lacks {} that {from} has",
1772
                    plural(gap.lacks, "change")
1773
                ))
1774
            );
1775
        }
7b9809e6 Andy McCall ↶ 1776
    }
1777
    Ok(0)
1778
}
1779
1780
pub fn merge(bookmark: &str) -> Result<i32> {
1781
    let repo = open()?;
1782
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
1783
    let r = repo.merge(bookmark)?;
1784
    if !r.changed {
75167672 Andy McCall 1785
        sp.done(&format!(
1786
            "{} {}",
1787
            ui::ok(ui::glyph("✔", "*")),
1788
            ui::dim(format!(
1789
                "{} already contains {bookmark}",
1790
                repo.config.bookmark
1791
            ))
1792
        ));
7b9809e6 Andy McCall ↶ 1793
        return Ok(0);
1794
    }
1795
    sp.done(&format!(
1796
        "{} {} into {}: now {}{}",
1797
        ui::done("Merged"),
1798
        ui::bookmark(bookmark),
1799
        ui::bookmark(&repo.config.bookmark),
1800
        plural(r.heads.len(), "head"),
75167672 Andy McCall 1801
        ui::dim(if r.checked_out {
1802
            "; working copy updated"
1803
        } else {
1804
            "; run oxy checkout to update the working copy"
1805
        })
7b9809e6 Andy McCall ↶ 1806
    ));
1807
    let snap = repo.snapshot("oxy merge")?;
1808
    if snap.base_snapshot.is_conflicted() {
75167672 Andy McCall 1809
        println!(
1810
            "  {} {}",
1811
            ui::caution(),
1812
            ui::warn("the result has conflicts; see oxy status")
1813
        );
7b9809e6 Andy McCall ↶ 1814
    }
1815
    Ok(0)
1816
}
1817
728da0f9 Andy McCall ↶ 1818
pub fn squash(change: &str, into: &str) -> Result<i32> {
1819
    let repo = open()?;
1820
    let c = repo.resolve_change(change)?;
1821
    let d = repo.resolve_change(into)?;
1822
    let sp = ui::spinner("Squashing…");
1823
    let h = repo.squash(&c, &d)?;
1824
    let new = repo.store().get_change(&h)?;
75167672 Andy McCall 1825
    sp.done(&format!(
1826
        "{} into {} {}  {}",
1827
        ui::done("Squashed"),
1828
        ui::id(short_id(&new)),
1829
        ui::hash(format!("#{}", h.short(12))),
1830
        ui::subject(subject_of(&new.message))
1831
    ));
728da0f9 Andy McCall ↶ 1832
    Ok(0)
1833
}
1834
1835
pub fn rebase(change: &str, onto: &[String]) -> Result<i32> {
1836
    let repo = open()?;
1837
    let c = repo.resolve_change(change)?;
1838
    let mut heads = Vec::new();
1839
    for o in onto {
1840
        heads.extend(repo.resolve_heads(o)?);
1841
    }
1842
    let sp = ui::spinner("Rebasing…");
1843
    let h = repo.rebase(&c, &heads)?;
1844
    let new = repo.store().get_change(&h)?;
75167672 Andy McCall 1845
    sp.done(&format!(
1846
        "{} {} {}  {}",
1847
        ui::done("Rebased"),
1848
        ui::id(short_id(&new)),
1849
        ui::hash(format!("#{}", h.short(12))),
1850
        ui::dim(format!(
1851
            "now depends on {}",
1852
            plural(new.deps.len(), "change")
1853
        ))
1854
    ));
728da0f9 Andy McCall ↶ 1855
    Ok(0)
1856
}