OXYGENHUB
# 141b1fb2ebe9 oxygen / src / cli / workspace.rs
46.5 KiB · Rust · last changed Build identity in oxy --version 1 month ago source blame history raw
1
//! Commands that act on the local repository and working copy.
2
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
};
7
use super::json;
8
use super::open;
9
use super::ui;
10
use anyhow::Result;
11
use oxy_core::objects::ChangeKind;
12
use oxy_core::repo::SignatureStatus;
13
use oxy_core::repo::{render_change, ChangeStatus, Repo};
14
use std::path::PathBuf;
15
16
pub fn init(path: Option<PathBuf>, bare: bool) -> Result<i32> {
17
    let path = path.unwrap_or(std::env::current_dir()?);
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
    );
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",
52
        ChangeStatus::Renamed => "R",
53
        ChangeStatus::ModeChanged => "X",
54
        ChangeStatus::ConflictEdited => "C!",
55
        ChangeStatus::Resolved => "V",
56
    }
57
}
58
59
pub fn status(json: bool) -> Result<i32> {
60
    let repo = open()?;
61
    let sp = ui::spinner("Snapshotting the working copy…");
62
    let snap = repo.snapshot("oxy status")?;
63
    let heads = repo.bookmark_heads()?;
64
    sp.clear();
65
    if json {
66
        println!("{}", repo.status_json(&snap)?);
67
        return Ok(if snap.base_snapshot.is_conflicted() {
68
            2
69
        } else {
70
            0
71
        });
72
    }
73
    println!(
74
        "{} {}{}working copy {}{}{}",
75
        ui::dim("On"),
76
        ui::bookmark(&repo.config.bookmark),
77
        ui::sep(),
78
        ui::id(snap.wc.change_id.short(8)),
79
        ui::sep(),
80
        ui::dim(plural(heads.len(), "head"))
81
    );
82
    if snap.statuses.is_empty() {
83
        println!(
84
            "  {} {}",
85
            ui::ok(ui::glyph("✔", "*")),
86
            ui::dim("nothing to commit, working copy clean")
87
        );
88
    } else {
89
        println!();
90
        for s in &snap.statuses {
91
            println!(
92
                "  {} {}",
93
                ui::status_mark(status_tag(s.status)),
94
                ui::path(&s.path)
95
            );
96
        }
97
    }
98
    if !snap.base_snapshot.is_conflicted() {
99
        return Ok(0);
100
    }
101
    println!();
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
    );
107
    for c in &snap.base_snapshot.tree.conflicts {
108
        println!("  {} tree: {c:?}", ui::err(ui::glyph("✱", "!")));
109
    }
110
    for (p, f) in &snap.base_snapshot.files {
111
        if f.is_conflicted() {
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
                }
124
                _ => ui::err(format!("{} unresolved", ui::glyph("✱", "!"))),
125
            };
126
            println!("  {}  {state}", ui::path(p));
127
        }
128
    }
129
    Ok(2)
130
}
131
132
pub fn commit(
133
    message: &str,
134
    depends_on: &[String],
135
    paths: &[String],
136
    interactive: bool,
137
    hunks: &[usize],
138
) -> Result<i32> {
139
    let repo = open()?;
140
    let mut deps = Vec::new();
141
    for d in depends_on {
142
        deps.push(repo.resolve_change(d)?);
143
    }
144
    let selection = if !hunks.is_empty() {
145
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
146
    } else if interactive {
147
        let (_, hunks) = repo.hunks()?;
148
        if hunks.is_empty() {
149
            anyhow::bail!("nothing to commit: the working copy matches its base");
150
        }
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();
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
            }
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
            );
174
            for line in h.text.lines() {
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
                };
182
                println!("  {styled}");
183
            }
184
            loop {
185
                print!(
186
                    "{} ",
187
                    ui::warn("Commit this hunk? [y]es [n]o [a]ll remaining [q]uit:")
188
                );
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
    };
220
    let sp = ui::spinner("Committing…");
221
    let h = repo.commit_selection(message, &deps, &selection)?;
222
    let c = repo.store().get_change(&h)?;
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
    ));
230
    if !matches!(selection, oxy_core::repo::Selection::All) {
231
        let rest = repo.snapshot("oxy commit")?;
232
        if !rest.statuses.is_empty() {
233
            println!(
234
                "  {} {}",
235
                ui::note(),
236
                ui::dim(format!(
237
                    "{} left uncommitted",
238
                    plural(rest.statuses.len(), "path")
239
                ))
240
            );
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
    }
264
    let width = lines
265
        .iter()
266
        .map(|l| l.author.chars().count())
267
        .max()
268
        .unwrap_or(0)
269
        .min(20);
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 } => {
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
            );
301
            Ok(0)
302
        }
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
            );
324
            Ok(0)
325
        }
326
        Found { culprit } => {
327
            let c = repo.store().get_change(culprit)?;
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
            );
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 } => {
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
            );
347
            Ok(1)
348
        }
349
    }
350
}
351
352
pub fn bisect_start() -> Result<i32> {
353
    let repo = open()?;
354
    repo.bisect_start()?;
355
    println!(
356
        "{} bisect; {}",
357
        ui::done("Started"),
358
        ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE")
359
    );
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
379
pub fn bisect_status(as_json: bool) -> Result<i32> {
380
    let repo = open()?;
381
    if as_json {
382
        use oxy_core::repo::BisectStep::*;
383
        let v = match repo.bisect_status()? {
384
            None => "null".to_string(),
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
            ]),
408
        };
409
        println!("{v}");
410
        return Ok(0);
411
    }
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"));
425
    Ok(0)
426
}
427
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.
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"))]),
434
        SignatureStatus::Valid {
435
            key,
436
            name,
437
            email,
438
            sealed,
439
            revoked,
440
        } => json::obj([
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
        ]),
447
        SignatureStatus::Invalid(why) => {
448
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
449
        }
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)),
466
        (
467
            "signature",
468
            if e.is_working_copy {
469
                "null".into()
470
            } else {
471
                signature_json(repo, &e.hash)?
472
            },
473
        ),
474
    ]))
475
}
476
477
pub fn log(limit: Option<usize>, verbose: bool, path: Option<&str>, as_json: bool) -> Result<i32> {
478
    let repo = open()?;
479
    let snap = repo.snapshot("oxy log")?;
480
    let conflicted = snap.base_snapshot.is_conflicted();
481
    let entries = match path {
482
        Some(p) => repo.log_for_path(p)?,
483
        None => repo.log()?,
484
    };
485
    if as_json {
486
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
487
        let mut items = Vec::new();
488
        for e in entries.iter().take(shown) {
489
            items.push(log_entry_json(&repo, e)?);
490
        }
491
        println!(
492
            "{}",
493
            json::obj([
494
                ("bookmark", json::s(&repo.config.bookmark)),
495
                ("total", json::n(entries.len())),
496
                ("changes", json::arr(items))
497
            ])
498
        );
499
        return Ok(0);
500
    }
501
    let total = entries.len();
502
    let shown = limit.unwrap_or(total).min(total);
503
    let rail = ui::rail();
504
    for (i, e) in entries.iter().take(shown).enumerate() {
505
        let c = &e.change;
506
        let bullet = ui::log_bullet(
507
            e.is_working_copy,
508
            e.is_head,
509
            e.is_working_copy && conflicted,
510
        );
511
        let mut labels = Vec::new();
512
        if e.is_working_copy {
513
            labels.push(ui::warn("working copy"));
514
        }
515
        if c.kind == ChangeKind::Resolution {
516
            labels.push(ui::warn("resolution"));
517
        }
518
        let labels = if labels.is_empty() {
519
            String::new()
520
        } else {
521
            format!(
522
                " {}{}{}",
523
                ui::dim("("),
524
                labels.join(ui::dim(", ").as_str()),
525
                ui::dim(")")
526
            )
527
        };
528
        let subject = if e.is_working_copy && c.message.is_empty() {
529
            ui::dim(if snap.statuses.is_empty() {
530
                "(clean)"
531
            } else {
532
                "(uncommitted changes)"
533
            })
534
        } else {
535
            ui::subject(subject_of(&c.message))
536
        };
537
        println!("{bullet} {}{labels}  {subject}", ui::id(short_meta_id(c)));
538
        let meta = format!(
539
            "{}{}{}{}{}{}{}",
540
            ui::hash(format!("#{}", e.hash.short(12))),
541
            ui::sep(),
542
            ui::author(author_name(&repo, c)),
543
            ui::sep(),
544
            ui::dim(ui::ago(c.hlc.wall_ms)),
545
            ui::sep(),
546
            if e.is_working_copy {
547
                ui::dim("not yet committed")
548
            } else {
549
                signature_mark(&repo, &e.hash)?
550
            }
551
        );
552
        println!("{rail} {meta}");
553
        if verbose {
554
            if !e.is_working_copy {
555
                println!(
556
                    "{rail} {}",
557
                    ui::dim(format!(
558
                        "{} {}",
559
                        when(c.hlc.wall_ms),
560
                        signature_line(&repo, &e.hash)?
561
                    ))
562
                );
563
            }
564
            if !c.deps.is_empty() {
565
                println!(
566
                    "{rail} {} {}",
567
                    ui::dim(ui::glyph("↳", "->")),
568
                    ui::dim(deps_of(&c.deps))
569
                );
570
            }
571
            let body: Vec<&str> = c
572
                .message
573
                .lines()
574
                .skip(1)
575
                .skip_while(|l| l.trim().is_empty())
576
                .collect();
577
            if !body.is_empty() {
578
                println!("{rail}");
579
                for line in body {
580
                    println!("{rail}   {line}");
581
                }
582
            }
583
        }
584
        if i + 1 < shown {
585
            println!("{rail}");
586
        }
587
    }
588
    if shown < total {
589
        println!(
590
            "{}",
591
            ui::dim(format!(
592
                "{} {} more; pass -n to see them",
593
                ui::glyph("…", "..."),
594
                total - shown
595
            ))
596
        );
597
    }
598
    Ok(0)
599
}
600
601
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
602
    let repo = open()?;
603
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
604
    if as_json {
605
        let files = repo.diff_files(hash.as_ref())?;
606
        let items = files.iter().map(|f| {
607
            json::obj([
608
                ("path", json::s(&f.path)),
609
                ("kind", json::s(&f.kind)),
610
                ("from", json::opt(f.from.as_deref(), json::s)),
611
                (
612
                    "hunks",
613
                    json::arr(f.hunks.iter().map(|h| {
614
                        json::obj([
615
                            ("base_line", json::n(h.base_line)),
616
                            (
617
                                "added",
618
                                json::arr(
619
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
620
                                ),
621
                            ),
622
                            (
623
                                "removed",
624
                                json::arr(h.removed.iter().map(|(n, l)| {
625
                                    json::obj([
626
                                        ("line", json::n(*n)),
627
                                        ("text", json::s(&String::from_utf8_lossy(l))),
628
                                    ])
629
                                })),
630
                            ),
631
                        ])
632
                    })),
633
                ),
634
            ])
635
        });
636
        println!(
637
            "{}",
638
            json::obj([
639
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
640
                ("files", json::arr(items))
641
            ])
642
        );
643
        return Ok(0);
644
    }
645
    match hash {
646
        Some(h) => {
647
            let c = repo.store().get_change(&h)?;
648
            let base = repo.load_state(&c.deps)?;
649
            let snapshot = base.materialize();
650
            print!("{}", render_change(&c, &base, &snapshot));
651
        }
652
        None => {
653
            let snap = repo.snapshot("oxy diff")?;
654
            print!(
655
                "{}",
656
                render_change(&snap.wc, &snap.base, &snap.base_snapshot)
657
            );
658
        }
659
    }
660
    Ok(0)
661
}
662
663
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
664
    let repo = open()?;
665
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
666
    let bytes = repo.file_at(path, heads.as_deref())?;
667
    use std::io::Write as _;
668
    std::io::stdout().write_all(&bytes)?;
669
    Ok(0)
670
}
671
672
pub fn root(as_json: bool) -> Result<i32> {
673
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
674
        if as_json {
675
            println!("null");
676
        }
677
        return Ok(1);
678
    };
679
    if as_json {
680
        println!(
681
            "{}",
682
            json::obj([
683
                ("root", json::s(&repo.root().to_string_lossy())),
684
                ("workspace", json::s(&repo.workspace().to_hex())),
685
                ("bookmark", json::s(&repo.config.bookmark))
686
            ])
687
        );
688
    } else {
689
        println!("{}", repo.root().display());
690
    }
691
    Ok(0)
692
}
693
694
pub fn version(as_json: bool) -> Result<i32> {
695
    if as_json {
696
        println!(
697
            "{}",
698
            json::obj([
699
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
700
                // What was built: a release's or install's `oxy describe`,
701
                // a Flow build's heads, or "local build".
702
                ("build", json::s(env!("OXY_BUILD_ID"))),
703
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
704
                ("format", json::n(2))
705
            ])
706
        );
707
    } else {
708
        println!(
709
            "oxy {} (repository format 2, protocol {})",
710
            env!("OXY_VERSION_LONG"),
711
            oxy_core::protocol::PROTOCOL_VERSION
712
        );
713
    }
714
    Ok(0)
715
}
716
717
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
718
    let repo = open()?;
719
    if paths.is_empty() && hunks.is_empty() {
720
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
721
    }
722
    let mut n = 0;
723
    if !hunks.is_empty() {
724
        n += repo.discard_hunks(hunks)?;
725
    }
726
    if !paths.is_empty() {
727
        n += repo.discard(paths)?;
728
    }
729
    println!(
730
        "{} {} restored to the working copy's base",
731
        ui::done("Discarded"),
732
        plural(n, "path")
733
    );
734
    Ok(0)
735
}
736
737
pub fn hunks(as_json: bool) -> Result<i32> {
738
    let repo = open()?;
739
    let (_, hunks) = repo.hunks()?;
740
    if as_json {
741
        println!(
742
            "{}",
743
            json::arr(hunks.iter().map(|h| json::obj([
744
                ("index", json::n(h.index)),
745
                ("path", json::s(&h.path)),
746
                ("text", json::s(&h.text))
747
            ])))
748
        );
749
        return Ok(0);
750
    }
751
    if hunks.is_empty() {
752
        println!(
753
            "{}",
754
            ui::dim("No hunks: the working copy matches its base.")
755
        );
756
    }
757
    for h in &hunks {
758
        println!(
759
            "{} {}",
760
            ui::section(format!("hunk {}", h.index)),
761
            ui::path(&h.path)
762
        );
763
        for line in h.text.lines() {
764
            let styled = if line.starts_with('+') {
765
                ui::ok(line)
766
            } else if line.starts_with('-') {
767
                ui::err(line)
768
            } else {
769
                ui::dim(line)
770
            };
771
            println!("  {styled}");
772
        }
773
    }
774
    Ok(0)
775
}
776
777
pub fn show(change: &str, as_json: bool) -> Result<i32> {
778
    let repo = open()?;
779
    repo.snapshot("oxy show")?;
780
    let h = repo.resolve_change(change)?;
781
    let c = repo.store().get_change(&h)?;
782
    if as_json {
783
        let files = repo.diff_files(Some(&h))?;
784
        let heads = repo.bookmark_heads()?;
785
        let entry = oxy_core::repo::LogEntry {
786
            hash: h,
787
            change: oxy_core::state::ChangeMeta::of(&c),
788
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
789
            is_head: heads.contains(&h),
790
        };
791
        let mut body = log_entry_json(&repo, &entry)?;
792
        body.pop();
793
        body.push_str(&format!(
794
            ",{}:{}}}",
795
            json::s("files"),
796
            json::arr(files.iter().map(|f| json::obj([
797
                ("path", json::s(&f.path)),
798
                ("kind", json::s(&f.kind)),
799
                ("from", json::opt(f.from.as_deref(), json::s))
800
            ])))
801
        ));
802
        println!("{body}");
803
        return Ok(0);
804
    }
805
    println!(
806
        "{} {} {}",
807
        ui::section("change"),
808
        ui::id(short_id(&c)),
809
        ui::hash(format!("#{h}"))
810
    );
811
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
812
    println!(
813
        "{}",
814
        ui::kv(
815
            "author",
816
            ui::author(author_name(&repo, &oxy_core::state::ChangeMeta::of(&c)))
817
        )
818
    );
819
    println!(
820
        "{}",
821
        ui::kv(
822
            "date",
823
            format!(
824
                "{} {}",
825
                when(c.hlc.wall_ms),
826
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
827
            )
828
        )
829
    );
830
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
831
    println!("{}", ui::kv("sig", signature_line(&repo, &h)?));
832
    println!();
833
    for line in (if c.message.is_empty() {
834
        "(no description)"
835
    } else {
836
        &c.message
837
    })
838
    .lines()
839
    {
840
        println!("    {line}");
841
    }
842
    println!();
843
    print!("{}", repo.describe_change(&h)?);
844
    Ok(0)
845
}
846
847
pub fn checkout(changes: &[String], discard: bool) -> Result<i32> {
848
    let repo = open()?;
849
    let heads = if changes.is_empty() {
850
        repo.bookmark_heads()?
851
    } else {
852
        let mut heads = Vec::new();
853
        for c in changes {
854
            heads.extend(repo.resolve_heads(c)?);
855
        }
856
        heads
857
    };
858
    let spec = if changes.is_empty() {
859
        repo.config.bookmark.clone()
860
    } else {
861
        changes.join(" ")
862
    };
863
    let sp = ui::spinner(&format!("Checking out {spec}…"));
864
    let r = repo.checkout(&heads, discard, &format!("oxy checkout {spec}"))?;
865
    sp.done(&format!(
866
        "{} on {}: {} written, {} removed",
867
        ui::done("Working copy"),
868
        ui::bookmark(&spec),
869
        plural(r.written, "file"),
870
        r.removed
871
    ));
872
    for n in &r.notes {
873
        println!("  {} {n}", ui::note());
874
    }
875
    if r.conflicted {
876
        println!(
877
            "  {} {}",
878
            ui::caution(),
879
            ui::warn("this state has conflicts; see oxy status")
880
        );
881
    }
882
    Ok(0)
883
}
884
885
pub fn resolve(as_json: bool) -> Result<i32> {
886
    let repo = open()?;
887
    let snap = repo.snapshot("oxy resolve")?;
888
    if as_json {
889
        println!("{}", repo.status_json(&snap)?);
890
        return Ok(if snap.base_snapshot.is_conflicted() {
891
            2
892
        } else {
893
            0
894
        });
895
    }
896
    if !snap.base_snapshot.is_conflicted() {
897
        println!("The working copy's base has no conflicts.");
898
        return Ok(0);
899
    }
900
    let mut remaining = 0;
901
    for (p, f) in &snap.base_snapshot.files {
902
        if !f.is_conflicted() {
903
            continue;
904
        }
905
        match snap
906
            .statuses
907
            .iter()
908
            .find(|s| s.path == *p)
909
            .map(|s| s.status)
910
        {
911
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
912
            Some(ChangeStatus::ConflictEdited) => {
913
                remaining += 1;
914
                println!("markers    {p}");
915
            }
916
            _ => {
917
                remaining += 1;
918
                println!("unresolved {p}");
919
            }
920
        }
921
    }
922
    for c in &snap.base_snapshot.tree.conflicts {
923
        remaining += 1;
924
        println!("tree       {c:?}");
925
    }
926
    if remaining == 0 {
927
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
928
        Ok(0)
929
    } else {
930
        Ok(2)
931
    }
932
}
933
934
pub fn undo() -> Result<i32> {
935
    let repo = open()?;
936
    let op = repo.undo()?;
937
    println!("{} now at: {}", ui::done("Undone;"), ui::dim(&op.command));
938
    Ok(0)
939
}
940
941
pub fn op_log(as_json: bool) -> Result<i32> {
942
    let repo = open()?;
943
    if as_json {
944
        let ops = repo.op_log()?;
945
        println!(
946
            "{}",
947
            json::arr(ops.iter().enumerate().map(|(i, (r, op))| {
948
                json::obj([
949
                    ("id", json::s(&r.to_hex())),
950
                    ("when_ms", json::n(op.hlc.wall_ms)),
951
                    ("command", json::s(&op.command)),
952
                    ("snapshot", json::b(op.command.ends_with("(snapshot)"))),
953
                    ("current", json::b(i == 0)),
954
                ])
955
            }))
956
        );
957
        return Ok(0);
958
    }
959
    for (i, (r, op)) in repo.op_log()?.into_iter().enumerate() {
960
        let bullet = if i == 0 {
961
            ui::ok(ui::glyph("●", "@"))
962
        } else {
963
            ui::dim(ui::glyph("○", "o"))
964
        };
965
        let cmd = subject_of(&op.command).split("\\n").next().unwrap_or("");
966
        println!(
967
            "{bullet} {}{}{}  {}",
968
            ui::hash(r.short(12)),
969
            ui::sep(),
970
            ui::dim(format!("{:<16}", ui::ago(op.hlc.wall_ms))),
971
            if i == 0 {
972
                ui::subject(cmd)
973
            } else {
974
                cmd.to_string()
975
            }
976
        );
977
    }
978
    Ok(0)
979
}
980
981
pub fn gc(now: bool) -> Result<i32> {
982
    let repo = open()?;
983
    let sp = ui::spinner("Packing and pruning…");
984
    let r = repo.gc(now)?;
985
    sp.clear();
986
    if r.packed.objects > 0 {
987
        println!(
988
            "Packed {}: {} bytes -> {} bytes ({:.0}%).",
989
            plural(r.packed.objects, "loose object"),
990
            r.packed.raw_bytes,
991
            r.packed.packed_bytes,
992
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
993
        );
994
    }
995
    println!(
996
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
997
        plural(r.reachable, "object"),
998
        plural(r.pruned.objects, "unreachable object"),
999
        r.pruned.bytes,
1000
        if r.pruned.deferred > 0 {
1001
            format!(
1002
                "; {} deferred by the grace period (use --now)",
1003
                plural(r.pruned.deferred, "object")
1004
            )
1005
        } else {
1006
            String::new()
1007
        },
1008
        if r.merged_packs > 0 {
1009
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1010
        } else {
1011
            String::new()
1012
        },
1013
        plural(repo.store().pack_count(), "pack")
1014
    );
1015
    Ok(0)
1016
}
1017
1018
/// The head the working copy sits on, for commands that default to it. With
1019
/// several heads beneath the working copy, the most recently made one is
1020
/// chosen and announced.
1021
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
1022
    let snap = repo.snapshot("oxy")?;
1023
    let base = snap.base.maximal(&snap.wc.deps);
1024
    match base.as_slice() {
1025
        [] => anyhow::bail!("the working copy sits on no change yet"),
1026
        [h] => Ok(*h),
1027
        many => {
1028
            let latest = many
1029
                .iter()
1030
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
1031
                .copied()
1032
                .unwrap();
1033
            let c = repo.store().get_change(&latest)?;
1034
            println!(
1035
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
1036
                short_id(&c),
1037
                latest.short(12),
1038
                many.len()
1039
            );
1040
            Ok(latest)
1041
        }
1042
    }
1043
}
1044
1045
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
1046
    let repo = open()?;
1047
    let h = match change {
1048
        Some(c) => repo.resolve_change(c)?,
1049
        None => current_head(&repo)?,
1050
    };
1051
    let new = repo.describe(&h, message)?;
1052
    let c = repo.store().get_change(&new)?;
1053
    println!(
1054
        "{} {} {}  {}",
1055
        ui::done("Described"),
1056
        ui::id(short_id(&c)),
1057
        ui::hash(format!("#{}", new.short(12))),
1058
        ui::subject(subject_of(message))
1059
    );
1060
    Ok(0)
1061
}
1062
1063
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
1064
    let repo = open()?;
1065
    let new = match into {
1066
        Some(spec) => {
1067
            let target = repo.resolve_change(spec)?;
1068
            repo.amend_into(&target, message)?
1069
        }
1070
        None => repo.amend(message)?,
1071
    };
1072
    let c = repo.store().get_change(&new)?;
1073
    println!(
1074
        "{} {} {}  {}",
1075
        ui::done("Amended"),
1076
        ui::id(short_id(&c)),
1077
        ui::hash(format!("#{}", new.short(12))),
1078
        ui::subject(subject_of(&c.message))
1079
    );
1080
    Ok(0)
1081
}
1082
1083
pub fn abandon(change: &str) -> Result<i32> {
1084
    let repo = open()?;
1085
    let h = repo.resolve_change(change)?;
1086
    let c = repo.store().get_change(&h)?;
1087
    let notes = repo.abandon(&h)?;
1088
    println!(
1089
        "{} {} {}  {}",
1090
        ui::done("Abandoned"),
1091
        ui::id(short_id(&c)),
1092
        ui::hash(format!("#{}", h.short(12))),
1093
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
1094
    );
1095
    for n in notes {
1096
        println!("  {} {n}", ui::note());
1097
    }
1098
    Ok(0)
1099
}
1100
1101
pub fn checkpoint() -> Result<i32> {
1102
    let repo = open()?;
1103
    let sp = ui::spinner("Writing checkpoint…");
1104
    let (r, changes, bytes) = repo.checkpoint()?;
1105
    sp.done(&format!(
1106
        "{} {} of {} ({} bytes) for {}",
1107
        ui::done("Checkpoint"),
1108
        ui::hash(format!("#{}", r.short(12))),
1109
        plural(changes, "change"),
1110
        bytes,
1111
        ui::id(&repo.config.bookmark)
1112
    ));
1113
    Ok(0)
1114
}
1115
1116
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
1117
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
1118
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
1119
        return Ok(1);
1120
    };
1121
    let info = repo.quick_status()?;
1122
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
1123
        oxy_core::repo::GLYPH_PROMPT_FORMAT
1124
    } else {
1125
        format
1126
    };
1127
    let line = match color {
1128
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
1129
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
1130
        Some(_) => info.format_colored(fmt, ("", "")),
1131
        None => info.format(fmt),
1132
    };
1133
    println!("{line}");
1134
    Ok(0)
1135
}
1136
1137
pub fn sparse(paths: &[String]) -> Result<i32> {
1138
    let mut repo = open()?;
1139
    if paths.is_empty() {
1140
        if repo.config.sparse_paths.is_empty() {
1141
            println!("No sparse filter: the whole tree is materialized.");
1142
        } else {
1143
            println!("{}", ui::heading("Sparse filter"));
1144
            for p in &repo.config.sparse_paths {
1145
                println!("  {}", ui::path(p));
1146
            }
1147
        }
1148
        return Ok(0);
1149
    }
1150
    let snap = repo.snapshot("oxy sparse")?;
1151
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
1152
        anyhow::bail!(
1153
            "the working copy has changes; commit them before changing the sparse filter"
1154
        );
1155
    }
1156
    repo.config.set("filter.paths", &paths.join(","))?;
1157
    repo.save_config()?;
1158
    let heads = repo.bookmark_heads()?;
1159
    let sp = ui::spinner("Re-checking out with the new filter…");
1160
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
1161
    sp.done(&format!(
1162
        "{} {}: {} written, {} removed",
1163
        ui::ok("Sparse filter set to"),
1164
        ui::path(paths.join(",")),
1165
        plural(r.written, "file"),
1166
        r.removed
1167
    ));
1168
    Ok(0)
1169
}
1170
1171
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
1172
    let repo = open()?;
1173
    repo.snapshot("oxy tag")?;
1174
    let heads = if changes.is_empty() {
1175
        repo.bookmark_heads()?
1176
    } else {
1177
        let mut heads = Vec::new();
1178
        for c in changes {
1179
            heads.extend(repo.resolve_heads(c)?);
1180
        }
1181
        heads
1182
    };
1183
    let t = repo.tag_create(name, &heads, message)?;
1184
    println!(
1185
        "{} {} {} {} ({}){}",
1186
        ui::done("Tagged"),
1187
        ui::bookmark(&t.name),
1188
        ui::dim(ui::glyph("→", "->")),
1189
        ui::hash(format!("#{}", t.state.short(12))),
1190
        plural(t.heads.len(), "head"),
1191
        t.signer
1192
            .map(|s| format!(", signed by {s}"))
1193
            .unwrap_or_else(|| ui::dim(", unsigned"))
1194
    );
1195
    Ok(0)
1196
}
1197
1198
pub fn tag_list(as_json: bool) -> Result<i32> {
1199
    let repo = open()?;
1200
    let tags = repo.tags()?;
1201
    if as_json {
1202
        println!(
1203
            "{}",
1204
            json::arr(tags.iter().map(|t| {
1205
                json::obj([
1206
                    ("name", json::s(&t.name)),
1207
                    ("state", json::s(&t.state.to_hex())),
1208
                    ("heads", json::hashes(&t.heads)),
1209
                    ("message", json::s(&t.message)),
1210
                    (
1211
                        "signer",
1212
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
1213
                    ),
1214
                ])
1215
            }))
1216
        );
1217
        return Ok(0);
1218
    }
1219
    if tags.is_empty() {
1220
        println!("{}", ui::dim("No tags."));
1221
    }
1222
    for t in tags {
1223
        println!(
1224
            "{} {} {}{}{}{}",
1225
            ui::ok(ui::glyph("⚑", "#")),
1226
            ui::bookmark(&t.name),
1227
            ui::hash(format!("#{}", t.state.short(12))),
1228
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
1229
            if t.message.is_empty() {
1230
                String::new()
1231
            } else {
1232
                format!("  {}", ui::subject(subject_of(&t.message)))
1233
            },
1234
            t.signer
1235
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
1236
                .unwrap_or_default()
1237
        );
1238
    }
1239
    Ok(0)
1240
}
1241
1242
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
1243
    let repo = open()?;
1244
    let heads = if changes.is_empty() {
1245
        None
1246
    } else {
1247
        let mut heads = Vec::new();
1248
        for c in changes {
1249
            heads.extend(repo.resolve_heads(c)?);
1250
        }
1251
        Some(heads)
1252
    };
1253
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
1254
    let ws = repo.workspace_add(path, heads.as_deref())?;
1255
    sp.done(&format!(
1256
        "{} {} (workspace {})",
1257
        ui::done("Workspace created at"),
1258
        ui::path(ws.root().display()),
1259
        ui::id(ws.workspace().short(8))
1260
    ));
1261
    Ok(0)
1262
}
1263
1264
pub fn workspace_list(as_json: bool) -> Result<i32> {
1265
    let repo = open()?;
1266
    if as_json {
1267
        println!(
1268
            "{}",
1269
            json::arr(repo.workspaces()?.iter().map(|w| {
1270
                json::obj([
1271
                    ("id", json::s(&w.id.to_hex())),
1272
                    ("path", json::s(&w.path.to_string_lossy())),
1273
                    ("current", json::b(w.current)),
1274
                    (
1275
                        "working_copy",
1276
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
1277
                    ),
1278
                ])
1279
            }))
1280
        );
1281
        return Ok(0);
1282
    }
1283
    for w in repo.workspaces()? {
1284
        println!(
1285
            "{} {} {}{}",
1286
            if w.current {
1287
                ui::ok(ui::glyph("●", "*"))
1288
            } else {
1289
                ui::dim(ui::glyph("○", "o"))
1290
            },
1291
            ui::id(w.id.short(8)),
1292
            ui::path(w.path.display()),
1293
            w.working_copy
1294
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
1295
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
1296
        );
1297
    }
1298
    Ok(0)
1299
}
1300
1301
pub fn workspace_forget(spec: &str) -> Result<i32> {
1302
    let repo = open()?;
1303
    let all = repo.workspaces()?;
1304
    let target = std::fs::canonicalize(spec).ok();
1305
    let matches: Vec<_> = all
1306
        .iter()
1307
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
1308
        .collect();
1309
    let w = match matches.as_slice() {
1310
        [w] => *w,
1311
        [] => anyhow::bail!("no workspace matches {spec:?}"),
1312
        _ => anyhow::bail!("{spec:?} is ambiguous"),
1313
    };
1314
    repo.workspace_forget(&w.id)?;
1315
    println!(
1316
        "{} workspace {} at {}; its files were left in place.",
1317
        ui::done("Forgot"),
1318
        ui::id(w.id.short(8)),
1319
        ui::path(w.path.display())
1320
    );
1321
    Ok(0)
1322
}
1323
1324
pub fn lock(path: &str) -> Result<i32> {
1325
    let repo = open()?;
1326
    repo.lock_path(path)?;
1327
    println!(
1328
        "{} {} {}",
1329
        ui::done("Locked"),
1330
        ui::path(path),
1331
        ui::dim("(advisory, local)")
1332
    );
1333
    Ok(0)
1334
}
1335
1336
pub fn unlock(path: &str) -> Result<i32> {
1337
    let repo = open()?;
1338
    repo.unlock_path(path)?;
1339
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
1340
    Ok(0)
1341
}
1342
1343
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
1344
    let repo = open()?;
1345
    let h = repo.resolve_change(change)?;
1346
    let (h1, h2) = repo.split(&h, paths)?;
1347
    let c1 = repo.store().get_change(&h1)?;
1348
    let c2 = repo.store().get_change(&h2)?;
1349
    println!(
1350
        "{} into {} {} and {} {}",
1351
        ui::done("Split"),
1352
        ui::id(short_id(&c1)),
1353
        ui::hash(format!("#{}", h1.short(12))),
1354
        ui::id(short_id(&c2)),
1355
        ui::hash(format!("#{}", h2.short(12)))
1356
    );
1357
    Ok(0)
1358
}
1359
1360
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
1361
    let mut heads = Vec::new();
1362
    for c in changes {
1363
        heads.extend(repo.resolve_heads(c)?);
1364
    }
1365
    Ok(heads)
1366
}
1367
1368
pub fn bookmark_create(name: &str, changes: &[String]) -> Result<i32> {
1369
    let repo = open()?;
1370
    repo.snapshot("oxy bookmark create")?;
1371
    let heads = if changes.is_empty() {
1372
        None
1373
    } else {
1374
        Some(heads_from(&repo, changes)?)
1375
    };
1376
    let heads = repo.bookmark_create(name, heads.as_deref())?;
1377
    println!(
1378
        "{} bookmark {} {} {}",
1379
        ui::done("Created"),
1380
        ui::bookmark(name),
1381
        ui::dim(ui::glyph("→", "->")),
1382
        ui::dim(plural(heads.len(), "head"))
1383
    );
1384
    println!(
1385
        "  {} {}",
1386
        ui::note(),
1387
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
1388
    );
1389
    Ok(0)
1390
}
1391
1392
pub fn bookmark_set(name: &str, changes: &[String]) -> Result<i32> {
1393
    let repo = open()?;
1394
    repo.snapshot("oxy bookmark set")?;
1395
    let heads = heads_from(&repo, changes)?;
1396
    let heads = repo.bookmark_set(name, &heads)?;
1397
    println!(
1398
        "{} bookmark {} {} {}",
1399
        ui::done("Moved"),
1400
        ui::bookmark(name),
1401
        ui::dim(ui::glyph("→", "->")),
1402
        ui::dim(plural(heads.len(), "head"))
1403
    );
1404
    Ok(0)
1405
}
1406
1407
pub fn bookmark_delete(name: &str) -> Result<i32> {
1408
    let repo = open()?;
1409
    repo.bookmark_delete(name)?;
1410
    println!(
1411
        "{} bookmark {} {}",
1412
        ui::done("Deleted"),
1413
        ui::bookmark(name),
1414
        ui::dim("(its changes stay until unreachable)")
1415
    );
1416
    Ok(0)
1417
}
1418
1419
pub fn bookmark_list(as_json: bool) -> Result<i32> {
1420
    let repo = open()?;
1421
    if as_json {
1422
        let items = repo.bookmarks()?.into_iter().map(|b| {
1423
            json::obj([
1424
                ("name", json::s(&b.name)),
1425
                ("heads", json::hashes(&b.heads)),
1426
                ("current", json::b(b.current)),
1427
                ("ahead", json::opt(b.ahead, json::n)),
1428
                ("behind", json::opt(b.behind, json::n)),
1429
            ])
1430
        });
1431
        println!("{}", json::arr(items));
1432
        return Ok(0);
1433
    }
1434
    for b in repo.bookmarks()? {
1435
        let mark = if b.current {
1436
            ui::ok(ui::glyph("●", "*"))
1437
        } else {
1438
            ui::dim(ui::glyph("○", "o"))
1439
        };
1440
        let mut tail = String::new();
1441
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
1442
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
1443
        }
1444
        if let Some(n) = b.behind.filter(|n| *n > 0) {
1445
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
1446
        }
1447
        let head = b
1448
            .heads
1449
            .first()
1450
            .map(|h| {
1451
                repo.store()
1452
                    .get_change(h)
1453
                    .map(|c| ui::subject(subject_of(&c.message)))
1454
                    .unwrap_or_default()
1455
            })
1456
            .unwrap_or_else(|| ui::dim("(empty)"));
1457
        println!(
1458
            "{mark} {}{}{}{tail}  {head}",
1459
            ui::bookmark(&b.name),
1460
            ui::sep(),
1461
            ui::dim(plural(b.heads.len(), "head"))
1462
        );
1463
    }
1464
    Ok(0)
1465
}
1466
1467
pub fn bookmark_switch(name: &str, discard: bool) -> Result<i32> {
1468
    let mut repo = open()?;
1469
    let sp = ui::spinner(&format!("Switching to {name}…"));
1470
    let r = repo.bookmark_switch(name, discard)?;
1471
    sp.done(&format!(
1472
        "{} to {}: {} written, {} removed",
1473
        ui::done("Switched"),
1474
        ui::bookmark(name),
1475
        plural(r.written, "file"),
1476
        r.removed
1477
    ));
1478
    if r.conflicted {
1479
        println!(
1480
            "  {} {}",
1481
            ui::caution(),
1482
            ui::warn("this state has conflicts; see oxy status")
1483
        );
1484
    }
1485
    Ok(0)
1486
}
1487
1488
pub fn merge(bookmark: &str) -> Result<i32> {
1489
    let repo = open()?;
1490
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
1491
    let r = repo.merge(bookmark)?;
1492
    if !r.changed {
1493
        sp.done(&format!(
1494
            "{} {}",
1495
            ui::ok(ui::glyph("✔", "*")),
1496
            ui::dim(format!(
1497
                "{} already contains {bookmark}",
1498
                repo.config.bookmark
1499
            ))
1500
        ));
1501
        return Ok(0);
1502
    }
1503
    sp.done(&format!(
1504
        "{} {} into {}: now {}{}",
1505
        ui::done("Merged"),
1506
        ui::bookmark(bookmark),
1507
        ui::bookmark(&repo.config.bookmark),
1508
        plural(r.heads.len(), "head"),
1509
        ui::dim(if r.checked_out {
1510
            "; working copy updated"
1511
        } else {
1512
            "; run oxy checkout to update the working copy"
1513
        })
1514
    ));
1515
    let snap = repo.snapshot("oxy merge")?;
1516
    if snap.base_snapshot.is_conflicted() {
1517
        println!(
1518
            "  {} {}",
1519
            ui::caution(),
1520
            ui::warn("the result has conflicts; see oxy status")
1521
        );
1522
    }
1523
    Ok(0)
1524
}
1525
1526
pub fn squash(change: &str, into: &str) -> Result<i32> {
1527
    let repo = open()?;
1528
    let c = repo.resolve_change(change)?;
1529
    let d = repo.resolve_change(into)?;
1530
    let sp = ui::spinner("Squashing…");
1531
    let h = repo.squash(&c, &d)?;
1532
    let new = repo.store().get_change(&h)?;
1533
    sp.done(&format!(
1534
        "{} into {} {}  {}",
1535
        ui::done("Squashed"),
1536
        ui::id(short_id(&new)),
1537
        ui::hash(format!("#{}", h.short(12))),
1538
        ui::subject(subject_of(&new.message))
1539
    ));
1540
    Ok(0)
1541
}
1542
1543
pub fn rebase(change: &str, onto: &[String]) -> Result<i32> {
1544
    let repo = open()?;
1545
    let c = repo.resolve_change(change)?;
1546
    let mut heads = Vec::new();
1547
    for o in onto {
1548
        heads.extend(repo.resolve_heads(o)?);
1549
    }
1550
    let sp = ui::spinner("Rebasing…");
1551
    let h = repo.rebase(&c, &heads)?;
1552
    let new = repo.store().get_change(&h)?;
1553
    sp.done(&format!(
1554
        "{} {} {}  {}",
1555
        ui::done("Rebased"),
1556
        ui::id(short_id(&new)),
1557
        ui::hash(format!("#{}", h.short(12))),
1558
        ui::dim(format!(
1559
            "now depends on {}",
1560
            plural(new.deps.len(), "change")
1561
        ))
1562
    ));
1563
    Ok(0)
1564
}