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