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