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