OXYGENHUB
# 155313e68e15 oxygen / src / cli / workspace.rs
53.6 KiB · Rust · last changed The history of a range of lines: oxy log -L START,END:PATH 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()?;
cc7a0056 Andy McCall ↶ 497
    let snap = repo.snapshot_status("oxy log")?;
94084087 Andy McCall ↶ 498
    let conflicted = snap.base_snapshot.is_conflicted();
83d61e80 Andy McCall ↶ 499
    let entries = match (path, lines) {
500
        (_, Some(spec)) => {
501
            let (first, last, p) = parse_line_range(spec)?;
502
            repo.line_history(&snap.base.maximal(&snap.wc.deps), p, first, last)?
503
        }
504
        (Some(p), None) => repo.log_for_path(p)?,
505
        (None, None) => repo.log()?,
c6aa5bd9 Andy McCall ↶ 506
    };
507
    if as_json {
508
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
509
        let mut items = Vec::new();
510
        for e in entries.iter().take(shown) {
511
            items.push(log_entry_json(&repo, e)?);
512
        }
75167672 Andy McCall 513
        println!(
514
            "{}",
515
            json::obj([
516
                ("bookmark", json::s(&repo.config.bookmark)),
517
                ("total", json::n(entries.len())),
518
                ("changes", json::arr(items))
519
            ])
520
        );
c6aa5bd9 Andy McCall ↶ 521
        return Ok(0);
522
    }
94084087 Andy McCall ↶ 523
    let total = entries.len();
524
    let shown = limit.unwrap_or(total).min(total);
525
    let rail = ui::rail();
526
    for (i, e) in entries.iter().take(shown).enumerate() {
fce44ae9 Andy McCall ↶ 527
        let c = &e.change;
75167672 Andy McCall 528
        let bullet = ui::log_bullet(
529
            e.is_working_copy,
530
            e.is_head,
531
            e.is_working_copy && conflicted,
532
        );
94084087 Andy McCall ↶ 533
        let mut labels = Vec::new();
fce44ae9 Andy McCall ↶ 534
        if e.is_working_copy {
94084087 Andy McCall ↶ 535
            labels.push(ui::warn("working copy"));
fce44ae9 Andy McCall ↶ 536
        }
94084087 Andy McCall ↶ 537
        if c.kind == ChangeKind::Resolution {
538
            labels.push(ui::warn("resolution"));
fce44ae9 Andy McCall ↶ 539
        }
75167672 Andy McCall 540
        let labels = if labels.is_empty() {
541
            String::new()
542
        } else {
543
            format!(
544
                " {}{}{}",
545
                ui::dim("("),
546
                labels.join(ui::dim(", ").as_str()),
547
                ui::dim(")")
548
            )
549
        };
94084087 Andy McCall ↶ 550
        let subject = if e.is_working_copy && c.message.is_empty() {
75167672 Andy McCall 551
            ui::dim(if snap.statuses.is_empty() {
552
                "(clean)"
553
            } else {
554
                "(uncommitted changes)"
555
            })
94084087 Andy McCall ↶ 556
        } else {
557
            ui::subject(subject_of(&c.message))
558
        };
559
        println!("{bullet} {}{labels}  {subject}", ui::id(short_meta_id(c)));
560
        let meta = format!(
561
            "{}{}{}{}{}{}{}",
562
            ui::hash(format!("#{}", e.hash.short(12))),
563
            ui::sep(),
564
            ui::author(author_name(&repo, c)),
565
            ui::sep(),
566
            ui::dim(ui::ago(c.hlc.wall_ms)),
567
            ui::sep(),
75167672 Andy McCall 568
            if e.is_working_copy {
569
                ui::dim("not yet committed")
570
            } else {
571
                signature_mark(&repo, &e.hash)?
572
            }
94084087 Andy McCall ↶ 573
        );
574
        println!("{rail} {meta}");
575
        if verbose {
576
            if !e.is_working_copy {
75167672 Andy McCall 577
                println!(
578
                    "{rail} {}",
579
                    ui::dim(format!(
580
                        "{} {}",
581
                        when(c.hlc.wall_ms),
582
                        signature_line(&repo, &e.hash)?
583
                    ))
584
                );
94084087 Andy McCall ↶ 585
            }
586
            if !c.deps.is_empty() {
75167672 Andy McCall 587
                println!(
588
                    "{rail} {} {}",
589
                    ui::dim(ui::glyph("↳", "->")),
590
                    ui::dim(deps_of(&c.deps))
591
                );
94084087 Andy McCall ↶ 592
            }
75167672 Andy McCall 593
            let body: Vec<&str> = c
594
                .message
595
                .lines()
596
                .skip(1)
597
                .skip_while(|l| l.trim().is_empty())
598
                .collect();
94084087 Andy McCall ↶ 599
            if !body.is_empty() {
600
                println!("{rail}");
601
                for line in body {
602
                    println!("{rail}   {line}");
603
                }
604
            }
fce44ae9 Andy McCall ↶ 605
        }
94084087 Andy McCall ↶ 606
        if i + 1 < shown {
607
            println!("{rail}");
fce44ae9 Andy McCall ↶ 608
        }
609
    }
94084087 Andy McCall ↶ 610
    if shown < total {
75167672 Andy McCall 611
        println!(
612
            "{}",
613
            ui::dim(format!(
614
                "{} {} more; pass -n to see them",
615
                ui::glyph("…", "..."),
616
                total - shown
617
            ))
618
        );
94084087 Andy McCall ↶ 619
    }
fce44ae9 Andy McCall ↶ 620
    Ok(0)
621
}
622
c6aa5bd9 Andy McCall ↶ 623
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
624
    let repo = open()?;
625
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
626
    if as_json {
627
        let files = repo.diff_files(hash.as_ref())?;
628
        let items = files.iter().map(|f| {
629
            json::obj([
630
                ("path", json::s(&f.path)),
631
                ("kind", json::s(&f.kind)),
632
                ("from", json::opt(f.from.as_deref(), json::s)),
633
                (
634
                    "hunks",
635
                    json::arr(f.hunks.iter().map(|h| {
636
                        json::obj([
637
                            ("base_line", json::n(h.base_line)),
75167672 Andy McCall 638
                            (
639
                                "added",
640
                                json::arr(
641
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
642
                                ),
643
                            ),
644
                            (
645
                                "removed",
646
                                json::arr(h.removed.iter().map(|(n, l)| {
647
                                    json::obj([
648
                                        ("line", json::n(*n)),
649
                                        ("text", json::s(&String::from_utf8_lossy(l))),
650
                                    ])
651
                                })),
652
                            ),
c6aa5bd9 Andy McCall ↶ 653
                        ])
654
                    })),
655
                ),
656
            ])
657
        });
75167672 Andy McCall 658
        println!(
659
            "{}",
660
            json::obj([
661
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
662
                ("files", json::arr(items))
663
            ])
664
        );
c6aa5bd9 Andy McCall ↶ 665
        return Ok(0);
666
    }
667
    match hash {
668
        Some(h) => {
669
            let c = repo.store().get_change(&h)?;
8ab265dc Andy McCall ↶ 670
            let (base, snapshot) = repo.change_base(&c)?;
c6aa5bd9 Andy McCall ↶ 671
            print!("{}", render_change(&c, &base, &snapshot));
672
        }
673
        None => {
8ab265dc Andy McCall ↶ 674
            let snap = repo.snapshot_status("oxy diff")?;
75167672 Andy McCall 675
            print!(
676
                "{}",
677
                render_change(&snap.wc, &snap.base, &snap.base_snapshot)
678
            );
c6aa5bd9 Andy McCall ↶ 679
        }
680
    }
681
    Ok(0)
682
}
683
684
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
685
    let repo = open()?;
686
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
687
    let bytes = repo.file_at(path, heads.as_deref())?;
688
    use std::io::Write as _;
689
    std::io::stdout().write_all(&bytes)?;
690
    Ok(0)
691
}
692
693
pub fn root(as_json: bool) -> Result<i32> {
694
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
695
        if as_json {
696
            println!("null");
697
        }
698
        return Ok(1);
699
    };
700
    if as_json {
75167672 Andy McCall 701
        println!(
702
            "{}",
703
            json::obj([
704
                ("root", json::s(&repo.root().to_string_lossy())),
705
                ("workspace", json::s(&repo.workspace().to_hex())),
706
                ("bookmark", json::s(&repo.config.bookmark))
707
            ])
708
        );
c6aa5bd9 Andy McCall ↶ 709
    } else {
710
        println!("{}", repo.root().display());
711
    }
712
    Ok(0)
713
}
714
715
pub fn version(as_json: bool) -> Result<i32> {
716
    if as_json {
75167672 Andy McCall 717
        println!(
718
            "{}",
719
            json::obj([
720
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
721
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
722
                ("format", json::n(2))
723
            ])
724
        );
c6aa5bd9 Andy McCall ↶ 725
    } else {
75167672 Andy McCall 726
        println!(
727
            "oxy {} (repository format 2, protocol {})",
728
            env!("CARGO_PKG_VERSION"),
729
            oxy_core::protocol::PROTOCOL_VERSION
730
        );
c6aa5bd9 Andy McCall ↶ 731
    }
732
    Ok(0)
733
}
734
735
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
736
    let repo = open()?;
737
    if paths.is_empty() && hunks.is_empty() {
738
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
739
    }
740
    let mut n = 0;
741
    if !hunks.is_empty() {
742
        n += repo.discard_hunks(hunks)?;
743
    }
744
    if !paths.is_empty() {
745
        n += repo.discard(paths)?;
746
    }
75167672 Andy McCall 747
    println!(
748
        "{} {} restored to the working copy's base",
749
        ui::done("Discarded"),
750
        plural(n, "path")
751
    );
c6aa5bd9 Andy McCall ↶ 752
    Ok(0)
753
}
754
755
pub fn hunks(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 756
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 757
    let (_, hunks) = repo.hunks()?;
758
    if as_json {
75167672 Andy McCall 759
        println!(
760
            "{}",
761
            json::arr(hunks.iter().map(|h| json::obj([
762
                ("index", json::n(h.index)),
763
                ("path", json::s(&h.path)),
764
                ("text", json::s(&h.text))
765
            ])))
766
        );
c6aa5bd9 Andy McCall ↶ 767
        return Ok(0);
768
    }
769
    if hunks.is_empty() {
75167672 Andy McCall 770
        println!(
771
            "{}",
772
            ui::dim("No hunks: the working copy matches its base.")
773
        );
c6aa5bd9 Andy McCall ↶ 774
    }
775
    for h in &hunks {
75167672 Andy McCall 776
        println!(
777
            "{} {}",
778
            ui::section(format!("hunk {}", h.index)),
779
            ui::path(&h.path)
780
        );
c6aa5bd9 Andy McCall ↶ 781
        for line in h.text.lines() {
75167672 Andy McCall 782
            let styled = if line.starts_with('+') {
783
                ui::ok(line)
784
            } else if line.starts_with('-') {
785
                ui::err(line)
786
            } else {
787
                ui::dim(line)
788
            };
c6aa5bd9 Andy McCall ↶ 789
            println!("  {styled}");
790
        }
791
    }
fce44ae9 Andy McCall ↶ 792
    Ok(0)
793
}
794
c6aa5bd9 Andy McCall ↶ 795
pub fn show(change: &str, as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 796
    let repo = open()?;
cc7a0056 Andy McCall ↶ 797
    repo.snapshot_status("oxy show")?;
fce44ae9 Andy McCall ↶ 798
    let h = repo.resolve_change(change)?;
799
    let c = repo.store().get_change(&h)?;
c6aa5bd9 Andy McCall ↶ 800
    if as_json {
801
        let files = repo.diff_files(Some(&h))?;
802
        let heads = repo.bookmark_heads()?;
75167672 Andy McCall 803
        let entry = oxy_core::repo::LogEntry {
804
            hash: h,
805
            change: oxy_core::state::ChangeMeta::of(&c),
806
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
807
            is_head: heads.contains(&h),
808
        };
c6aa5bd9 Andy McCall ↶ 809
        let mut body = log_entry_json(&repo, &entry)?;
810
        body.pop();
75167672 Andy McCall 811
        body.push_str(&format!(
812
            ",{}:{}}}",
813
            json::s("files"),
814
            json::arr(files.iter().map(|f| json::obj([
815
                ("path", json::s(&f.path)),
816
                ("kind", json::s(&f.kind)),
817
                ("from", json::opt(f.from.as_deref(), json::s))
818
            ])))
819
        ));
c6aa5bd9 Andy McCall ↶ 820
        println!("{body}");
821
        return Ok(0);
822
    }
75167672 Andy McCall 823
    println!(
824
        "{} {} {}",
825
        ui::section("change"),
826
        ui::id(short_id(&c)),
827
        ui::hash(format!("#{h}"))
828
    );
94084087 Andy McCall ↶ 829
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
75167672 Andy McCall 830
    println!(
831
        "{}",
832
        ui::kv(
833
            "author",
834
            ui::author(author_name(&repo, &oxy_core::state::ChangeMeta::of(&c)))
835
        )
836
    );
837
    println!(
838
        "{}",
839
        ui::kv(
840
            "date",
841
            format!(
842
                "{} {}",
843
                when(c.hlc.wall_ms),
844
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
845
            )
846
        )
847
    );
94084087 Andy McCall ↶ 848
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
849
    println!("{}", ui::kv("sig", signature_line(&repo, &h)?));
850
    println!();
75167672 Andy McCall 851
    for line in (if c.message.is_empty() {
852
        "(no description)"
853
    } else {
854
        &c.message
855
    })
856
    .lines()
857
    {
94084087 Andy McCall ↶ 858
        println!("    {line}");
859
    }
860
    println!();
fce44ae9 Andy McCall ↶ 861
    print!("{}", repo.describe_change(&h)?);
862
    Ok(0)
863
}
864
1c2bd9ab Andy McCall ↶ 865
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 866
    let repo = open()?;
867
    let heads = if changes.is_empty() {
868
        repo.bookmark_heads()?
869
    } else {
132b884b Andy McCall ↶ 870
        let mut heads = Vec::new();
871
        for c in changes {
872
            heads.extend(repo.resolve_heads(c)?);
873
        }
874
        heads
fce44ae9 Andy McCall ↶ 875
    };
75167672 Andy McCall 876
    let spec = if changes.is_empty() {
877
        repo.config.bookmark.clone()
878
    } else {
879
        changes.join(" ")
880
    };
135212de Andy McCall ↶ 881
    let sp = ui::spinner(&format!("Checking out {spec}…"));
1c2bd9ab Andy McCall ↶ 882
    let command = format!("oxy checkout {spec}");
883
    let (r, carried) = if carry {
884
        repo.checkout_carry(&heads, &spec, &command)?
885
    } else {
886
        (repo.checkout(&heads, discard, &command)?, vec![])
887
    };
75167672 Andy McCall 888
    sp.done(&format!(
1c2bd9ab Andy McCall ↶ 889
        "{} on {}: {} written, {} removed{}",
75167672 Andy McCall 890
        ui::done("Working copy"),
891
        ui::bookmark(&spec),
892
        plural(r.written, "file"),
1c2bd9ab Andy McCall ↶ 893
        r.removed,
894
        if carried.is_empty() {
895
            String::new()
896
        } else {
897
            format!("; carried {}", plural(carried.len(), "changed path"))
898
        }
75167672 Andy McCall 899
    ));
4dee277c Andy McCall ↶ 900
    for n in &r.notes {
901
        println!("  {} {n}", ui::note());
902
    }
fce44ae9 Andy McCall ↶ 903
    if r.conflicted {
75167672 Andy McCall 904
        println!(
905
            "  {} {}",
906
            ui::caution(),
907
            ui::warn("this state has conflicts; see oxy status")
908
        );
fce44ae9 Andy McCall ↶ 909
    }
910
    Ok(0)
911
}
912
c6aa5bd9 Andy McCall ↶ 913
pub fn resolve(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 914
    let repo = open()?;
915
    let snap = repo.snapshot("oxy resolve")?;
c6aa5bd9 Andy McCall ↶ 916
    if as_json {
917
        println!("{}", repo.status_json(&snap)?);
75167672 Andy McCall 918
        return Ok(if snap.base_snapshot.is_conflicted() {
919
            2
920
        } else {
921
            0
922
        });
c6aa5bd9 Andy McCall ↶ 923
    }
fce44ae9 Andy McCall ↶ 924
    if !snap.base_snapshot.is_conflicted() {
925
        println!("The working copy's base has no conflicts.");
926
        return Ok(0);
927
    }
928
    let mut remaining = 0;
929
    for (p, f) in &snap.base_snapshot.files {
930
        if !f.is_conflicted() {
931
            continue;
932
        }
75167672 Andy McCall 933
        match snap
934
            .statuses
935
            .iter()
936
            .find(|s| s.path == *p)
937
            .map(|s| s.status)
938
        {
fce44ae9 Andy McCall ↶ 939
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
940
            Some(ChangeStatus::ConflictEdited) => {
941
                remaining += 1;
942
                println!("markers    {p}");
943
            }
944
            _ => {
945
                remaining += 1;
946
                println!("unresolved {p}");
947
            }
948
        }
949
    }
950
    for c in &snap.base_snapshot.tree.conflicts {
951
        remaining += 1;
952
        println!("tree       {c:?}");
953
    }
954
    if remaining == 0 {
955
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
956
        Ok(0)
957
    } else {
958
        Ok(2)
959
    }
960
}
961
962
pub fn undo() -> Result<i32> {
963
    let repo = open()?;
964
    let op = repo.undo()?;
94084087 Andy McCall ↶ 965
    println!("{} now at: {}", ui::done("Undone;"), ui::dim(&op.command));
fce44ae9 Andy McCall ↶ 966
    Ok(0)
967
}
968
c6aa5bd9 Andy McCall ↶ 969
pub fn op_log(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 970
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 971
    if as_json {
972
        let ops = repo.op_log()?;
973
        println!(
974
            "{}",
975
            json::arr(ops.iter().enumerate().map(|(i, (r, op))| {
976
                json::obj([
977
                    ("id", json::s(&r.to_hex())),
978
                    ("when_ms", json::n(op.hlc.wall_ms)),
979
                    ("command", json::s(&op.command)),
980
                    ("snapshot", json::b(op.command.ends_with("(snapshot)"))),
981
                    ("current", json::b(i == 0)),
982
                ])
983
            }))
984
        );
985
        return Ok(0);
986
    }
fce44ae9 Andy McCall ↶ 987
    for (i, (r, op)) in repo.op_log()?.into_iter().enumerate() {
75167672 Andy McCall 988
        let bullet = if i == 0 {
989
            ui::ok(ui::glyph("●", "@"))
990
        } else {
991
            ui::dim(ui::glyph("○", "o"))
992
        };
94084087 Andy McCall ↶ 993
        let cmd = subject_of(&op.command).split("\\n").next().unwrap_or("");
75167672 Andy McCall 994
        println!(
995
            "{bullet} {}{}{}  {}",
996
            ui::hash(r.short(12)),
997
            ui::sep(),
998
            ui::dim(format!("{:<16}", ui::ago(op.hlc.wall_ms))),
999
            if i == 0 {
1000
                ui::subject(cmd)
1001
            } else {
1002
                cmd.to_string()
1003
            }
1004
        );
fce44ae9 Andy McCall ↶ 1005
    }
1006
    Ok(0)
1007
}
d02e545d Andy McCall ↶ 1008
ba160f60 Andy McCall ↶ 1009
pub fn gc(now: bool) -> Result<i32> {
d02e545d Andy McCall ↶ 1010
    let repo = open()?;
135212de Andy McCall ↶ 1011
    let sp = ui::spinner("Packing and pruning…");
ba160f60 Andy McCall ↶ 1012
    let r = repo.gc(now)?;
135212de Andy McCall ↶ 1013
    sp.clear();
ba160f60 Andy McCall ↶ 1014
    if r.packed.objects > 0 {
d02e545d Andy McCall ↶ 1015
        println!(
ba160f60 Andy McCall ↶ 1016
            "Packed {}: {} bytes -> {} bytes ({:.0}%).",
1017
            plural(r.packed.objects, "loose object"),
1018
            r.packed.raw_bytes,
1019
            r.packed.packed_bytes,
1020
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
d02e545d Andy McCall ↶ 1021
        );
1022
    }
75167672 Andy McCall 1023
    println!(
1024
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
ba160f60 Andy McCall ↶ 1025
        plural(r.reachable, "object"),
1026
        plural(r.pruned.objects, "unreachable object"),
1027
        r.pruned.bytes,
75167672 Andy McCall 1028
        if r.pruned.deferred > 0 {
1029
            format!(
1030
                "; {} deferred by the grace period (use --now)",
1031
                plural(r.pruned.deferred, "object")
1032
            )
1033
        } else {
1034
            String::new()
1035
        },
1036
        if r.merged_packs > 0 {
1037
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1038
        } else {
1039
            String::new()
1040
        },
ba160f60 Andy McCall ↶ 1041
        plural(repo.store().pack_count(), "pack")
1042
    );
d02e545d Andy McCall ↶ 1043
    Ok(0)
1044
}
614541c3 Andy McCall ↶ 1045
3e5772cc Andy McCall ↶ 1046
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
1047
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1048
    use oxy_core::repo::Health;
1049
    let repo = open()?;
1050
    let sp = ui::spinner(if offline {
1051
        "Checking…"
1052
    } else {
1053
        "Checking, and contacting remotes…"
1054
    });
1055
    let r = repo.doctor(!offline);
1056
    sp.clear();
1057
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
1058
    let word = |h: Health| match h {
1059
        Health::Ok => "ok",
1060
        Health::Warn => "warning",
1061
        Health::Fail => "fail",
1062
    };
1063
    if as_json {
1064
        let checks: Vec<String> = r
1065
            .checks
1066
            .iter()
1067
            .map(|c| {
1068
                json::obj([
1069
                    ("area", json::s(&c.area)),
1070
                    ("health", json::s(word(c.health))),
1071
                    ("message", json::s(&c.message)),
1072
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
1073
                ])
1074
            })
1075
            .collect();
1076
        println!(
1077
            "{}",
1078
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1079
        );
1080
        return Ok(code);
1081
    }
1082
    let mut last = "";
1083
    for c in &r.checks {
1084
        if c.area != last {
1085
            println!("{}", ui::section(&c.area));
1086
            last = &c.area;
1087
        }
1088
        let mark = match c.health {
1089
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
1090
            Health::Warn => ui::caution(),
1091
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1092
        };
1093
        println!("  {mark} {}", c.message);
1094
        if let Some(h) = &c.hint {
1095
            println!("    {} {}", ui::dim("→"), ui::dim(h));
1096
        }
1097
    }
1098
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
1099
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
1100
    if fails + warns == 0 {
1101
        println!("{}", ui::done("Everything looks right."));
1102
    } else {
1103
        println!(
1104
            "{} {}, {}.",
1105
            if fails > 0 {
1106
                ui::err(ui::glyph("✖", "x"))
1107
            } else {
1108
                ui::caution()
1109
            },
1110
            plural(fails, "problem"),
1111
            plural(warns, "warning")
1112
        );
1113
    }
1114
    Ok(code)
1115
}
1116
387335ff Andy McCall ↶ 1117
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
1118
pub fn fsck(as_json: bool) -> Result<i32> {
1119
    use oxy_core::repo::Severity;
1120
    let repo = open()?;
1121
    let sp = ui::spinner("Checking every object…");
1122
    let r = repo.fsck()?;
1123
    sp.clear();
1124
    let code = if r.errors() > 0 { 1 } else { 0 };
1125
    if as_json {
1126
        let problems: Vec<String> = r
1127
            .problems
1128
            .iter()
1129
            .map(|p| {
1130
                json::obj([
1131
                    (
1132
                        "severity",
1133
                        json::s(match p.severity {
1134
                            Severity::Error => "error",
1135
                            Severity::Warning => "warning",
1136
                        }),
1137
                    ),
1138
                    (
1139
                        "object",
1140
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1141
                    ),
1142
                    ("what", json::s(&p.what)),
1143
                ])
1144
            })
1145
            .collect();
1146
        println!(
1147
            "{}",
1148
            json::obj([
1149
                ("ok", json::b(code == 0)),
1150
                ("objects", json::n(r.objects)),
1151
                ("ops", json::n(r.ops)),
1152
                ("changes", json::n(r.changes)),
1153
                ("signed", json::n(r.signed)),
1154
                ("unsigned", json::n(r.unsigned)),
1155
                ("checkpoints", json::n(r.checkpoints)),
1156
                ("attestations", json::n(r.attestations)),
1157
                ("errors", json::n(r.errors())),
1158
                ("warnings", json::n(r.warnings())),
1159
                ("problems", json::arr(problems)),
1160
            ])
1161
        );
1162
        return Ok(code);
1163
    }
1164
    println!(
1165
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
1166
        plural(r.objects, "object"),
1167
        plural(r.ops, "operation"),
1168
        plural(r.changes, "change"),
1169
        r.signed,
1170
        r.unsigned,
1171
        plural(r.checkpoints, "checkpoint"),
1172
        plural(r.attestations, "attestation"),
1173
    );
1174
    for p in &r.problems {
1175
        let obj = p
1176
            .object
1177
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
1178
            .unwrap_or_default();
1179
        match p.severity {
1180
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
1181
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1182
        }
1183
    }
1184
    if r.problems.is_empty() {
1185
        println!("{}", ui::done("No problems found."));
1186
    } else if code == 0 {
1187
        println!(
1188
            "{}",
1189
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
1190
        );
1191
    } else {
1192
        println!(
1193
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
1194
            ui::err(ui::glyph("✖", "x")),
1195
            plural(r.errors(), "error"),
1196
            plural(r.warnings(), "warning")
1197
        );
1198
    }
1199
    Ok(code)
1200
}
1201
79d03f82 Andy McCall ↶ 1202
/// The head the working copy sits on, for commands that default to it. With
1203
/// several heads beneath the working copy, the most recently made one is
1204
/// chosen and announced.
614541c3 Andy McCall ↶ 1205
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
cc7a0056 Andy McCall ↶ 1206
    let snap = repo.snapshot_status("oxy")?;
614541c3 Andy McCall ↶ 1207
    let base = snap.base.maximal(&snap.wc.deps);
1208
    match base.as_slice() {
79d03f82 Andy McCall ↶ 1209
        [] => anyhow::bail!("the working copy sits on no change yet"),
614541c3 Andy McCall ↶ 1210
        [h] => Ok(*h),
79d03f82 Andy McCall ↶ 1211
        many => {
1212
            let latest = many
1213
                .iter()
1214
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
1215
                .copied()
1216
                .unwrap();
1217
            let c = repo.store().get_change(&latest)?;
75167672 Andy McCall 1218
            println!(
1219
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
1220
                short_id(&c),
1221
                latest.short(12),
1222
                many.len()
1223
            );
79d03f82 Andy McCall ↶ 1224
            Ok(latest)
1225
        }
614541c3 Andy McCall ↶ 1226
    }
1227
}
1228
6a81dbab Andy McCall ↶ 1229
/// `oxy describe` without -m: the working copy's name for a build.
1230
pub fn describe_name(as_json: bool) -> Result<i32> {
1231
    let repo = open()?;
1232
    let d = repo.describe_working_copy()?;
1233
    if as_json {
1234
        println!(
1235
            "{}",
1236
            json::obj([
1237
                ("describe", json::s(&d.line())),
1238
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
1239
                ("distance", json::n(d.distance)),
1240
                ("bookmark", json::s(&d.bookmark)),
1241
                ("change", json::s(&d.change.to_hex())),
1242
                ("hash", json::s(&d.hash.to_hex())),
1243
                ("dirty", json::b(d.dirty)),
1244
            ])
1245
        );
1246
    } else {
1247
        println!("{}", d.line());
1248
    }
1249
    Ok(0)
1250
}
1251
614541c3 Andy McCall ↶ 1252
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
1253
    let repo = open()?;
1254
    let h = match change {
1255
        Some(c) => repo.resolve_change(c)?,
1256
        None => current_head(&repo)?,
1257
    };
1258
    let new = repo.describe(&h, message)?;
1259
    let c = repo.store().get_change(&new)?;
75167672 Andy McCall 1260
    println!(
1261
        "{} {} {}  {}",
1262
        ui::done("Described"),
1263
        ui::id(short_id(&c)),
1264
        ui::hash(format!("#{}", new.short(12))),
1265
        ui::subject(subject_of(message))
1266
    );
614541c3 Andy McCall ↶ 1267
    Ok(0)
1268
}
1269
23b217d7 Andy McCall ↶ 1270
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
614541c3 Andy McCall ↶ 1271
    let repo = open()?;
23b217d7 Andy McCall ↶ 1272
    let new = match into {
1273
        Some(spec) => {
1274
            let target = repo.resolve_change(spec)?;
1275
            repo.amend_into(&target, message)?
1276
        }
1277
        None => repo.amend(message)?,
1278
    };
614541c3 Andy McCall ↶ 1279
    let c = repo.store().get_change(&new)?;
75167672 Andy McCall 1280
    println!(
1281
        "{} {} {}  {}",
1282
        ui::done("Amended"),
1283
        ui::id(short_id(&c)),
1284
        ui::hash(format!("#{}", new.short(12))),
1285
        ui::subject(subject_of(&c.message))
1286
    );
614541c3 Andy McCall ↶ 1287
    Ok(0)
1288
}
1289
1290
pub fn abandon(change: &str) -> Result<i32> {
1291
    let repo = open()?;
1292
    let h = repo.resolve_change(change)?;
1293
    let c = repo.store().get_change(&h)?;
6706bdcf Andy McCall ↶ 1294
    let notes = repo.abandon(&h)?;
75167672 Andy McCall 1295
    println!(
1296
        "{} {} {}  {}",
1297
        ui::done("Abandoned"),
1298
        ui::id(short_id(&c)),
1299
        ui::hash(format!("#{}", h.short(12))),
1300
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
1301
    );
6706bdcf Andy McCall ↶ 1302
    for n in notes {
94084087 Andy McCall ↶ 1303
        println!("  {} {n}", ui::note());
6706bdcf Andy McCall ↶ 1304
    }
614541c3 Andy McCall ↶ 1305
    Ok(0)
1306
}
252e8cb2 Andy McCall ↶ 1307
1308
pub fn checkpoint() -> Result<i32> {
1309
    let repo = open()?;
135212de Andy McCall ↶ 1310
    let sp = ui::spinner("Writing checkpoint…");
252e8cb2 Andy McCall ↶ 1311
    let (r, changes, bytes) = repo.checkpoint()?;
75167672 Andy McCall 1312
    sp.done(&format!(
1313
        "{} {} of {} ({} bytes) for {}",
1314
        ui::done("Checkpoint"),
1315
        ui::hash(format!("#{}", r.short(12))),
1316
        plural(changes, "change"),
1317
        bytes,
1318
        ui::id(&repo.config.bookmark)
1319
    ));
135212de Andy McCall ↶ 1320
    Ok(0)
1321
}
1322
1323
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
694805cc Andy McCall ↶ 1324
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
75167672 Andy McCall 1325
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
1326
        return Ok(1);
1327
    };
135212de Andy McCall ↶ 1328
    let info = repo.quick_status()?;
75167672 Andy McCall 1329
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
1330
        oxy_core::repo::GLYPH_PROMPT_FORMAT
1331
    } else {
1332
        format
1333
    };
694805cc Andy McCall ↶ 1334
    let line = match color {
1335
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
1336
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
1337
        Some(_) => info.format_colored(fmt, ("", "")),
1338
        None => info.format(fmt),
1339
    };
1340
    println!("{line}");
252e8cb2 Andy McCall ↶ 1341
    Ok(0)
1342
}
7421309f Andy McCall ↶ 1343
1344
pub fn sparse(paths: &[String]) -> Result<i32> {
1345
    let mut repo = open()?;
1346
    if paths.is_empty() {
1347
        if repo.config.sparse_paths.is_empty() {
1348
            println!("No sparse filter: the whole tree is materialized.");
1349
        } else {
1350
            println!("{}", ui::heading("Sparse filter"));
1351
            for p in &repo.config.sparse_paths {
1352
                println!("  {}", ui::path(p));
1353
            }
1354
        }
1355
        return Ok(0);
1356
    }
1357
    let snap = repo.snapshot("oxy sparse")?;
1358
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
75167672 Andy McCall 1359
        anyhow::bail!(
1360
            "the working copy has changes; commit them before changing the sparse filter"
1361
        );
7421309f Andy McCall ↶ 1362
    }
1363
    repo.config.set("filter.paths", &paths.join(","))?;
1364
    repo.save_config()?;
1365
    let heads = repo.bookmark_heads()?;
1366
    let sp = ui::spinner("Re-checking out with the new filter…");
1367
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
75167672 Andy McCall 1368
    sp.done(&format!(
1369
        "{} {}: {} written, {} removed",
1370
        ui::ok("Sparse filter set to"),
1371
        ui::path(paths.join(",")),
1372
        plural(r.written, "file"),
1373
        r.removed
1374
    ));
7421309f Andy McCall ↶ 1375
    Ok(0)
1376
}
132b884b Andy McCall ↶ 1377
1378
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
1379
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1380
    repo.snapshot_status("oxy tag")?;
132b884b Andy McCall ↶ 1381
    let heads = if changes.is_empty() {
1382
        repo.bookmark_heads()?
1383
    } else {
1384
        let mut heads = Vec::new();
1385
        for c in changes {
1386
            heads.extend(repo.resolve_heads(c)?);
1387
        }
1388
        heads
1389
    };
1390
    let t = repo.tag_create(name, &heads, message)?;
1391
    println!(
94084087 Andy McCall ↶ 1392
        "{} {} {} {} ({}){}",
1393
        ui::done("Tagged"),
1394
        ui::bookmark(&t.name),
1395
        ui::dim(ui::glyph("→", "->")),
132b884b Andy McCall ↶ 1396
        ui::hash(format!("#{}", t.state.short(12))),
1397
        plural(t.heads.len(), "head"),
75167672 Andy McCall 1398
        t.signer
1399
            .map(|s| format!(", signed by {s}"))
1400
            .unwrap_or_else(|| ui::dim(", unsigned"))
132b884b Andy McCall ↶ 1401
    );
1402
    Ok(0)
1403
}
1404
1196b29b Andy McCall ↶ 1405
pub fn tag_list(as_json: bool) -> Result<i32> {
132b884b Andy McCall ↶ 1406
    let repo = open()?;
1407
    let tags = repo.tags()?;
1196b29b Andy McCall ↶ 1408
    if as_json {
1409
        println!(
1410
            "{}",
1411
            json::arr(tags.iter().map(|t| {
1412
                json::obj([
1413
                    ("name", json::s(&t.name)),
1414
                    ("state", json::s(&t.state.to_hex())),
1415
                    ("heads", json::hashes(&t.heads)),
1416
                    ("message", json::s(&t.message)),
75167672 Andy McCall 1417
                    (
1418
                        "signer",
1419
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
1420
                    ),
1196b29b Andy McCall ↶ 1421
                ])
1422
            }))
1423
        );
1424
        return Ok(0);
1425
    }
132b884b Andy McCall ↶ 1426
    if tags.is_empty() {
1427
        println!("{}", ui::dim("No tags."));
1428
    }
1429
    for t in tags {
1430
        println!(
94084087 Andy McCall ↶ 1431
            "{} {} {}{}{}{}",
1432
            ui::ok(ui::glyph("⚑", "#")),
1433
            ui::bookmark(&t.name),
6a81dbab Andy McCall ↶ 1434
            // The heads, as `oxy log` shows changes, not the state hash.
1435
            ui::hash(
1436
                t.heads
1437
                    .iter()
1438
                    .map(|h| format!("#{}", h.short(12)))
1439
                    .collect::<Vec<_>>()
1440
                    .join(" ")
1441
            ),
94084087 Andy McCall ↶ 1442
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
75167672 Andy McCall 1443
            if t.message.is_empty() {
1444
                String::new()
1445
            } else {
1446
                format!("  {}", ui::subject(subject_of(&t.message)))
1447
            },
1448
            t.signer
1449
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
1450
                .unwrap_or_default()
132b884b Andy McCall ↶ 1451
        );
1452
    }
1453
    Ok(0)
1454
}
4e88e774 Andy McCall ↶ 1455
1456
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
1457
    let repo = open()?;
1458
    let heads = if changes.is_empty() {
1459
        None
1460
    } else {
1461
        let mut heads = Vec::new();
1462
        for c in changes {
1463
            heads.extend(repo.resolve_heads(c)?);
1464
        }
1465
        Some(heads)
1466
    };
1467
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
1468
    let ws = repo.workspace_add(path, heads.as_deref())?;
75167672 Andy McCall 1469
    sp.done(&format!(
1470
        "{} {} (workspace {})",
1471
        ui::done("Workspace created at"),
1472
        ui::path(ws.root().display()),
1473
        ui::id(ws.workspace().short(8))
1474
    ));
4e88e774 Andy McCall ↶ 1475
    Ok(0)
1476
}
1477
1196b29b Andy McCall ↶ 1478
pub fn workspace_list(as_json: bool) -> Result<i32> {
4e88e774 Andy McCall ↶ 1479
    let repo = open()?;
1196b29b Andy McCall ↶ 1480
    if as_json {
1481
        println!(
1482
            "{}",
1483
            json::arr(repo.workspaces()?.iter().map(|w| {
1484
                json::obj([
1485
                    ("id", json::s(&w.id.to_hex())),
1486
                    ("path", json::s(&w.path.to_string_lossy())),
1487
                    ("current", json::b(w.current)),
75167672 Andy McCall 1488
                    (
1489
                        "working_copy",
1490
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
1491
                    ),
1196b29b Andy McCall ↶ 1492
                ])
1493
            }))
1494
        );
1495
        return Ok(0);
1496
    }
4e88e774 Andy McCall ↶ 1497
    for w in repo.workspaces()? {
1498
        println!(
1499
            "{} {} {}{}",
75167672 Andy McCall 1500
            if w.current {
1501
                ui::ok(ui::glyph("●", "*"))
1502
            } else {
1503
                ui::dim(ui::glyph("○", "o"))
1504
            },
4e88e774 Andy McCall ↶ 1505
            ui::id(w.id.short(8)),
1506
            ui::path(w.path.display()),
75167672 Andy McCall 1507
            w.working_copy
1508
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
1509
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
4e88e774 Andy McCall ↶ 1510
        );
1511
    }
1512
    Ok(0)
1513
}
1514
1515
pub fn workspace_forget(spec: &str) -> Result<i32> {
1516
    let repo = open()?;
1517
    let all = repo.workspaces()?;
1518
    let target = std::fs::canonicalize(spec).ok();
75167672 Andy McCall 1519
    let matches: Vec<_> = all
1520
        .iter()
1521
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
1522
        .collect();
4e88e774 Andy McCall ↶ 1523
    let w = match matches.as_slice() {
1524
        [w] => *w,
1525
        [] => anyhow::bail!("no workspace matches {spec:?}"),
1526
        _ => anyhow::bail!("{spec:?} is ambiguous"),
1527
    };
1528
    repo.workspace_forget(&w.id)?;
75167672 Andy McCall 1529
    println!(
1530
        "{} workspace {} at {}; its files were left in place.",
1531
        ui::done("Forgot"),
1532
        ui::id(w.id.short(8)),
1533
        ui::path(w.path.display())
1534
    );
4e88e774 Andy McCall ↶ 1535
    Ok(0)
1536
}
cdb5beba Andy McCall ↶ 1537
1538
pub fn lock(path: &str) -> Result<i32> {
1539
    let repo = open()?;
1540
    repo.lock_path(path)?;
75167672 Andy McCall 1541
    println!(
1542
        "{} {} {}",
1543
        ui::done("Locked"),
1544
        ui::path(path),
1545
        ui::dim("(advisory, local)")
1546
    );
cdb5beba Andy McCall ↶ 1547
    Ok(0)
1548
}
1549
1550
pub fn unlock(path: &str) -> Result<i32> {
1551
    let repo = open()?;
1552
    repo.unlock_path(path)?;
94084087 Andy McCall ↶ 1553
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
cdb5beba Andy McCall ↶ 1554
    Ok(0)
1555
}
23b217d7 Andy McCall ↶ 1556
1557
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
1558
    let repo = open()?;
1559
    let h = repo.resolve_change(change)?;
1560
    let (h1, h2) = repo.split(&h, paths)?;
1561
    let c1 = repo.store().get_change(&h1)?;
1562
    let c2 = repo.store().get_change(&h2)?;
75167672 Andy McCall 1563
    println!(
1564
        "{} into {} {} and {} {}",
1565
        ui::done("Split"),
1566
        ui::id(short_id(&c1)),
1567
        ui::hash(format!("#{}", h1.short(12))),
1568
        ui::id(short_id(&c2)),
1569
        ui::hash(format!("#{}", h2.short(12)))
1570
    );
23b217d7 Andy McCall ↶ 1571
    Ok(0)
1572
}
7b9809e6 Andy McCall ↶ 1573
1574
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
1575
    let mut heads = Vec::new();
1576
    for c in changes {
1577
        heads.extend(repo.resolve_heads(c)?);
1578
    }
1579
    Ok(heads)
1580
}
1581
1582
pub fn bookmark_create(name: &str, changes: &[String]) -> Result<i32> {
1583
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1584
    repo.snapshot_status("oxy bookmark create")?;
75167672 Andy McCall 1585
    let heads = if changes.is_empty() {
1586
        None
1587
    } else {
1588
        Some(heads_from(&repo, changes)?)
1589
    };
7b9809e6 Andy McCall ↶ 1590
    let heads = repo.bookmark_create(name, heads.as_deref())?;
75167672 Andy McCall 1591
    println!(
1592
        "{} bookmark {} {} {}",
1593
        ui::done("Created"),
1594
        ui::bookmark(name),
1595
        ui::dim(ui::glyph("→", "->")),
1596
        ui::dim(plural(heads.len(), "head"))
1597
    );
1598
    println!(
1599
        "  {} {}",
1600
        ui::note(),
1601
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
1602
    );
7b9809e6 Andy McCall ↶ 1603
    Ok(0)
1604
}
1605
1606
pub fn bookmark_set(name: &str, changes: &[String]) -> Result<i32> {
1607
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1608
    repo.snapshot_status("oxy bookmark set")?;
7b9809e6 Andy McCall ↶ 1609
    let heads = heads_from(&repo, changes)?;
1610
    let heads = repo.bookmark_set(name, &heads)?;
75167672 Andy McCall 1611
    println!(
1612
        "{} bookmark {} {} {}",
1613
        ui::done("Moved"),
1614
        ui::bookmark(name),
1615
        ui::dim(ui::glyph("→", "->")),
1616
        ui::dim(plural(heads.len(), "head"))
1617
    );
7b9809e6 Andy McCall ↶ 1618
    Ok(0)
1619
}
1620
1621
pub fn bookmark_delete(name: &str) -> Result<i32> {
1622
    let repo = open()?;
1623
    repo.bookmark_delete(name)?;
75167672 Andy McCall 1624
    println!(
1625
        "{} bookmark {} {}",
1626
        ui::done("Deleted"),
1627
        ui::bookmark(name),
1628
        ui::dim("(its changes stay until unreachable)")
1629
    );
7b9809e6 Andy McCall ↶ 1630
    Ok(0)
1631
}
1632
c6aa5bd9 Andy McCall ↶ 1633
pub fn bookmark_list(as_json: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 1634
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 1635
    if as_json {
1636
        let items = repo.bookmarks()?.into_iter().map(|b| {
1637
            json::obj([
1638
                ("name", json::s(&b.name)),
1639
                ("heads", json::hashes(&b.heads)),
1640
                ("current", json::b(b.current)),
1641
                ("ahead", json::opt(b.ahead, json::n)),
1642
                ("behind", json::opt(b.behind, json::n)),
1643
            ])
1644
        });
1645
        println!("{}", json::arr(items));
1646
        return Ok(0);
1647
    }
7b9809e6 Andy McCall ↶ 1648
    for b in repo.bookmarks()? {
75167672 Andy McCall 1649
        let mark = if b.current {
1650
            ui::ok(ui::glyph("●", "*"))
1651
        } else {
1652
            ui::dim(ui::glyph("○", "o"))
1653
        };
7b9809e6 Andy McCall ↶ 1654
        let mut tail = String::new();
1655
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
1656
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
1657
        }
1658
        if let Some(n) = b.behind.filter(|n| *n > 0) {
1659
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
1660
        }
75167672 Andy McCall 1661
        let head = b
1662
            .heads
1663
            .first()
1664
            .map(|h| {
1665
                repo.store()
1666
                    .get_change(h)
1667
                    .map(|c| ui::subject(subject_of(&c.message)))
1668
                    .unwrap_or_default()
1669
            })
1670
            .unwrap_or_else(|| ui::dim("(empty)"));
1671
        println!(
1672
            "{mark} {}{}{}{tail}  {head}",
1673
            ui::bookmark(&b.name),
1674
            ui::sep(),
1675
            ui::dim(plural(b.heads.len(), "head"))
1676
        );
7b9809e6 Andy McCall ↶ 1677
    }
1678
    Ok(0)
1679
}
1680
61e3bce7 Andy McCall ↶ 1681
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 1682
    let mut repo = open()?;
1683
    let sp = ui::spinner(&format!("Switching to {name}…"));
61e3bce7 Andy McCall ↶ 1684
    let (r, carried) = if carry {
1685
        repo.bookmark_switch_carry(name)?
1686
    } else {
1687
        (repo.bookmark_switch(name, discard)?, vec![])
1688
    };
75167672 Andy McCall 1689
    sp.done(&format!(
61e3bce7 Andy McCall ↶ 1690
        "{} to {}: {} written, {} removed{}",
75167672 Andy McCall 1691
        ui::done("Switched"),
1692
        ui::bookmark(name),
1693
        plural(r.written, "file"),
61e3bce7 Andy McCall ↶ 1694
        r.removed,
1695
        if carried.is_empty() {
1696
            String::new()
1697
        } else {
1698
            format!("; carried {}", plural(carried.len(), "changed path"))
1699
        }
75167672 Andy McCall 1700
    ));
7b9809e6 Andy McCall ↶ 1701
    if r.conflicted {
75167672 Andy McCall 1702
        println!(
1703
            "  {} {}",
1704
            ui::caution(),
1705
            ui::warn("this state has conflicts; see oxy status")
1706
        );
7b9809e6 Andy McCall ↶ 1707
    }
1708
    Ok(0)
1709
}
1710
1711
pub fn merge(bookmark: &str) -> Result<i32> {
1712
    let repo = open()?;
1713
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
1714
    let r = repo.merge(bookmark)?;
1715
    if !r.changed {
75167672 Andy McCall 1716
        sp.done(&format!(
1717
            "{} {}",
1718
            ui::ok(ui::glyph("✔", "*")),
1719
            ui::dim(format!(
1720
                "{} already contains {bookmark}",
1721
                repo.config.bookmark
1722
            ))
1723
        ));
7b9809e6 Andy McCall ↶ 1724
        return Ok(0);
1725
    }
1726
    sp.done(&format!(
1727
        "{} {} into {}: now {}{}",
1728
        ui::done("Merged"),
1729
        ui::bookmark(bookmark),
1730
        ui::bookmark(&repo.config.bookmark),
1731
        plural(r.heads.len(), "head"),
75167672 Andy McCall 1732
        ui::dim(if r.checked_out {
1733
            "; working copy updated"
1734
        } else {
1735
            "; run oxy checkout to update the working copy"
1736
        })
7b9809e6 Andy McCall ↶ 1737
    ));
1738
    let snap = repo.snapshot("oxy merge")?;
1739
    if snap.base_snapshot.is_conflicted() {
75167672 Andy McCall 1740
        println!(
1741
            "  {} {}",
1742
            ui::caution(),
1743
            ui::warn("the result has conflicts; see oxy status")
1744
        );
7b9809e6 Andy McCall ↶ 1745
    }
1746
    Ok(0)
1747
}
1748
728da0f9 Andy McCall ↶ 1749
pub fn squash(change: &str, into: &str) -> Result<i32> {
1750
    let repo = open()?;
1751
    let c = repo.resolve_change(change)?;
1752
    let d = repo.resolve_change(into)?;
1753
    let sp = ui::spinner("Squashing…");
1754
    let h = repo.squash(&c, &d)?;
1755
    let new = repo.store().get_change(&h)?;
75167672 Andy McCall 1756
    sp.done(&format!(
1757
        "{} into {} {}  {}",
1758
        ui::done("Squashed"),
1759
        ui::id(short_id(&new)),
1760
        ui::hash(format!("#{}", h.short(12))),
1761
        ui::subject(subject_of(&new.message))
1762
    ));
728da0f9 Andy McCall ↶ 1763
    Ok(0)
1764
}
1765
1766
pub fn rebase(change: &str, onto: &[String]) -> Result<i32> {
1767
    let repo = open()?;
1768
    let c = repo.resolve_change(change)?;
1769
    let mut heads = Vec::new();
1770
    for o in onto {
1771
        heads.extend(repo.resolve_heads(o)?);
1772
    }
1773
    let sp = ui::spinner("Rebasing…");
1774
    let h = repo.rebase(&c, &heads)?;
1775
    let new = repo.store().get_change(&h)?;
75167672 Andy McCall 1776
    sp.done(&format!(
1777
        "{} {} {}  {}",
1778
        ui::done("Rebased"),
1779
        ui::id(short_id(&new)),
1780
        ui::hash(format!("#{}", h.short(12))),
1781
        ui::dim(format!(
1782
            "now depends on {}",
1783
            plural(new.deps.len(), "change")
1784
        ))
1785
    ));
728da0f9 Andy McCall ↶ 1786
    Ok(0)
1787
}