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