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