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