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