OXYGENHUB
# dab94366a4f0 oxygen / src / cli / workspace.rs
98.4 KiB · Rust · last changed Cylinder C1, first part: artifacts as trees of the repository's chunks, oxy artifact pack/list/show/unpack/verify, kept by gc (refs #108) 7 days 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, signature_line, signature_mark_of,
5
    subject_of, via, 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::io::Write;
15
use std::path::PathBuf;
16
17
pub fn init(path: Option<PathBuf>, bare: bool, store: Option<&str>) -> Result<i32> {
18
    let path = path.unwrap_or(std::env::current_dir()?);
19
    let repo = Repo::init_new(&path, bare, store)?;
20
    println!(
21
        "{} {}oxy repository in {}",
22
        ui::done("Initialized"),
23
        if bare { "bare " } else { "" },
24
        ui::path(repo.root().display())
25
    );
26
    println!(
27
        "{}",
28
        ui::kv("bookmark", ui::bookmark(&repo.config.bookmark))
29
    );
30
    if let Some(url) = &repo.config.storage_url {
31
        println!(
32
            "{}",
33
            ui::kv(
34
                "store",
35
                format!(
36
                    "{url} (cache in {}, up to {} MiB)",
37
                    ui::path(repo.root().join(".oxy/cache").display()),
38
                    repo.config.storage_cache >> 20
39
                )
40
            )
41
        );
42
    }
43
    println!(
44
        "{}",
45
        ui::kv(
46
            "author",
47
            format!(
48
                "{} <{}>",
49
                ui::author(&repo.config.author_name),
50
                repo.config.author_email
51
            )
52
        )
53
    );
54
    Ok(0)
55
}
56
57
fn status_tag(s: ChangeStatus) -> &'static str {
58
    match s {
59
        ChangeStatus::Added => "A",
60
        ChangeStatus::Modified => "M",
61
        ChangeStatus::Removed => "D",
62
        ChangeStatus::Renamed => "R",
63
        ChangeStatus::ModeChanged => "X",
64
        ChangeStatus::ConflictEdited => "C!",
65
        ChangeStatus::Resolved => "V",
66
    }
67
}
68
69
/// New untracked files left out of the snapshot for their size (oxygen#98):
70
/// named, with how to keep them out quietly or take them in.
71
fn print_skipped_large(repo: &Repo) {
72
    let skipped = repo.skipped_large();
73
    if skipped.is_empty() {
74
        return;
75
    }
76
    let size = |n: u64| {
77
        if n >= 1 << 30 {
78
            format!("{:.1} GiB", n as f64 / (1u64 << 30) as f64)
79
        } else {
80
            format!("{:.0} MiB", n as f64 / (1u64 << 20) as f64)
81
        }
82
    };
83
    println!();
84
    println!(
85
        "{} {}",
86
        ui::section(ui::warn("Not tracked")),
87
        ui::dim(format!("new files over {}", size(repo.config.max_new_file)))
88
    );
89
    for (p, n) in &skipped {
90
        println!("  {} {}  {}", ui::caution(), ui::path(p), ui::dim(size(*n)));
91
    }
92
    println!(
93
        "  {} {}",
94
        ui::note(),
95
        ui::dim(
96
            "to leave them out quietly, list them in .oxyignore; to track one, \
97
             raise snapshot.max-new-file-size (oxy config snapshot.max-new-file-size 2G)"
98
        )
99
    );
100
}
101
102
/// Name what a checkout removed from the working copy (oxygen#102): a
103
/// switch to a bookmark lacking files takes them off disk, which an
104
/// editor open on the tree notices before a person reading a count does.
105
fn print_removed(r: &oxy_core::repo::CheckoutReport) {
106
    if r.removed == 0 {
107
        return;
108
    }
109
    let more = r.removed.saturating_sub(r.removed_paths.len());
110
    let names = r.removed_paths.join(", ");
111
    let tail = if more > 0 {
112
        format!(" and {more} more")
113
    } else {
114
        String::new()
115
    };
116
    let lead = if r.removed >= 20 {
117
        ui::caution()
118
    } else {
119
        ui::note()
120
    };
121
    println!(
122
        "  {} {}",
123
        lead,
124
        ui::dim(format!(
125
            "removed from disk (the bookmark does not have them): {names}{tail}"
126
        ))
127
    );
128
}
129
130
/// Name the work a switch carried (oxygen#120): it is still on disk, as it
131
/// was, on the new bookmark.
132
fn print_carried(paths: &[String]) {
133
    if paths.is_empty() {
134
        return;
135
    }
136
    let shown: Vec<&str> = paths.iter().take(10).map(String::as_str).collect();
137
    let more = paths.len().saturating_sub(shown.len());
138
    println!(
139
        "  {} {}",
140
        ui::note(),
141
        ui::dim(format!(
142
            "carried, as they were: {}{}",
143
            shown.join(", "),
144
            if more > 0 {
145
                format!(" and {more} more")
146
            } else {
147
                String::new()
148
            }
149
        ))
150
    );
151
}
152
153
/// Folders holding a repository of their own, which oxy leaves out (oxygen#43):
154
/// named, with how to track them.
155
fn print_untracked_nested(repo: &Repo, nested: &[String]) {
156
    if nested.is_empty() {
157
        return;
158
    }
159
    println!();
160
    println!(
161
        "{} {}",
162
        ui::section(ui::warn("Not tracked")),
163
        ui::dim("folders holding a repository of their own")
164
    );
165
    for p in nested {
166
        let kind = if repo.root().join(p).join(".git").exists() {
167
            "Git"
168
        } else {
169
            "Oxygen"
170
        };
171
        println!(
172
            "  {} {}  {}",
173
            ui::caution(),
174
            ui::path(format!("{p}/")),
175
            ui::dim(format!("a nested {kind} repository"))
176
        );
177
    }
178
    println!(
179
        "  {} {}",
180
        ui::note(),
181
        ui::dim(
182
            "to track one's files, remove its .git (or .oxy); to keep it a repository of its own, \
183
             oxy submodule add URL PATH; to leave it out quietly, list it in .oxyignore"
184
        )
185
    );
186
}
187
188
/// The working copy's changed paths, or that it is clean.
189
fn print_statuses(statuses: &[oxy_core::repo::PathStatus]) {
190
    if statuses.is_empty() {
191
        println!(
192
            "  {} {}",
193
            ui::ok(ui::glyph("✔", "*")),
194
            ui::dim("nothing to commit, working copy clean")
195
        );
196
        return;
197
    }
198
    println!();
199
    for s in statuses {
200
        println!(
201
            "  {} {}",
202
            ui::status_mark(status_tag(s.status)),
203
            ui::path(&s.path)
204
        );
205
    }
206
}
207
208
/// Say when the working copy has fallen behind its own bookmark: a
209
/// "clean" status there hid a pull that left it on old code (oxygen#89).
210
fn print_behind(repo: &Repo) {
211
    if let Ok(Some(n)) = repo.working_copy_behind() {
212
        println!(
213
            "  {} {}",
214
            ui::caution(),
215
            ui::warn(format!(
216
                "the working copy is behind {}: it lacks {} the bookmark has; oxy checkout brings it up",
217
                repo.config.bookmark,
218
                plural(n, "change")
219
            ))
220
        );
221
    }
222
}
223
224
pub fn status(json: bool) -> Result<i32> {
225
    let repo = open()?;
226
    // Answered by the manifest alone, with no history to load (oxygen#35,
227
    // #41): a clean working copy, or one as the last snapshot left it.
228
    let known = if json {
229
        None
230
    } else {
231
        repo.status_by_manifest()?
232
    };
233
    if let Some(statuses) = known {
234
        let (_, wc) = repo.working_copy()?;
235
        let heads = repo.bookmark_heads()?;
236
        println!(
237
            "{} {}{}working copy {}{}{}",
238
            ui::dim("On"),
239
            ui::bookmark(&repo.config.bookmark),
240
            ui::sep(),
241
            ui::id(wc.change_id.short(8)),
242
            ui::sep(),
243
            ui::dim(plural(heads.len(), "head"))
244
        );
245
        print_behind(&repo);
246
        print_statuses(&statuses);
247
        print_untracked_nested(&repo, &repo.untracked_nested());
248
        print_skipped_large(&repo);
249
        return Ok(0);
250
    }
251
    let sp = ui::spinner("Snapshotting the working copy…");
252
    let snap = repo.snapshot_status("oxy status")?;
253
    let heads = {
254
        let _t = oxy_core::timing::phase("status: heads");
255
        repo.bookmark_heads()?
256
    };
257
    let _drop = oxy_core::timing::phase("status: print and drop");
258
    sp.clear();
259
    if json {
260
        println!("{}", repo.status_json(&snap)?);
261
        return Ok(if snap.base_snapshot.is_conflicted() {
262
            2
263
        } else {
264
            0
265
        });
266
    }
267
    println!(
268
        "{} {}{}working copy {}{}{}",
269
        ui::dim("On"),
270
        ui::bookmark(&repo.config.bookmark),
271
        ui::sep(),
272
        ui::id(snap.wc.change_id.short(8)),
273
        ui::sep(),
274
        ui::dim(plural(heads.len(), "head"))
275
    );
276
    print_behind(&repo);
277
    print_statuses(&snap.statuses);
278
    print_untracked_nested(&repo, &snap.untracked_nested);
279
    print_skipped_large(&repo);
280
    if !snap.base_snapshot.is_conflicted() {
281
        return Ok(0);
282
    }
283
    println!();
284
    println!(
285
        "{} {}",
286
        ui::section(ui::err("Conflicts")),
287
        ui::dim("edit the marked files, or the .oxy-conflict-N candidates, then commit")
288
    );
289
    for c in &snap.base_snapshot.tree.conflicts {
290
        println!("  {} tree: {c:?}", ui::err(ui::glyph("✱", "!")));
291
    }
292
    for (p, f) in &snap.base_snapshot.files {
293
        if f.is_conflicted() {
294
            let state = match snap
295
                .statuses
296
                .iter()
297
                .find(|s| s.path == *p)
298
                .map(|s| s.status)
299
            {
300
                Some(ChangeStatus::Resolved) => {
301
                    ui::ok(format!("{} resolved in working copy", ui::glyph("✔", "*")))
302
                }
303
                Some(ChangeStatus::ConflictEdited) => {
304
                    ui::warn(format!("{} markers remain", ui::glyph("‼", "!")))
305
                }
306
                _ => ui::err(format!("{} unresolved", ui::glyph("✱", "!"))),
307
            };
308
            println!("  {}  {state}", ui::path(p));
309
            let resolved = matches!(
310
                snap.statuses
311
                    .iter()
312
                    .find(|s| s.path == *p)
313
                    .map(|s| s.status),
314
                Some(ChangeStatus::Resolved)
315
            );
316
            let both = if resolved {
317
                0
318
            } else {
319
                snap.base.both_sides(&f.node).iter().flatten().count()
320
            };
321
            if both > 0 {
322
                println!(
323
                    "     {}",
324
                    ui::dim(format!(
325
                        "{} adjacent {}: `oxy resolve --both {p}` keeps both sides, earliest first",
326
                        both,
327
                        if both == 1 { "insertion" } else { "insertions" }
328
                    ))
329
                );
330
            }
331
        }
332
    }
333
    Ok(2)
334
}
335
336
pub fn commit(
337
    message: &str,
338
    depends_on: &[String],
339
    paths: &[String],
340
    interactive: bool,
341
    hunks: &[usize],
342
) -> Result<i32> {
343
    let repo = open()?;
344
    let mut deps = Vec::new();
345
    for d in depends_on {
346
        deps.push(repo.resolve_change(d)?);
347
    }
348
    let selection = if !hunks.is_empty() {
349
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
350
    } else if interactive {
351
        let (_, hunks) = repo.hunks()?;
352
        if hunks.is_empty() {
353
            anyhow::bail!("nothing to commit: the working copy matches its base");
354
        }
355
        let hunks: Vec<_> = hunks
356
            .into_iter()
357
            .filter(|h| {
358
                paths.is_empty()
359
                    || paths.iter().any(|p| {
360
                        h.path == *p || h.path.starts_with(&format!("{}/", p.trim_end_matches('/')))
361
                    })
362
            })
363
            .collect();
364
        let mut chosen = Vec::new();
365
        let stdin = std::io::stdin();
366
        let mut take_rest = false;
367
        for (n, h) in hunks.iter().enumerate() {
368
            if take_rest {
369
                chosen.push(h.index);
370
                continue;
371
            }
372
            println!(
373
                "{} {} {}",
374
                ui::section(format!("hunk {} of {}", n + 1, hunks.len())),
375
                ui::path(&h.path),
376
                ui::dim(format!("(#{})", h.index))
377
            );
378
            for line in h.text.lines() {
379
                let styled = if line.starts_with('+') {
380
                    ui::ok(line)
381
                } else if line.starts_with('-') {
382
                    ui::err(line)
383
                } else {
384
                    ui::dim(line)
385
                };
386
                println!("  {styled}");
387
            }
388
            loop {
389
                print!(
390
                    "{} ",
391
                    ui::warn("Commit this hunk? [y]es [n]o [a]ll remaining [q]uit:")
392
                );
393
                use std::io::Write as _;
394
                std::io::stdout().flush()?;
395
                let mut answer = String::new();
396
                if stdin.read_line(&mut answer)? == 0 {
397
                    anyhow::bail!("aborted");
398
                }
399
                match answer.trim() {
400
                    "y" | "Y" => {
401
                        chosen.push(h.index);
402
                        break;
403
                    }
404
                    "n" | "N" | "" => break,
405
                    "a" | "A" => {
406
                        chosen.push(h.index);
407
                        take_rest = true;
408
                        break;
409
                    }
410
                    "q" | "Q" => anyhow::bail!("aborted; nothing committed"),
411
                    _ => continue,
412
                }
413
            }
414
        }
415
        if chosen.is_empty() {
416
            anyhow::bail!("no hunks chosen; nothing committed");
417
        }
418
        oxy_core::repo::Selection::Hunks(chosen)
419
    } else if paths.is_empty() {
420
        oxy_core::repo::Selection::All
421
    } else {
422
        oxy_core::repo::Selection::Paths(paths.to_vec())
423
    };
424
    let sp = ui::spinner("Committing…");
425
    let (h, partial) = repo.commit_selection_partial(message, &deps, &selection)?;
426
    // The metadata only: a first commit's change holds the whole tree.
427
    let meta = repo.store().get_change_meta(&h)?;
428
    sp.done(&format!(
429
        "{} {} {}  {}",
430
        ui::done("Committed"),
431
        ui::id(meta.change_id.short(8)),
432
        ui::hash(format!("#{}", h.short(12))),
433
        ui::subject(subject_of(message))
434
    ));
435
    print_untracked_nested(&repo, &repo.untracked_nested());
436
    print_skipped_large(&repo);
437
    // Only a commit that took part of the working copy leaves anything.
438
    if partial {
439
        let rest = repo.snapshot_status("oxy commit")?;
440
        if !rest.statuses.is_empty() {
441
            println!(
442
                "  {} {}",
443
                ui::note(),
444
                ui::dim(format!(
445
                    "{} left uncommitted",
446
                    plural(rest.statuses.len(), "path")
447
                ))
448
            );
449
        }
450
    }
451
    where_now(&repo);
452
    Ok(0)
453
}
454
455
pub fn blame(path: &str, json: bool) -> Result<i32> {
456
    let repo = open()?;
457
    let lines = repo.blame(path)?;
458
    if json {
459
        let items = lines.iter().map(|l| {
460
            format!(
461
                "{{\"line\":{},\"change_id\":{},\"hash\":{},\"index\":{},\"author\":{},\"when_ms\":{}}}",
462
                l.line,
463
                oxy_core::repo::json_str(&l.change_id.to_hex()),
464
                oxy_core::repo::json_str(&l.hash.to_hex()),
465
                l.index,
466
                oxy_core::repo::json_str(&l.author),
467
                l.when_ms
468
            )
469
        });
470
        println!("{}", oxy_core::repo::json_array(items));
471
        return Ok(0);
472
    }
473
    let width = lines
474
        .iter()
475
        .map(|l| l.author.chars().count())
476
        .max()
477
        .unwrap_or(0)
478
        .min(20);
479
    let digits = lines.len().to_string().len();
480
    let _t = oxy_core::timing::phase("blame: print");
481
    // Most lines share their change with many others: each change's id,
482
    // author and age are formatted once, and the lines go out through one
483
    // buffered lock on stdout.
484
    let mut prefix: std::collections::HashMap<oxy_core::hash::ChangeHash, String> =
485
        std::collections::HashMap::new();
486
    let bar = ui::dim(ui::glyph("│", "|"));
487
    let mut out = std::io::BufWriter::with_capacity(1 << 16, std::io::stdout().lock());
488
    for l in &lines {
489
        let p = prefix.entry(l.hash).or_insert_with(|| {
490
            let author: String = l.author.chars().take(20).collect();
491
            format!(
492
                "{} {} {}",
493
                ui::id(l.change_id.short(8)),
494
                ui::author(format!("{author:<width$}")),
495
                ui::dim(ui::ago(l.when_ms))
496
            )
497
        });
498
        let text = String::from_utf8_lossy(&l.text);
499
        if writeln!(
500
            out,
501
            "{p} {:>digits$}{bar} {}",
502
            l.line,
503
            text.trim_end_matches('\n')
504
        )
505
        .is_err()
506
        {
507
            // A closed pipe (blame | head): stop quietly.
508
            return Ok(0);
509
        }
510
    }
511
    let _ = out.flush();
512
    Ok(0)
513
}
514
515
fn bisect_report(repo: &Repo, step: &oxy_core::repo::BisectStep) -> Result<i32> {
516
    use oxy_core::repo::BisectStep::*;
517
    match step {
518
        NeedMarks { good, bad } => {
519
            println!(
520
                "{} {} {}",
521
                ui::note(),
522
                ui::dim(format!("{good} good, {bad} bad;")),
523
                ui::dim(if *good == 0 {
524
                    "mark a known-good change or bookmark: oxy bisect good CHANGE"
525
                } else {
526
                    "mark a known-bad change or bookmark: oxy bisect bad CHANGE"
527
                })
528
            );
529
            Ok(0)
530
        }
531
        Testing {
532
            heads,
533
            remaining,
534
            steps_left,
535
        } => {
536
            println!(
537
                "{} {} {}",
538
                ui::done("Testing"),
539
                ui::dim(format!(
540
                    "{} in the state under test;",
541
                    plural(heads.len(), "head")
542
                )),
543
                ui::dim(format!(
544
                    "{remaining} candidates left, about {steps_left} more steps"
545
                ))
546
            );
547
            println!(
548
                "  {} {}",
549
                ui::note(),
550
                ui::dim("run your test, then oxy bisect good | bad | skip")
551
            );
552
            Ok(0)
553
        }
554
        Found { culprit } => {
555
            let c = repo.store().get_change(culprit)?;
556
            println!(
557
                "{} {} {}  {}",
558
                ui::done("Found"),
559
                ui::id(short_id(&c)),
560
                ui::hash(format!("#{}", culprit.short(12))),
561
                ui::subject(subject_of(&c.message))
562
            );
563
            println!("  {} {}", ui::note(), ui::dim("the first change whose inclusion makes the state bad; oxy bisect reset to return"));
564
            Ok(0)
565
        }
566
        Inconclusive { candidates } => {
567
            println!(
568
                "{} {}",
569
                ui::caution(),
570
                ui::warn(format!(
571
                    "every remaining candidate was skipped ({}); oxy bisect reset to return",
572
                    plural(candidates.len(), "change")
573
                ))
574
            );
575
            Ok(1)
576
        }
577
    }
578
}
579
580
pub fn bisect_start() -> Result<i32> {
581
    let repo = open()?;
582
    repo.bisect_start()?;
583
    println!(
584
        "{} bisect; {}",
585
        ui::done("Started"),
586
        ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE")
587
    );
588
    Ok(0)
589
}
590
591
pub fn bisect_mark(good: Option<bool>, changes: &[String]) -> Result<i32> {
592
    let repo = open()?;
593
    let mut heads = Vec::new();
594
    for c in changes {
595
        heads.extend(repo.resolve_heads(c)?);
596
    }
597
    let step = repo.bisect_mark(good, &heads)?;
598
    bisect_report(&repo, &step)
599
}
600
601
pub fn bisect_run(command: &[String]) -> Result<i32> {
602
    let repo = open()?;
603
    let step = repo.bisect_run(command)?;
604
    bisect_report(&repo, &step)
605
}
606
607
pub fn bisect_status(as_json: bool) -> Result<i32> {
608
    let repo = open()?;
609
    if as_json {
610
        use oxy_core::repo::BisectStep::*;
611
        let v = match repo.bisect_status()? {
612
            None => "null".to_string(),
613
            Some(NeedMarks { good, bad }) => json::obj([
614
                ("state", json::s("need-marks")),
615
                ("good", json::n(good)),
616
                ("bad", json::n(bad)),
617
            ]),
618
            Some(Testing {
619
                heads,
620
                remaining,
621
                steps_left,
622
            }) => json::obj([
623
                ("state", json::s("testing")),
624
                ("heads", json::hashes(&heads)),
625
                ("remaining", json::n(remaining)),
626
                ("steps_left", json::n(steps_left)),
627
            ]),
628
            Some(Found { culprit }) => json::obj([
629
                ("state", json::s("found")),
630
                ("culprit", json::s(&culprit.to_hex())),
631
            ]),
632
            Some(Inconclusive { candidates }) => json::obj([
633
                ("state", json::s("inconclusive")),
634
                ("candidates", json::hashes(&candidates)),
635
            ]),
636
        };
637
        println!("{v}");
638
        return Ok(0);
639
    }
640
    match repo.bisect_status()? {
641
        None => {
642
            println!("{}", ui::dim("No bisect in progress."));
643
            Ok(0)
644
        }
645
        Some(step) => bisect_report(&repo, &step),
646
    }
647
}
648
649
pub fn bisect_reset() -> Result<i32> {
650
    let repo = open()?;
651
    repo.bisect_reset()?;
652
    println!("{} bisect; working copy restored", ui::done("Reset"));
653
    Ok(0)
654
}
655
656
/// The log: one entry per change, newest first, joined by a rail. The
657
/// default view is the subject and a metadata line; `verbose` adds the full
658
/// message, dependencies, and the authenticating key.
659
fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
660
    Ok(match repo.authenticate_change(h)? {
661
        SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]),
662
        SignatureStatus::Valid {
663
            key,
664
            name,
665
            email,
666
            sealed,
667
            revoked,
668
        } => json::obj([
669
            ("status", json::s(if sealed { "sealed" } else { "signed" })),
670
            ("key", json::s(&key.to_hex())),
671
            ("name", json::s(&name)),
672
            ("email", json::s(&email)),
673
            ("revoked", json::b(revoked)),
674
        ]),
675
        SignatureStatus::Invalid(why) => {
676
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
677
        }
678
    })
679
}
680
681
fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result<String> {
682
    let c = &e.change;
683
    Ok(json::obj([
684
        ("hash", json::s(&e.hash.to_hex())),
685
        ("change_id", json::s(&c.change_id.to_hex())),
686
        ("author", json::s(&author_name(repo, c))),
687
        ("author_key", json::s(&c.author.to_hex())),
688
        (
689
            "via",
690
            match via(
691
                repo,
692
                &repo.authenticate_change_known(&e.hash, Some(c))?,
693
                &c.author,
694
            ) {
695
                Some(v) => json::obj([
696
                    ("name", json::s(&v.name)),
697
                    ("email", json::s(&v.email)),
698
                    ("key", json::s(&v.key.to_hex())),
699
                    ("scope", json::opt(v.scope.as_deref(), json::s)),
700
                    ("expires_ms", json::opt(v.expires, json::n)),
701
                    ("revoked", json::b(v.revoked)),
702
                ]),
703
                None => "null".to_string(),
704
            },
705
        ),
706
        ("when_ms", json::n(c.hlc.wall_ms)),
707
        ("message", json::s(&c.message)),
708
        ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())),
709
        ("deps", json::hashes(&c.deps)),
710
        ("head", json::b(e.is_head)),
711
        ("working_copy", json::b(e.is_working_copy)),
712
        (
713
            "signature",
714
            if e.is_working_copy {
715
                "null".into()
716
            } else {
717
                signature_json(repo, &e.hash)?
718
            },
719
        ),
720
    ]))
721
}
722
723
/// `START,END:PATH` for `oxy log -L`.
724
fn parse_line_range(spec: &str) -> Result<(usize, usize, &str)> {
725
    let bad = || anyhow::anyhow!("-L {spec}: expected START,END:PATH, as 10,24:src/lib.rs");
726
    let (range, path) = spec.split_once(':').ok_or_else(bad)?;
727
    let (a, b) = range.split_once(',').ok_or_else(bad)?;
728
    Ok((
729
        a.trim().parse().map_err(|_| bad())?,
730
        b.trim().parse().map_err(|_| bad())?,
731
        path,
732
    ))
733
}
734
735
pub fn log(
736
    revset: Option<&str>,
737
    limit: Option<usize>,
738
    verbose: bool,
739
    path: Option<&str>,
740
    lines: Option<&str>,
741
    as_json: bool,
742
) -> Result<i32> {
743
    let repo = open()?;
744
    // Whether the working copy is clean and conflicted: from the manifest
745
    // when it proves the working copy clean, else from a snapshot.
746
    // The working copy as last recorded, without looking at the files (as
747
    // Git's log does not): whether its change holds edits, and whether its
748
    // base was conflicted. `oxy status` is what checks the disk.
749
    let conflicted = !repo.is_at_op() && repo.recorded_conflicted()?;
750
    let listing = oxy_core::timing::phase("log: entries");
751
    let entries = match (path, lines) {
752
        _ if revset.is_some() => repo.log_revset(revset.unwrap_or_default())?,
753
        (_, Some(spec)) => {
754
            let (first, last, p) = parse_line_range(spec)?;
755
            let (_, wc) = repo.working_copy()?;
756
            let base = repo.load_state_history(&wc.deps)?.maximal(&wc.deps);
757
            repo.line_history(&base, p, first, last)?
758
        }
759
        (Some(p), None) => repo.log_for_path(p)?,
760
        (None, None) => repo.log()?,
761
    };
762
    drop(listing);
763
    let _print = oxy_core::timing::phase("log: print");
764
    if as_json {
765
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
766
        let mut items = Vec::new();
767
        for e in entries.iter().take(shown) {
768
            items.push(log_entry_json(&repo, e)?);
769
        }
770
        println!(
771
            "{}",
772
            json::obj([
773
                ("bookmark", json::s(&repo.config.bookmark)),
774
                ("total", json::n(entries.len())),
775
                ("changes", json::arr(items))
776
            ])
777
        );
778
        return Ok(0);
779
    }
780
    let total = entries.len();
781
    let shown = limit.unwrap_or(total).min(total);
782
    // Lay out a little past what is shown, so edges into the cut are drawn.
783
    let window: Vec<(ChangeHash, Vec<ChangeHash>)> = entries
784
        .iter()
785
        .take((shown + MAX_EDGE).min(total))
786
        .map(|e| (e.hash, e.change.deps.clone()))
787
        .collect();
788
    let rows = oxy_core::lanes::graph(&window, MAX_EDGE);
789
    // Highlight the shortest prefix that names each change: against the
790
    // whole log, which is what `resolve_change` searches.
791
    let everything;
792
    let all = if path.is_some() || lines.is_some() || revset.is_some() {
793
        everything = repo.log()?;
794
        &everything
795
    } else {
796
        &entries
797
    };
798
    let prefixes = oxy_core::timing::phase("log: id prefixes");
799
    let id_prefix = id_prefixes(
800
        all.iter().map(|e| e.change.change_id.0).collect(),
801
        entries.iter().take(shown).map(|e| e.change.change_id.0),
802
    );
803
    drop(prefixes);
804
    let labels = reference_labels(&repo)?;
805
    for (e, row) in entries.iter().take(shown).zip(&rows) {
806
        let c = &e.change;
807
        let bullet = ui::log_bullet(
808
            e.is_working_copy,
809
            e.is_head,
810
            e.is_working_copy && conflicted,
811
        );
812
        let id = c.change_id.to_hex();
813
        let n = id_prefix.get(&c.change_id.0).copied().unwrap_or(8).min(8);
814
        let mut head = vec![format!("{}{}", ui::id(&id[..n]), ui::dim(&id[n..8]))];
815
        head.push(ui::author(author_name(&repo, c)));
816
        head.push(ui::dim(ui::ago(c.hlc.wall_ms)));
817
        if let Some(names) = labels.get(&e.hash) {
818
            head.push(names.join(" "));
819
        }
820
        if c.kind == ChangeKind::Resolution {
821
            head.push(ui::warn("resolution"));
822
        }
823
        if !e.is_working_copy {
824
            head.push(ui::hash(format!("#{}", e.hash.short(8))));
825
            let status = repo.authenticate_change_known(&e.hash, Some(c))?;
826
            if let Some(agent) = via(&repo, &status, &c.author) {
827
                head.push(ui::dim(format!("via {}", agent.name)));
828
            }
829
            head.push(signature_mark_of(&status));
830
        }
831
        println!("{}{}", node_line(row, &bullet), head.join(" "));
832
        let subject = if e.is_working_copy && c.message.is_empty() {
833
            let edited = repo
834
                .store()
835
                .get_change(&e.hash)
836
                .is_ok_and(|w| !w.tree_ops.is_empty() || !w.edits.is_empty());
837
            ui::dim(if edited {
838
                "(working copy, uncommitted changes)"
839
            } else {
840
                "(working copy)"
841
            })
842
        } else if c.message.trim().is_empty() {
843
            ui::dim("(no description)")
844
        } else {
845
            subject_of(&c.message).to_string()
846
        };
847
        println!("{}{subject}", below_line(row));
848
        if verbose {
849
            let rail = continuation(row);
850
            if !e.is_working_copy {
851
                println!(
852
                    "{rail}{}",
853
                    ui::dim(format!(
854
                        "{} {}",
855
                        when(c.hlc.wall_ms),
856
                        signature_line(&repo, &e.hash)?
857
                    ))
858
                );
859
            }
860
            if !c.deps.is_empty() {
861
                println!(
862
                    "{rail}{} {}",
863
                    ui::dim(ui::glyph("↳", "->")),
864
                    ui::dim(deps_of(&c.deps))
865
                );
866
            }
867
            let body: Vec<&str> = c
868
                .message
869
                .lines()
870
                .skip(1)
871
                .skip_while(|l| l.trim().is_empty())
872
                .collect();
873
            for line in body {
874
                println!("{rail}  {line}");
875
            }
876
        }
877
    }
878
    if shown < total {
879
        if let Some(last) = rows.get(shown.saturating_sub(1)) {
880
            let cut: String = last
881
                .below
882
                .iter()
883
                .map(|c| match c {
884
                    Cell::Blank | Cell::Elided | Cell::JoinRight => "  ",
885
                    _ => "~ ",
886
                })
887
                .collect();
888
            if cut.trim().is_empty() {
889
                println!("{}", ui::dim("~"));
890
            } else {
891
                println!("{}", ui::dim(cut.trim_end()));
892
            }
893
        }
894
        println!(
895
            "{}",
896
            ui::dim(format!(
897
                "{} {} more; pass -n to see them",
898
                ui::glyph("…", "..."),
899
                total - shown
900
            ))
901
        );
902
    }
903
    Ok(0)
904
}
905
906
/// Rows a drawn edge may span in `oxy log`; a longer one is elided (`~`).
907
const MAX_EDGE: usize = 12;
908
909
use oxy_core::hash::ChangeHash;
910
use oxy_core::lanes::{Cell, GraphRow};
911
912
/// A graph cell, two columns wide.
913
fn cell(c: Cell) -> &'static str {
914
    match c {
915
        Cell::Blank => "  ",
916
        Cell::Line => ui::glyph("│ ", "| "),
917
        Cell::Elided => "~ ",
918
        Cell::JoinLeft => ui::glyph("├─", "|-"),
919
        Cell::JoinPass => ui::glyph("──", "--"),
920
        Cell::JoinCross => ui::glyph("┼─", "+-"),
921
        Cell::JoinRight => ui::glyph("╯ ", "' "),
922
    }
923
}
924
925
/// The graph part of a change's own line, its bullet in its column.
926
fn node_line(row: &GraphRow, bullet: &str) -> String {
927
    let width = row
928
        .passing
929
        .iter()
930
        .copied()
931
        .max()
932
        .unwrap_or(0)
933
        .max(row.column)
934
        + 1;
935
    let mut out = String::new();
936
    for c in 0..width {
937
        if c == row.column {
938
            out.push_str(bullet);
939
            out.push(' ');
940
        } else if row.passing.contains(&c) {
941
            out.push_str(&ui::dim(cell(Cell::Line)));
942
        } else {
943
            out.push_str("  ");
944
        }
945
    }
946
    out.push(' ');
947
    out
948
}
949
950
/// The graph part of the line under a change: lanes carrying on, a join,
951
/// or `~` for an elided edge.
952
fn below_line(row: &GraphRow) -> String {
953
    let g: String = row.below.iter().map(|c| cell(*c)).collect();
954
    format!("{} ", ui::dim(g))
955
}
956
957
/// The graph part of any further line of a change (`-v`).
958
fn continuation(row: &GraphRow) -> String {
959
    let g: String = row
960
        .below
961
        .iter()
962
        .map(|c| match c {
963
            Cell::Line | Cell::JoinLeft | Cell::JoinCross => cell(Cell::Line),
964
            _ => "  ",
965
        })
966
        .collect();
967
    format!("{} ", ui::dim(g))
968
}
969
970
/// For each hex ID, the length of its shortest prefix no other ID shares.
971
/// The shortest prefix, in hex digits, that names each of `wanted` among
972
/// `all`: worked out for the few shown rather than for the whole history.
973
fn id_prefixes(
974
    mut all: Vec<[u8; 16]>,
975
    wanted: impl Iterator<Item = [u8; 16]>,
976
) -> std::collections::HashMap<[u8; 16], usize> {
977
    all.sort_unstable();
978
    all.dedup();
979
    // Hex digits two ids share at the start.
980
    let common = |a: &[u8; 16], b: &[u8; 16]| {
981
        let bytes = a.iter().zip(b).take_while(|(x, y)| x == y).count();
982
        match (a.get(bytes), b.get(bytes)) {
983
            (Some(x), Some(y)) if x >> 4 == y >> 4 => 2 * bytes + 1,
984
            _ => 2 * bytes,
985
        }
986
    };
987
    let mut out = std::collections::HashMap::new();
988
    for id in wanted {
989
        let Ok(i) = all.binary_search(&id) else {
990
            continue;
991
        };
992
        let before = i.checked_sub(1).map_or(0, |j| common(&all[j], &id));
993
        let after = all.get(i + 1).map_or(0, |n| common(&id, n));
994
        out.insert(id, before.max(after) + 1);
995
    }
996
    out
997
}
998
999
fn unique_prefixes(ids: impl Iterator<Item = String>) -> std::collections::HashMap<String, usize> {
1000
    let mut v: Vec<String> = ids.collect();
1001
    v.sort();
1002
    v.dedup();
1003
    let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
1004
    let mut out = std::collections::HashMap::with_capacity(v.len());
1005
    for i in 0..v.len() {
1006
        let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 };
1007
        let after = if i + 1 < v.len() {
1008
            common(&v[i], &v[i + 1])
1009
        } else {
1010
            0
1011
        };
1012
        out.insert(v[i].clone(), before.max(after) + 1);
1013
    }
1014
    out
1015
}
1016
1017
/// Bookmark, remote bookmark and tag names to show beside the changes they
1018
/// point at. A name is shown on each head of its state; one with more than
1019
/// three heads names too much of the log to help, so it is left out (oxy
1020
/// bookmark list shows it). A remote bookmark at the same state as the
1021
/// local one of that name is not repeated.
1022
fn reference_labels(repo: &Repo) -> Result<std::collections::HashMap<ChangeHash, Vec<String>>> {
1023
    const MAX_HEADS: usize = 3;
1024
    let view = repo.view()?;
1025
    let mut out: std::collections::HashMap<ChangeHash, Vec<String>> = Default::default();
1026
    let mut add = |heads: Vec<ChangeHash>, label: String| {
1027
        if heads.len() <= MAX_HEADS {
1028
            for h in heads {
1029
                out.entry(h).or_default().push(label.clone());
1030
            }
1031
        }
1032
    };
1033
    for (name, st) in &view.bookmarks {
1034
        add(repo.store().get_state(st)?.heads, ui::bookmark(name));
1035
    }
1036
    for (remote, bookmarks) in &view.remotes {
1037
        for (name, st) in bookmarks {
1038
            if view.bookmarks.get(name) == Some(st) {
1039
                continue;
1040
            }
1041
            add(
1042
                repo.store().get_state(st)?.heads,
1043
                ui::dim(format!("{remote}/{name}")),
1044
            );
1045
        }
1046
    }
1047
    for t in repo.tags()? {
1048
        add(t.heads.clone(), ui::warn(&t.name));
1049
    }
1050
    Ok(out)
1051
}
1052
1053
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
1054
    let repo = open()?;
1055
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
1056
    if as_json {
1057
        let files = repo.diff_files(hash.as_ref())?;
1058
        let items = files.iter().map(|f| {
1059
            json::obj([
1060
                ("path", json::s(&f.path)),
1061
                ("kind", json::s(&f.kind)),
1062
                ("from", json::opt(f.from.as_deref(), json::s)),
1063
                (
1064
                    "hunks",
1065
                    json::arr(f.hunks.iter().map(|h| {
1066
                        json::obj([
1067
                            ("base_line", json::n(h.base_line)),
1068
                            (
1069
                                "added",
1070
                                json::arr(
1071
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
1072
                                ),
1073
                            ),
1074
                            (
1075
                                "removed",
1076
                                json::arr(h.removed.iter().map(|(n, l)| {
1077
                                    json::obj([
1078
                                        ("line", json::n(*n)),
1079
                                        ("text", json::s(&String::from_utf8_lossy(l))),
1080
                                    ])
1081
                                })),
1082
                            ),
1083
                        ])
1084
                    })),
1085
                ),
1086
            ])
1087
        });
1088
        println!(
1089
            "{}",
1090
            json::obj([
1091
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
1092
                ("files", json::arr(items))
1093
            ])
1094
        );
1095
        return Ok(0);
1096
    }
1097
    match hash {
1098
        Some(h) => {
1099
            let c = repo.store().get_change(&h)?;
1100
            let (base, snapshot) = repo.change_base(&c)?;
1101
            print!("{}", render_change(&c, &base, &snapshot));
1102
        }
1103
        None => {
1104
            let (wc, base, snapshot) = repo.working_copy_with_base()?;
1105
            let text = {
1106
                let _t = oxy_core::timing::phase("diff: render the change");
1107
                render_change(&wc, &base, &snapshot)
1108
            };
1109
            print!("{text}");
1110
            // The process ends here: freeing the base's tree and graphs
1111
            // one by one would only cost time (about 27 ms on Linux).
1112
            std::mem::forget((wc, base, snapshot));
1113
        }
1114
    }
1115
    Ok(0)
1116
}
1117
1118
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
1119
    let repo = open()?;
1120
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
1121
    let bytes = repo.file_at(path, heads.as_deref())?;
1122
    use std::io::Write as _;
1123
    std::io::stdout().write_all(&bytes)?;
1124
    Ok(0)
1125
}
1126
1127
pub fn root(as_json: bool) -> Result<i32> {
1128
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
1129
        if as_json {
1130
            println!("null");
1131
        }
1132
        return Ok(1);
1133
    };
1134
    if as_json {
1135
        println!(
1136
            "{}",
1137
            json::obj([
1138
                ("root", json::s(&repo.root().to_string_lossy())),
1139
                ("workspace", json::s(&repo.workspace().to_hex())),
1140
                ("bookmark", json::s(&repo.config.bookmark))
1141
            ])
1142
        );
1143
    } else {
1144
        println!("{}", repo.root().display());
1145
    }
1146
    Ok(0)
1147
}
1148
1149
pub fn version(as_json: bool) -> Result<i32> {
1150
    if as_json {
1151
        println!(
1152
            "{}",
1153
            json::obj([
1154
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
1155
                // What was built: a release's or install's `oxy describe`,
1156
                // a Flow build's heads, or "local build".
1157
                ("build", json::s(env!("OXY_BUILD_ID"))),
1158
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
1159
                ("format", json::n(2))
1160
            ])
1161
        );
1162
    } else {
1163
        println!(
1164
            "oxy {} (repository format 2, protocol {})",
1165
            env!("OXY_VERSION_LONG"),
1166
            oxy_core::protocol::PROTOCOL_VERSION
1167
        );
1168
    }
1169
    Ok(0)
1170
}
1171
1172
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
1173
    let repo = open()?;
1174
    if paths.is_empty() && hunks.is_empty() {
1175
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
1176
    }
1177
    let mut n = 0;
1178
    if !hunks.is_empty() {
1179
        n += repo.discard_hunks(hunks)?;
1180
    }
1181
    if !paths.is_empty() {
1182
        n += repo.discard(paths)?;
1183
    }
1184
    println!(
1185
        "{} {} restored to the working copy's base",
1186
        ui::done("Discarded"),
1187
        plural(n, "path")
1188
    );
1189
    Ok(0)
1190
}
1191
1192
pub fn hunks(as_json: bool) -> Result<i32> {
1193
    let repo = open()?;
1194
    let (_, hunks) = repo.hunks()?;
1195
    if as_json {
1196
        println!(
1197
            "{}",
1198
            json::arr(hunks.iter().map(|h| json::obj([
1199
                ("index", json::n(h.index)),
1200
                ("path", json::s(&h.path)),
1201
                ("text", json::s(&h.text))
1202
            ])))
1203
        );
1204
        return Ok(0);
1205
    }
1206
    if hunks.is_empty() {
1207
        println!(
1208
            "{}",
1209
            ui::dim("No hunks: the working copy matches its base.")
1210
        );
1211
    }
1212
    for h in &hunks {
1213
        println!(
1214
            "{} {}",
1215
            ui::section(format!("hunk {}", h.index)),
1216
            ui::path(&h.path)
1217
        );
1218
        for line in h.text.lines() {
1219
            let styled = if line.starts_with('+') {
1220
                ui::ok(line)
1221
            } else if line.starts_with('-') {
1222
                ui::err(line)
1223
            } else {
1224
                ui::dim(line)
1225
            };
1226
            println!("  {styled}");
1227
        }
1228
    }
1229
    Ok(0)
1230
}
1231
1232
pub fn show(change: Option<&str>, revset: Option<&str>, stat: bool, as_json: bool) -> Result<i32> {
1233
    let repo = open()?;
1234
    repo.snapshot_status("oxy show")?;
1235
    let Some(r) = revset else {
1236
        let h = repo.resolve_change(change.unwrap_or("@"))?;
1237
        return show_one(&repo, h, as_json, false, stat);
1238
    };
1239
    // Several changes: a JSON array, or the changes one after another.
1240
    let hashes = repo.revset(r)?.hashes;
1241
    if as_json {
1242
        print!("[");
1243
        for (i, h) in hashes.iter().enumerate() {
1244
            if i > 0 {
1245
                print!(",");
1246
            }
1247
            show_one(&repo, *h, true, true, stat)?;
1248
        }
1249
        println!("]");
1250
        return Ok(0);
1251
    }
1252
    if hashes.is_empty() {
1253
        println!("{}", ui::dim(format!("No change matches {r:?}.")));
1254
        return Ok(0);
1255
    }
1256
    for (i, h) in hashes.iter().enumerate() {
1257
        if i > 0 {
1258
            println!();
1259
        }
1260
        show_one(&repo, *h, false, false, stat)?;
1261
    }
1262
    Ok(0)
1263
}
1264
1265
/// Lines added and removed in one file's diff.
1266
fn counts(f: &oxy_core::repo::FileDiff) -> (usize, usize) {
1267
    f.hunks
1268
        .iter()
1269
        .fold((0, 0), |(a, r), h| (a + h.added.len(), r + h.removed.len()))
1270
}
1271
1272
/// What `--stat` prints (oxygen#119): each file the change touched, its
1273
/// lines added and removed, then the total.
1274
fn print_stat(files: &[oxy_core::repo::FileDiff]) {
1275
    let width = files
1276
        .iter()
1277
        .map(|f| f.path.chars().count())
1278
        .max()
1279
        .unwrap_or(0)
1280
        .min(60);
1281
    let (mut added, mut removed) = (0, 0);
1282
    for f in files {
1283
        let (a, r) = counts(f);
1284
        added += a;
1285
        removed += r;
1286
        let path = match &f.from {
1287
            Some(from) => format!("{from} → {}", f.path),
1288
            None => f.path.clone(),
1289
        };
1290
        println!(
1291
            " {path:<width$}  {} {}  {}",
1292
            ui::ok(format!("{:>6}", format!("+{a}"))),
1293
            ui::err(format!("{:>6}", format!("-{r}"))),
1294
            ui::dim(&f.kind)
1295
        );
1296
    }
1297
    println!(
1298
        " {}",
1299
        ui::dim(format!(
1300
            "{} changed, {added} added, {removed} removed",
1301
            plural(files.len(), "file")
1302
        ))
1303
    );
1304
}
1305
1306
/// One change, as `oxy show` prints it; `inline` JSON goes without its
1307
/// newline, for an array. `stat` lists the files instead of the diff.
1308
fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool, stat: bool) -> Result<i32> {
1309
    let c = repo.store().get_change(&h)?;
1310
    if as_json {
1311
        let files = repo.diff_files(Some(&h))?;
1312
        let heads = repo.bookmark_heads()?;
1313
        let entry = oxy_core::repo::LogEntry {
1314
            hash: h,
1315
            change: oxy_core::state::ChangeMeta::of(&c),
1316
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
1317
            is_head: heads.contains(&h),
1318
        };
1319
        let mut body = log_entry_json(repo, &entry)?;
1320
        body.pop();
1321
        body.push_str(&format!(
1322
            ",{}:{}}}",
1323
            json::s("files"),
1324
            json::arr(files.iter().map(|f| {
1325
                let (a, r) = counts(f);
1326
                json::obj([
1327
                    ("path", json::s(&f.path)),
1328
                    ("kind", json::s(&f.kind)),
1329
                    ("from", json::opt(f.from.as_deref(), json::s)),
1330
                    ("added", a.to_string()),
1331
                    ("removed", r.to_string()),
1332
                ])
1333
            }))
1334
        ));
1335
        if inline {
1336
            print!("{body}");
1337
        } else {
1338
            println!("{body}");
1339
        }
1340
        return Ok(0);
1341
    }
1342
    println!(
1343
        "{} {} {}",
1344
        ui::section("change"),
1345
        ui::id(short_id(&c)),
1346
        ui::hash(format!("#{h}"))
1347
    );
1348
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1349
    // Fetched but not pulled (oxygen#56): say where it is.
1350
    if let Some(at) = repo.remote_only_location(&h)? {
1351
        println!(
1352
            "{}",
1353
            ui::kv(
1354
                "only in",
1355
                ui::warn(format!(
1356
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
1357
                ))
1358
            )
1359
        );
1360
    }
1361
    let meta = oxy_core::state::ChangeMeta::of(&c);
1362
    let status = repo.authenticate_change_known(&h, Some(&meta))?;
1363
    println!("{}", ui::kv("author", ui::author(author_name(repo, &meta))));
1364
    if let Some(agent) = via(repo, &status, &meta.author) {
1365
        println!("{}", ui::kv("via", agent.line()));
1366
    }
1367
    println!(
1368
        "{}",
1369
        ui::kv(
1370
            "date",
1371
            format!(
1372
                "{} {}",
1373
                when(c.hlc.wall_ms),
1374
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1375
            )
1376
        )
1377
    );
1378
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
1379
    println!("{}", ui::kv("sig", signature_line(repo, &h)?));
1380
    println!();
1381
    for line in (if c.message.is_empty() {
1382
        "(no description)"
1383
    } else {
1384
        &c.message
1385
    })
1386
    .lines()
1387
    {
1388
        println!("    {line}");
1389
    }
1390
    println!();
1391
    if stat {
1392
        print_stat(&repo.diff_files(Some(&h))?);
1393
    } else {
1394
        print!("{}", repo.describe_change(&h)?);
1395
    }
1396
    Ok(0)
1397
}
1398
1399
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
1400
    let repo = open()?;
1401
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1402
    // BRANCH` is: checking its files out under another bookmark's name
1403
    // made the next commit move the wrong bookmark (oxygen#60).
1404
    if let [name] = changes {
1405
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
1406
            drop(repo);
1407
            return bookmark_switch(name, discard, carry);
1408
        }
1409
    }
1410
    let heads = if changes.is_empty() {
1411
        repo.bookmark_heads()?
1412
    } else {
1413
        let mut heads = Vec::new();
1414
        for c in changes {
1415
            heads.extend(repo.resolve_heads(c)?);
1416
        }
1417
        heads
1418
    };
1419
    let spec = if changes.is_empty() {
1420
        repo.config.bookmark.clone()
1421
    } else {
1422
        changes.join(" ")
1423
    };
1424
    let sp = ui::spinner(&format!("Checking out {spec}…"));
1425
    let command = format!("oxy checkout {spec}");
1426
    let (r, carried) = if carry {
1427
        repo.checkout_carry(&heads, &spec, &command)?
1428
    } else {
1429
        (repo.checkout(&heads, discard, &command)?, vec![])
1430
    };
1431
    sp.done(&format!(
1432
        "{} on {}: {} written, {} removed{}",
1433
        ui::done("Working copy"),
1434
        ui::bookmark(&spec),
1435
        plural(r.written, "file"),
1436
        r.removed,
1437
        if carried.is_empty() {
1438
            String::new()
1439
        } else {
1440
            format!("; carried {}", plural(carried.len(), "changed path"))
1441
        }
1442
    ));
1443
    print_removed(&r);
1444
    for n in &r.notes {
1445
        println!("  {} {n}", ui::note());
1446
    }
1447
    print_kept_both(&r);
1448
    if r.conflicted {
1449
        println!(
1450
            "  {} {}",
1451
            ui::caution(),
1452
            ui::warn("this state has conflicts; see oxy status")
1453
        );
1454
    }
1455
    where_now(&repo);
1456
    Ok(0)
1457
}
1458
1459
/// Union files (`merge=union`, oxygen#145) a checkout settled itself.
1460
fn print_kept_both(r: &oxy_core::repo::CheckoutReport) {
1461
    for k in &r.kept_both {
1462
        let how = if k.identical.len() == k.settled.len() {
1463
            "kept one of its identical sides"
1464
        } else if k.identical.is_empty() {
1465
            "kept both sides (merge=union)"
1466
        } else {
1467
            "kept one of identical sides and both of others (merge=union)"
1468
        };
1469
        println!(
1470
            "  {} settled {}: {how}; the next commit records it",
1471
            ui::note(),
1472
            ui::path(&k.path)
1473
        );
1474
    }
1475
}
1476
1477
pub fn resolve(paths: &[String], both: bool, reverse: bool, as_json: bool) -> Result<i32> {
1478
    let repo = open()?;
1479
    let mut snap = repo.snapshot("oxy resolve")?;
1480
    let paths: Vec<String> = paths
1481
        .iter()
1482
        .map(|p| p.trim_start_matches("./").trim_end_matches('/').to_string())
1483
        .collect();
1484
    if both {
1485
        // Adjacent insertions (oxygen#121): every side kept, in order.
1486
        let kept = repo.keep_both(&snap, &paths, reverse)?;
1487
        if !as_json {
1488
            for k in &kept {
1489
                if !k.settled.is_empty() {
1490
                    let n: Vec<String> = k.settled.iter().map(|n| n.to_string()).collect();
1491
                    println!("kept both  {}: conflict {}", k.path, n.join(", "));
1492
                }
1493
                for (n, why) in &k.left {
1494
                    println!("markers    {}: conflict {n}: {why}", k.path);
1495
                }
1496
            }
1497
        }
1498
        snap = repo.snapshot("oxy resolve")?;
1499
    } else if !paths.is_empty() {
1500
        // A replace conflict has no markers to edit out: the user says which
1501
        // content wins (oxygen#140, spec §9.3), and the snapshot builds it.
1502
        repo.choose_resolutions(&snap.base_snapshot, &paths)?;
1503
        snap = repo.snapshot("oxy resolve")?;
1504
    }
1505
    if as_json {
1506
        println!("{}", repo.status_json(&snap)?);
1507
        return Ok(if snap.base_snapshot.is_conflicted() {
1508
            2
1509
        } else {
1510
            0
1511
        });
1512
    }
1513
    if !snap.base_snapshot.is_conflicted() {
1514
        println!("The working copy's base has no conflicts.");
1515
        return Ok(0);
1516
    }
1517
    let mut remaining = 0;
1518
    for (p, f) in &snap.base_snapshot.files {
1519
        if !f.is_conflicted() {
1520
            continue;
1521
        }
1522
        match snap
1523
            .statuses
1524
            .iter()
1525
            .find(|s| s.path == *p)
1526
            .map(|s| s.status)
1527
        {
1528
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
1529
            Some(ChangeStatus::ConflictEdited) => {
1530
                remaining += 1;
1531
                println!("markers    {p}");
1532
            }
1533
            _ => {
1534
                remaining += 1;
1535
                println!("unresolved {p}");
1536
            }
1537
        }
1538
    }
1539
    for c in &snap.base_snapshot.tree.conflicts {
1540
        remaining += 1;
1541
        println!("tree       {c:?}");
1542
    }
1543
    if remaining == 0 {
1544
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
1545
        Ok(0)
1546
    } else {
1547
        Ok(2)
1548
    }
1549
}
1550
1551
pub fn undo() -> Result<i32> {
1552
    let repo = open()?;
1553
    let u = repo.undo()?;
1554
    println!("{} {}", ui::done("Undone:"), u.command);
1555
    for c in &u.changes {
1556
        println!("  {} {}", ui::note(), change_words(&repo, c));
1557
    }
1558
    if u.others_kept > 0 {
1559
        let s = if u.others_kept == 1 { "" } else { "s" };
1560
        println!(
1561
            "  {} {}",
1562
            ui::note(),
1563
            ui::dim(format!(
1564
                "{} newer operation{s} from other workspaces left as they are",
1565
                u.others_kept
1566
            ))
1567
        );
1568
    }
1569
    for (bookmark, remote) in &u.pushed {
1570
        println!(
1571
            "  {} {}",
1572
            ui::caution(),
1573
            ui::warn(format!(
1574
                "{remote}/{bookmark} already has what this undid: undone here only; the next push of {bookmark} needs --force to take it back there"
1575
            ))
1576
        );
1577
    }
1578
    where_now(&repo);
1579
    Ok(0)
1580
}
1581
1582
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
1583
    let repo = open()?;
1584
    let ops = repo.op_log()?;
1585
    // What each operation changed, against the one before it.
1586
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
1587
        match ops.get(i + 1) {
1588
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
1589
            None => Ok(vec![]),
1590
        }
1591
    };
1592
    if as_json {
1593
        let mut items = Vec::new();
1594
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
1595
            let summary: Vec<String> = changes_of(i)?
1596
                .iter()
1597
                .map(|c| change_words(&repo, c))
1598
                .collect();
1599
            items.push(json::obj([
1600
                ("id", json::s(&r.to_hex())),
1601
                ("when_ms", json::n(op.hlc.wall_ms)),
1602
                ("command", json::s(&op.command)),
1603
                ("snapshot", json::b(op.is_snapshot())),
1604
                ("current", json::b(i == 0)),
1605
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1606
            ]));
1607
        }
1608
        println!("{}", json::arr(items));
1609
        return Ok(0);
1610
    }
1611
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
1612
    let id = |r: &oxy_core::hash::ObjectRef| {
1613
        let hex = r.to_hex();
1614
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
1615
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
1616
    };
1617
    let rail = ui::dim(ui::glyph("│", "|"));
1618
    let (mut i, mut shown) = (0, 0);
1619
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
1620
        let (r, op) = &ops[i];
1621
        let bullet = if i == 0 {
1622
            ui::ok(ui::glyph("@", "@"))
1623
        } else {
1624
            ui::dim(ui::glyph("○", "o"))
1625
        };
1626
        // A run of snapshots folds into one entry.
1627
        let mut run = 1;
1628
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
1629
            run += 1;
1630
        }
1631
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
1632
        if op.is_snapshot() {
1633
            let span = if run > 1 {
1634
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1635
            } else {
1636
                String::new()
1637
            };
1638
            println!(
1639
                "{bullet}  {}{} {when}",
1640
                id(r),
1641
                if span.is_empty() {
1642
                    String::new()
1643
                } else {
1644
                    format!(" {span}")
1645
                }
1646
            );
1647
            println!(
1648
                "{rail}  {}",
1649
                ui::dim(if run == 1 {
1650
                    "working-copy snapshot".to_string()
1651
                } else {
1652
                    format!("{run} working-copy snapshots")
1653
                })
1654
            );
1655
        } else {
1656
            println!("{bullet}  {} {when}", id(r));
1657
            let words: Vec<String> = changes_of(i)?
1658
                .iter()
1659
                .map(|c| change_words(&repo, c))
1660
                .collect();
1661
            let summary = if words.is_empty() {
1662
                if i + 1 == ops.len() {
1663
                    "created the repository".to_string()
1664
                } else {
1665
                    "no bookmark or working-copy change".to_string()
1666
                }
1667
            } else {
1668
                words.join("; ")
1669
            };
1670
            println!(
1671
                "{rail}  {}",
1672
                if i == 0 {
1673
                    ui::subject(&summary)
1674
                } else {
1675
                    summary
1676
                }
1677
            );
1678
            let cmd = op.command.lines().next().unwrap_or("");
1679
            let cmd: String = cmd.chars().take(100).collect();
1680
            println!("{rail}  {}", ui::dim(cmd));
1681
        }
1682
        i += run;
1683
        shown += 1;
1684
    }
1685
    if i < ops.len() {
1686
        println!(
1687
            "{}",
1688
            ui::dim(format!(
1689
                "{} {} older; pass -n to see more",
1690
                ui::glyph("…", "..."),
1691
                plural(ops.len() - i, "operation")
1692
            ))
1693
        );
1694
    }
1695
    Ok(0)
1696
}
1697
1698
/// One change an operation made, in words.
1699
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1700
    use oxy_core::repo::ViewChange::*;
1701
    match c {
1702
        BookmarkCreated { name, heads } => {
1703
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1704
        }
1705
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
1706
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
1707
        BookmarkMoved { name, from, to } => format!(
1708
            "{name}: {from} {} {}",
1709
            ui::glyph("→", "->"),
1710
            plural(*to, "head")
1711
        ),
1712
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
1713
        TagCreated { name } => format!("tagged {name}"),
1714
        TagDeleted { name } => format!("removed tag {name}"),
1715
        Policy => "trust policy changed".to_string(),
1716
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
1717
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
1718
            Err(_) => "working copy moved".to_string(),
1719
        },
1720
    }
1721
}
1722
1723
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
1724
    let repo = open()?;
1725
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
1726
    let r = repo.op_restore(op, discard)?;
1727
    sp.done(&format!(
1728
        "{} to operation {} {}",
1729
        ui::done("Restored"),
1730
        ui::hash(r.op.short(12)),
1731
        ui::dim(r.command.lines().next().unwrap_or(""))
1732
    ));
1733
    println!(
1734
        "  {} {}",
1735
        ui::note(),
1736
        ui::dim(format!(
1737
            "{} written, {} removed; oxy undo goes back again",
1738
            plural(r.checkout.written, "file"),
1739
            r.checkout.removed
1740
        ))
1741
    );
1742
    where_now(&repo);
1743
    Ok(0)
1744
}
1745
1746
pub fn op_revert(op: &str) -> Result<i32> {
1747
    let repo = open()?;
1748
    let r = repo.op_revert(op)?;
1749
    let view = repo.view()?;
1750
    let names: Vec<String> = r
1751
        .reverted
1752
        .iter()
1753
        .map(|n| {
1754
            if view.bookmarks.contains_key(n) {
1755
                ui::bookmark(n)
1756
            } else {
1757
                format!("{} (removed)", ui::bookmark(n))
1758
            }
1759
        })
1760
        .collect();
1761
    println!(
1762
        "{} operation {} {}",
1763
        ui::done("Reverted"),
1764
        ui::hash(r.op.short(12)),
1765
        ui::dim(r.command.lines().next().unwrap_or(""))
1766
    );
1767
    println!(
1768
        "  {} {}",
1769
        ui::note(),
1770
        ui::dim(format!("as before it: {}", names.join(", ")))
1771
    );
1772
    if !r.kept.is_empty() {
1773
        println!(
1774
            "  {} {}",
1775
            ui::caution(),
1776
            ui::warn(format!(
1777
                "left as they are, having moved again since: {}",
1778
                r.kept.join(", ")
1779
            ))
1780
        );
1781
    }
1782
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
1783
        println!(
1784
            "  {} {}",
1785
            ui::note(),
1786
            ui::dim("the working copy has work of its own: oxy checkout to move it")
1787
        );
1788
    }
1789
    where_now(&repo);
1790
    Ok(0)
1791
}
1792
1793
/// Where the working copy and bookmark are now, after a command moved
1794
/// them (as jj says "Working copy now at").
1795
pub fn where_now(repo: &Repo) {
1796
    let Ok((_, wc)) = repo.working_copy() else {
1797
        return;
1798
    };
1799
    let heads = repo.bookmark_heads().unwrap_or_default();
1800
    let newest = heads
1801
        .iter()
1802
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
1803
        .max_by_key(|(m, _)| m.hlc);
1804
    println!(
1805
        "  {} {}",
1806
        ui::dim(format!("{:<13}", "Working copy")),
1807
        ui::id(wc.change_id.short(8))
1808
    );
1809
    let tail = match newest {
1810
        Some((m, _)) => format!(
1811
            ", newest {} {}",
1812
            ui::id(m.change_id.short(8)),
1813
            subject_of(&m.message)
1814
        ),
1815
        None => String::new(),
1816
    };
1817
    println!(
1818
        "  {} {}: {}{tail}",
1819
        ui::dim(format!("{:<13}", "Bookmark")),
1820
        ui::bookmark(&repo.config.bookmark),
1821
        plural(heads.len(), "head")
1822
    );
1823
}
1824
1825
pub fn gc(now: bool, expire_snapshots: bool) -> Result<i32> {
1826
    let mut repo = open()?;
1827
    if expire_snapshots {
1828
        repo.config.snapshot_retention_days = 0;
1829
    }
1830
    let sp = ui::spinner("Packing and pruning…");
1831
    // Cylinder's artifacts are named from outside the history: keep them.
1832
    let artifacts = cylinder::roots(&repo)?;
1833
    let r = repo.gc_keeping(now, &artifacts, &mut |phase| sp.set(&format!("{phase}…")))?;
1834
    sp.clear();
1835
    if r.packed.objects > 0 {
1836
        println!(
1837
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
1838
            plural(r.packed.objects, "object"),
1839
            r.packed.raw_bytes,
1840
            r.packed.packed_bytes,
1841
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
1842
        );
1843
    }
1844
    println!(
1845
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
1846
        plural(r.reachable, "object"),
1847
        plural(r.pruned.objects, "unreachable object"),
1848
        r.pruned.bytes,
1849
        if r.pruned.deferred > 0 {
1850
            format!(
1851
                "; {} deferred by the grace period (use --now)",
1852
                plural(r.pruned.deferred, "object")
1853
            )
1854
        } else {
1855
            String::new()
1856
        },
1857
        if r.merged_packs > 0 {
1858
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1859
        } else {
1860
            String::new()
1861
        },
1862
        plural(repo.store().pack_count(), "pack")
1863
    );
1864
    // What earlier repacks replaced stays an hour for readers still using
1865
    // it (oxygenhub#249); a collection after that deletes it.
1866
    let kept = if r.retired.kept > 0 {
1867
        format!(
1868
            "{} retired less than an hour ago kept for readers",
1869
            plural(r.retired.kept, "file")
1870
        )
1871
    } else {
1872
        String::new()
1873
    };
1874
    if r.retired.packs + r.retired.loose > 0 {
1875
        println!(
1876
            "Deleted {} and {} retired by earlier repacks{}.",
1877
            plural(r.retired.packs, "pack"),
1878
            plural(r.retired.loose, "loose object"),
1879
            if kept.is_empty() {
1880
                String::new()
1881
            } else {
1882
                format!("; {kept}")
1883
            }
1884
        );
1885
    } else if !kept.is_empty() {
1886
        println!("{kept}.");
1887
    }
1888
    Ok(0)
1889
}
1890
1891
/// `oxy gc --remote NAME`: fold a store remote's bundles into one.
1892
pub fn gc_remote(name: &str, now: bool) -> Result<i32> {
1893
    let repo = open()?;
1894
    let sp = ui::spinner(&format!("Folding {name}'s bundles…"));
1895
    let r = repo.gc_remote(name, now)?;
1896
    sp.clear();
1897
    if r.merged > 0 {
1898
        println!(
1899
            "{} {} into one of {} bytes ({})",
1900
            ui::done("Folded"),
1901
            plural(r.merged, "bundle"),
1902
            r.bundle_bytes,
1903
            plural(r.changes, "change")
1904
        );
1905
    } else {
1906
        println!(
1907
            "{} {}",
1908
            ui::note(),
1909
            ui::dim("nothing to fold: one bundle holds everything")
1910
        );
1911
    }
1912
    println!(
1913
        "  {} {}",
1914
        ui::note(),
1915
        ui::dim(format!(
1916
            "removed {}{}",
1917
            plural(r.deleted, "superseded bundle"),
1918
            if r.deferred > 0 {
1919
                format!(
1920
                    "; {} kept for readers that may still fetch them (use --now)",
1921
                    plural(r.deferred, "bundle")
1922
                )
1923
            } else {
1924
                String::new()
1925
            }
1926
        ))
1927
    );
1928
    Ok(0)
1929
}
1930
1931
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
1932
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1933
    use oxy_core::repo::Health;
1934
    let repo = open()?;
1935
    let sp = ui::spinner(if offline {
1936
        "Checking…"
1937
    } else {
1938
        "Checking, and contacting remotes…"
1939
    });
1940
    let r = repo.doctor(!offline);
1941
    sp.clear();
1942
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
1943
    let word = |h: Health| match h {
1944
        Health::Ok => "ok",
1945
        Health::Warn => "warning",
1946
        Health::Fail => "fail",
1947
    };
1948
    if as_json {
1949
        let checks: Vec<String> = r
1950
            .checks
1951
            .iter()
1952
            .map(|c| {
1953
                json::obj([
1954
                    ("area", json::s(&c.area)),
1955
                    ("health", json::s(word(c.health))),
1956
                    ("message", json::s(&c.message)),
1957
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
1958
                ])
1959
            })
1960
            .collect();
1961
        println!(
1962
            "{}",
1963
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1964
        );
1965
        return Ok(code);
1966
    }
1967
    let mut last = "";
1968
    for c in &r.checks {
1969
        if c.area != last {
1970
            println!("{}", ui::section(&c.area));
1971
            last = &c.area;
1972
        }
1973
        let mark = match c.health {
1974
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
1975
            Health::Warn => ui::caution(),
1976
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1977
        };
1978
        println!("  {mark} {}", c.message);
1979
        if let Some(h) = &c.hint {
1980
            println!("    {} {}", ui::dim("→"), ui::dim(h));
1981
        }
1982
    }
1983
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
1984
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
1985
    if fails + warns == 0 {
1986
        println!("{}", ui::done("Everything looks right."));
1987
    } else {
1988
        println!(
1989
            "{} {}, {}.",
1990
            if fails > 0 {
1991
                ui::err(ui::glyph("✖", "x"))
1992
            } else {
1993
                ui::caution()
1994
            },
1995
            plural(fails, "problem"),
1996
            plural(warns, "warning")
1997
        );
1998
    }
1999
    Ok(code)
2000
}
2001
2002
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
2003
pub fn fsck(as_json: bool) -> Result<i32> {
2004
    use oxy_core::repo::Severity;
2005
    let repo = open()?;
2006
    let sp = ui::spinner("Checking every object…");
2007
    let r = repo.fsck()?;
2008
    sp.clear();
2009
    let code = if r.errors() > 0 { 1 } else { 0 };
2010
    if as_json {
2011
        let problems: Vec<String> = r
2012
            .problems
2013
            .iter()
2014
            .map(|p| {
2015
                json::obj([
2016
                    (
2017
                        "severity",
2018
                        json::s(match p.severity {
2019
                            Severity::Error => "error",
2020
                            Severity::Warning => "warning",
2021
                        }),
2022
                    ),
2023
                    (
2024
                        "object",
2025
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
2026
                    ),
2027
                    ("what", json::s(&p.what)),
2028
                ])
2029
            })
2030
            .collect();
2031
        println!(
2032
            "{}",
2033
            json::obj([
2034
                ("ok", json::b(code == 0)),
2035
                ("objects", json::n(r.objects)),
2036
                ("ops", json::n(r.ops)),
2037
                ("changes", json::n(r.changes)),
2038
                ("signed", json::n(r.signed)),
2039
                ("unsigned", json::n(r.unsigned)),
2040
                ("checkpoints", json::n(r.checkpoints)),
2041
                ("attestations", json::n(r.attestations)),
2042
                ("errors", json::n(r.errors())),
2043
                ("warnings", json::n(r.warnings())),
2044
                ("problems", json::arr(problems)),
2045
            ])
2046
        );
2047
        return Ok(code);
2048
    }
2049
    println!(
2050
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
2051
        plural(r.objects, "object"),
2052
        plural(r.ops, "operation"),
2053
        plural(r.changes, "change"),
2054
        r.signed,
2055
        r.unsigned,
2056
        plural(r.checkpoints, "checkpoint"),
2057
        plural(r.attestations, "attestation"),
2058
    );
2059
    for p in &r.problems {
2060
        let obj = p
2061
            .object
2062
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
2063
            .unwrap_or_default();
2064
        match p.severity {
2065
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
2066
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
2067
        }
2068
    }
2069
    if r.problems.is_empty() {
2070
        println!("{}", ui::done("No problems found."));
2071
    } else if code == 0 {
2072
        println!(
2073
            "{}",
2074
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
2075
        );
2076
    } else {
2077
        println!(
2078
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
2079
            ui::err(ui::glyph("✖", "x")),
2080
            plural(r.errors(), "error"),
2081
            plural(r.warnings(), "warning")
2082
        );
2083
    }
2084
    Ok(code)
2085
}
2086
2087
/// The head the working copy sits on, for commands that default to it. With
2088
/// several heads beneath the working copy, the most recently made one is
2089
/// chosen and announced.
2090
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
2091
    let snap = repo.snapshot_status("oxy")?;
2092
    let base = snap.base.maximal(&snap.wc.deps);
2093
    match base.as_slice() {
2094
        [] => anyhow::bail!("the working copy sits on no change yet"),
2095
        [h] => Ok(*h),
2096
        many => {
2097
            let latest = many
2098
                .iter()
2099
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
2100
                .copied()
2101
                .unwrap();
2102
            let c = repo.store().get_change(&latest)?;
2103
            println!(
2104
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
2105
                short_id(&c),
2106
                latest.short(12),
2107
                many.len()
2108
            );
2109
            Ok(latest)
2110
        }
2111
    }
2112
}
2113
2114
/// `oxy describe` without -m: the working copy's name for a build.
2115
pub fn describe_name(as_json: bool) -> Result<i32> {
2116
    let repo = open()?;
2117
    let d = repo.describe_working_copy()?;
2118
    if as_json {
2119
        println!(
2120
            "{}",
2121
            json::obj([
2122
                ("describe", json::s(&d.line())),
2123
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
2124
                ("distance", json::n(d.distance)),
2125
                ("bookmark", json::s(&d.bookmark)),
2126
                ("change", json::s(&d.change.to_hex())),
2127
                ("hash", json::s(&d.hash.to_hex())),
2128
                ("dirty", json::b(d.dirty)),
2129
            ])
2130
        );
2131
    } else {
2132
        println!("{}", d.line());
2133
    }
2134
    Ok(0)
2135
}
2136
2137
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
2138
    let repo = open()?;
2139
    let h = match change {
2140
        Some(c) => repo.resolve_change(c)?,
2141
        None => current_head(&repo)?,
2142
    };
2143
    let new = repo.describe(&h, message)?;
2144
    let c = repo.store().get_change_meta(&new)?;
2145
    println!(
2146
        "{} {} {}  {}",
2147
        ui::done("Described"),
2148
        ui::id(c.change_id.short(8)),
2149
        ui::hash(format!("#{}", new.short(12))),
2150
        ui::subject(subject_of(message))
2151
    );
2152
    Ok(0)
2153
}
2154
2155
pub fn amend(message: Option<&str>, into: Option<&str>, paths: &[String]) -> Result<i32> {
2156
    let repo = open()?;
2157
    let before = repo.view()?;
2158
    let new = match into {
2159
        Some(spec) => {
2160
            let target = repo.resolve_change(spec)?;
2161
            repo.amend_into(&target, message)?
2162
        }
2163
        None if !paths.is_empty() => repo.amend_paths(message, paths)?,
2164
        None => repo.amend(message)?,
2165
    };
2166
    let c = repo.store().get_change_meta(&new)?;
2167
    println!(
2168
        "{} {} {}  {}",
2169
        ui::done("Amended"),
2170
        ui::id(c.change_id.short(8)),
2171
        ui::hash(format!("#{}", new.short(12))),
2172
        ui::subject(subject_of(&c.message))
2173
    );
2174
    // Rewriting what a remote already has means the next push replaces it
2175
    // there (oxygen#99): say so now, not when the push is refused.
2176
    let bookmark = repo.config.bookmark.clone();
2177
    let (had, has) = (
2178
        repo.heads_of(&before, &bookmark)?,
2179
        repo.heads_of(&repo.view()?, &bookmark)?,
2180
    );
2181
    for (remote, bookmarks) in &before.remotes {
2182
        let Some(st) = bookmarks.get(&bookmark) else {
2183
            continue;
2184
        };
2185
        let theirs = repo.store().get_state(st)?.heads;
2186
        if theirs.iter().any(|h| had.contains(h) && !has.contains(h)) {
2187
            println!(
2188
                "  {} {}",
2189
                ui::caution(),
2190
                ui::warn(format!(
2191
                    "{remote}/{bookmark} has the change as it was: the next push of {bookmark} needs --force to replace it"
2192
                ))
2193
            );
2194
        }
2195
    }
2196
    where_now(&repo);
2197
    Ok(0)
2198
}
2199
2200
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
2201
    let repo = open()?;
2202
    let Some(r) = revset else {
2203
        let h = repo.resolve_change(change.unwrap_or_default())?;
2204
        abandon_one(&repo, h)?;
2205
        where_now(&repo);
2206
        return Ok(0);
2207
    };
2208
    // A revset: say what it selects, refuse an empty set, ask above a few.
2209
    let selected = repo.revset(r)?;
2210
    let wc = repo.working_copy().ok().map(|(h, _)| h);
2211
    let hashes: Vec<ChangeHash> = selected
2212
        .hashes
2213
        .iter()
2214
        .copied()
2215
        .filter(|h| Some(*h) != wc)
2216
        .collect();
2217
    if hashes.is_empty() {
2218
        anyhow::bail!("{r:?} selects no change to abandon");
2219
    }
2220
    println!(
2221
        "{} {} selects {}:",
2222
        ui::section("abandon"),
2223
        ui::id(r),
2224
        plural(hashes.len(), "change")
2225
    );
2226
    for h in &hashes {
2227
        if let Some(m) = selected.metas.get(h) {
2228
            println!(
2229
                "  {} {}  {}",
2230
                ui::id(m.change_id.short(8)),
2231
                ui::hash(format!("#{}", h.short(12))),
2232
                subject_of(&m.message)
2233
            );
2234
        }
2235
    }
2236
    const ASK_ABOVE: usize = 5;
2237
    if hashes.len() > ASK_ABOVE && !yes {
2238
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
2239
    }
2240
    // Newest first: abandoning a change rewrites what depends on it, so a
2241
    // later member is found again by its ChangeId.
2242
    let mut done = 0;
2243
    for h in &hashes {
2244
        let Some(m) = selected.metas.get(h) else {
2245
            continue;
2246
        };
2247
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
2248
            Ok(h) => h,
2249
            Err(_) => continue,
2250
        };
2251
        abandon_one(&repo, now)?;
2252
        done += 1;
2253
    }
2254
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
2255
    where_now(&repo);
2256
    Ok(0)
2257
}
2258
2259
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
2260
    let c = repo.store().get_change_meta(&h)?;
2261
    let notes = repo.abandon(&h)?;
2262
    println!(
2263
        "{} {} {}  {}",
2264
        ui::done("Abandoned"),
2265
        ui::id(c.change_id.short(8)),
2266
        ui::hash(format!("#{}", h.short(12))),
2267
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
2268
    );
2269
    for n in notes {
2270
        println!("  {} {n}", ui::note());
2271
    }
2272
    Ok(())
2273
}
2274
2275
pub fn checkpoint() -> Result<i32> {
2276
    let repo = open()?;
2277
    let sp = ui::spinner("Writing checkpoint…");
2278
    let (r, changes, bytes) = repo.checkpoint()?;
2279
    sp.done(&format!(
2280
        "{} {} of {} ({} bytes) for {}",
2281
        ui::done("Checkpoint"),
2282
        ui::hash(format!("#{}", r.short(12))),
2283
        plural(changes, "change"),
2284
        bytes,
2285
        ui::id(&repo.config.bookmark)
2286
    ));
2287
    Ok(0)
2288
}
2289
2290
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
2291
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
2292
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
2293
        return Ok(1);
2294
    };
2295
    let info = repo.quick_status()?;
2296
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
2297
        oxy_core::repo::GLYPH_PROMPT_FORMAT
2298
    } else {
2299
        format
2300
    };
2301
    let line = match color {
2302
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
2303
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
2304
        Some(_) => info.format_colored(fmt, ("", "")),
2305
        None => info.format(fmt),
2306
    };
2307
    println!("{line}");
2308
    Ok(0)
2309
}
2310
2311
pub fn sparse(paths: &[String]) -> Result<i32> {
2312
    let mut repo = open()?;
2313
    if paths.is_empty() {
2314
        if repo.config.sparse_paths.is_empty() {
2315
            println!("No sparse filter: the whole tree is materialized.");
2316
        } else {
2317
            println!("{}", ui::heading("Sparse filter"));
2318
            for p in &repo.config.sparse_paths {
2319
                println!("  {}", ui::path(p));
2320
            }
2321
        }
2322
        return Ok(0);
2323
    }
2324
    let snap = repo.snapshot("oxy sparse")?;
2325
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
2326
        anyhow::bail!(
2327
            "the working copy has changes; commit them before changing the sparse filter"
2328
        );
2329
    }
2330
    repo.config.set("filter.paths", &paths.join(","))?;
2331
    repo.save_config()?;
2332
    let heads = repo.bookmark_heads()?;
2333
    let sp = ui::spinner("Re-checking out with the new filter…");
2334
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
2335
    sp.done(&format!(
2336
        "{} {}: {} written, {} removed",
2337
        ui::done("Sparse filter set to"),
2338
        ui::path(paths.join(",")),
2339
        plural(r.written, "file"),
2340
        r.removed
2341
    ));
2342
    Ok(0)
2343
}
2344
2345
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
2346
    let repo = open()?;
2347
    repo.snapshot_status("oxy tag")?;
2348
    let heads = if changes.is_empty() {
2349
        repo.bookmark_heads()?
2350
    } else {
2351
        let mut heads = Vec::new();
2352
        for c in changes {
2353
            heads.extend(repo.resolve_heads(c)?);
2354
        }
2355
        heads
2356
    };
2357
    let t = repo.tag_create(name, &heads, message)?;
2358
    println!(
2359
        "{} {} {} {} ({}){}",
2360
        ui::done("Tagged"),
2361
        ui::bookmark(&t.name),
2362
        ui::dim(ui::glyph("→", "->")),
2363
        ui::hash(format!("#{}", t.state.short(12))),
2364
        plural(t.heads.len(), "head"),
2365
        t.signer
2366
            .map(|s| format!(", signed by {s}"))
2367
            .unwrap_or_else(|| ui::dim(", unsigned"))
2368
    );
2369
    Ok(0)
2370
}
2371
2372
pub fn tag_list(as_json: bool) -> Result<i32> {
2373
    let repo = open()?;
2374
    let tags = repo.tags()?;
2375
    if as_json {
2376
        println!(
2377
            "{}",
2378
            json::arr(tags.iter().map(|t| {
2379
                json::obj([
2380
                    ("name", json::s(&t.name)),
2381
                    ("state", json::s(&t.state.to_hex())),
2382
                    ("heads", json::hashes(&t.heads)),
2383
                    ("message", json::s(&t.message)),
2384
                    (
2385
                        "signer",
2386
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2387
                    ),
2388
                ])
2389
            }))
2390
        );
2391
        return Ok(0);
2392
    }
2393
    if tags.is_empty() {
2394
        println!("{}", ui::dim("No tags."));
2395
    }
2396
    for t in tags {
2397
        println!(
2398
            "{} {} {}{}{}{}",
2399
            ui::ok(ui::glyph("⚑", "#")),
2400
            ui::bookmark(&t.name),
2401
            // The heads, as `oxy log` shows changes, not the state hash.
2402
            ui::hash(
2403
                t.heads
2404
                    .iter()
2405
                    .map(|h| format!("#{}", h.short(12)))
2406
                    .collect::<Vec<_>>()
2407
                    .join(" ")
2408
            ),
2409
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
2410
            if t.message.is_empty() {
2411
                String::new()
2412
            } else {
2413
                format!("  {}", ui::subject(subject_of(&t.message)))
2414
            },
2415
            t.signer
2416
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
2417
                .unwrap_or_default()
2418
        );
2419
    }
2420
    Ok(0)
2421
}
2422
2423
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2424
/// and workspace add take as "be on this bookmark" (oxygen#60).
2425
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
2426
    Ok(repo.view()?.bookmarks.contains_key(name)
2427
        || repo
2428
            .remote_only_bookmarks()?
2429
            .iter()
2430
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
2431
}
2432
2433
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
2434
    let repo = open()?;
2435
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2436
    // this workspace's bookmark with that one's files.
2437
    if let [name] = changes {
2438
        if names_bookmark(&repo, name)? {
2439
            let (local, _) = repo.local_bookmark_for(name)?;
2440
            let heads = repo.resolve_heads(&local)?;
2441
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
2442
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
2443
            sp.done(&format!(
2444
                "{} {} (workspace {}) on {}",
2445
                ui::done("Workspace created at"),
2446
                ui::path(ws.root().display()),
2447
                ui::id(ws.workspace().short(8)),
2448
                ui::bookmark(&local)
2449
            ));
2450
            return Ok(0);
2451
        }
2452
    }
2453
    let heads = if changes.is_empty() {
2454
        None
2455
    } else {
2456
        let mut heads = Vec::new();
2457
        for c in changes {
2458
            heads.extend(repo.resolve_heads(c)?);
2459
        }
2460
        Some(heads)
2461
    };
2462
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
2463
    let ws = repo.workspace_add(path, heads.as_deref())?;
2464
    sp.done(&format!(
2465
        "{} {} (workspace {})",
2466
        ui::done("Workspace created at"),
2467
        ui::path(ws.root().display()),
2468
        ui::id(ws.workspace().short(8))
2469
    ));
2470
    Ok(0)
2471
}
2472
2473
pub fn workspace_list(as_json: bool) -> Result<i32> {
2474
    let repo = open()?;
2475
    if as_json {
2476
        println!(
2477
            "{}",
2478
            json::arr(repo.workspaces()?.iter().map(|w| {
2479
                json::obj([
2480
                    ("id", json::s(&w.id.to_hex())),
2481
                    ("path", json::s(&w.path.to_string_lossy())),
2482
                    ("current", json::b(w.current)),
2483
                    (
2484
                        "working_copy",
2485
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2486
                    ),
2487
                ])
2488
            }))
2489
        );
2490
        return Ok(0);
2491
    }
2492
    for w in repo.workspaces()? {
2493
        println!(
2494
            "{} {} {}{}",
2495
            if w.current {
2496
                ui::ok(ui::glyph("●", "*"))
2497
            } else {
2498
                ui::dim(ui::glyph("○", "o"))
2499
            },
2500
            ui::id(w.id.short(8)),
2501
            ui::path(w.path.display()),
2502
            w.working_copy
2503
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
2504
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2505
        );
2506
    }
2507
    Ok(0)
2508
}
2509
2510
pub fn workspace_forget(spec: &str) -> Result<i32> {
2511
    let repo = open()?;
2512
    let all = repo.workspaces()?;
2513
    let target = std::fs::canonicalize(spec).ok();
2514
    let matches: Vec<_> = all
2515
        .iter()
2516
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
2517
        .collect();
2518
    let w = match matches.as_slice() {
2519
        [w] => *w,
2520
        [] => anyhow::bail!("no workspace matches {spec:?}"),
2521
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2522
    };
2523
    repo.workspace_forget(&w.id)?;
2524
    println!(
2525
        "{} workspace {} at {}; its files were left in place.",
2526
        ui::done("Forgot"),
2527
        ui::id(w.id.short(8)),
2528
        ui::path(w.path.display())
2529
    );
2530
    Ok(0)
2531
}
2532
2533
pub fn lock(path: &str) -> Result<i32> {
2534
    let repo = open()?;
2535
    repo.lock_path(path)?;
2536
    println!(
2537
        "{} {} {}",
2538
        ui::done("Locked"),
2539
        ui::path(path),
2540
        ui::dim("(advisory, local)")
2541
    );
2542
    Ok(0)
2543
}
2544
2545
pub fn unlock(path: &str) -> Result<i32> {
2546
    let repo = open()?;
2547
    repo.unlock_path(path)?;
2548
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
2549
    Ok(0)
2550
}
2551
2552
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
2553
    let repo = open()?;
2554
    let h = repo.resolve_change(change)?;
2555
    let (h1, h2) = repo.split(&h, paths)?;
2556
    let c1 = repo.store().get_change_meta(&h1)?;
2557
    let c2 = repo.store().get_change_meta(&h2)?;
2558
    println!(
2559
        "{} into {} {} and {} {}",
2560
        ui::done("Split"),
2561
        ui::id(c1.change_id.short(8)),
2562
        ui::hash(format!("#{}", h1.short(12))),
2563
        ui::id(c2.change_id.short(8)),
2564
        ui::hash(format!("#{}", h2.short(12)))
2565
    );
2566
    Ok(0)
2567
}
2568
2569
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
2570
    let mut heads = Vec::new();
2571
    for c in changes {
2572
        heads.extend(repo.resolve_heads(c)?);
2573
    }
2574
    Ok(heads)
2575
}
2576
2577
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
2578
    let repo = open()?;
2579
    repo.snapshot_status("oxy bookmark create")?;
2580
    let heads = if changes.is_empty() {
2581
        None
2582
    } else {
2583
        let named = heads_from(&repo, changes)?;
2584
        let (_, wc) = repo.working_copy()?;
2585
        let gap = repo.state_gap(&wc.deps, &named)?;
2586
        if upto {
2587
            Some(gap.upto)
2588
        } else if only || gap.earlier.is_empty() {
2589
            Some(named)
2590
        } else {
2591
            anyhow::bail!(
2592
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2593
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2594
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2595
                 or --only for just {0} and what it depends on.",
2596
                changes.join(" "),
2597
                plural(gap.earlier.len(), "change"),
2598
                listed_changes(&repo, &gap.earlier)
2599
            );
2600
        }
2601
    };
2602
    let heads = repo.bookmark_create(name, heads.as_deref())?;
2603
    println!(
2604
        "{} bookmark {} {} {}",
2605
        ui::done("Created"),
2606
        ui::bookmark(name),
2607
        ui::dim(ui::glyph("→", "->")),
2608
        ui::dim(plural(heads.len(), "head"))
2609
    );
2610
    println!(
2611
        "  {} {}",
2612
        ui::note(),
2613
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2614
    );
2615
    Ok(0)
2616
}
2617
2618
/// Up to five changes, newest last, as `  #hash subject` lines.
2619
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
2620
    let shown = changes.len().min(5);
2621
    let mut lines: Vec<String> = changes[changes.len() - shown..]
2622
        .iter()
2623
        .map(|h| {
2624
            let subject = repo
2625
                .store()
2626
                .get_change(h)
2627
                .map(|c| subject_of(&c.message).to_string())
2628
                .unwrap_or_default();
2629
            format!("  #{} {subject}", h.short(12))
2630
        })
2631
        .collect();
2632
    if changes.len() > shown {
2633
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
2634
    }
2635
    lines.join("\n")
2636
}
2637
2638
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
2639
    let repo = open()?;
2640
    repo.snapshot_status("oxy bookmark set")?;
2641
    let named = heads_from(&repo, changes)?;
2642
    // What the bookmark holds now and the new heads would leave out.
2643
    let current = repo
2644
        .bookmarks()?
2645
        .into_iter()
2646
        .find(|b| b.name == name)
2647
        .map(|b| b.heads)
2648
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
2649
    let gap = repo.state_gap(&current, &named)?;
2650
    let heads = if upto {
2651
        gap.upto
2652
    } else if only || gap.earlier.is_empty() {
2653
        named
2654
    } else {
2655
        anyhow::bail!(
2656
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2657
             A state is its heads and what they depend on, not everything recorded before them.\n\
2658
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2659
             or --only for just {0} and what it depends on.",
2660
            changes.join(" "),
2661
            plural(gap.earlier.len(), "change"),
2662
            listed_changes(&repo, &gap.earlier)
2663
        );
2664
    };
2665
    let heads = repo.bookmark_set(name, &heads)?;
2666
    println!(
2667
        "{} bookmark {} {} {}",
2668
        ui::done("Moved"),
2669
        ui::bookmark(name),
2670
        ui::dim(ui::glyph("→", "->")),
2671
        ui::dim(plural(heads.len(), "head"))
2672
    );
2673
    Ok(0)
2674
}
2675
2676
pub fn bookmark_delete(name: &str) -> Result<i32> {
2677
    let repo = open()?;
2678
    repo.bookmark_delete(name)?;
2679
    println!(
2680
        "{} bookmark {} {}",
2681
        ui::done("Deleted"),
2682
        ui::bookmark(name),
2683
        ui::dim("(its changes stay until unreachable)")
2684
    );
2685
    Ok(0)
2686
}
2687
2688
/// Heads with their metadata, newest first.
2689
fn heads_newest_first(
2690
    repo: &Repo,
2691
    heads: &[oxy_core::hash::ChangeHash],
2692
) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> {
2693
    let mut out: Vec<_> = heads
2694
        .iter()
2695
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m)))
2696
        .collect();
2697
    out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc));
2698
    out
2699
}
2700
2701
/// One head as a line: id, hash, author, when, subject.
2702
fn print_head(
2703
    repo: &Repo,
2704
    indent: &str,
2705
    h: &oxy_core::hash::ChangeHash,
2706
    m: &oxy_core::state::ChangeMeta,
2707
) {
2708
    println!(
2709
        "{indent}{} {} {}{}{}{}{}",
2710
        ui::id(m.change_id.short(8)),
2711
        ui::dim(format!("#{}", &h.to_hex()[..8])),
2712
        author_name(repo, m),
2713
        ui::sep(),
2714
        ui::dim(ui::ago(m.hlc.wall_ms)),
2715
        ui::sep(),
2716
        ui::subject(subject_of(&m.message))
2717
    );
2718
}
2719
2720
pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result<i32> {
2721
    let repo = open()?;
2722
    let name = name.unwrap_or(&repo.config.bookmark).to_string();
2723
    let view = repo.view()?;
2724
    let st = match view.bookmarks.get(&name) {
2725
        Some(st) => *st,
2726
        None => match oxy_core::repo::remote_bookmark(&view, &name) {
2727
            Some((_, _, st)) => st,
2728
            None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"),
2729
        },
2730
    };
2731
    let heads = repo.store().get_state(&st)?.heads;
2732
    let shown = heads_newest_first(&repo, &heads);
2733
    if as_json {
2734
        println!(
2735
            "{}",
2736
            json::obj([
2737
                ("name", json::s(&name)),
2738
                ("current", json::b(name == repo.config.bookmark)),
2739
                (
2740
                    "heads",
2741
                    json::arr(shown.iter().map(|(h, m)| {
2742
                        json::obj([
2743
                            ("hash", json::s(&h.to_hex())),
2744
                            ("id", json::s(&m.change_id.to_string())),
2745
                            ("author", json::s(&author_name(&repo, m))),
2746
                            ("time_ms", json::n(m.hlc.wall_ms)),
2747
                            ("subject", json::s(subject_of(&m.message))),
2748
                        ])
2749
                    }))
2750
                ),
2751
            ])
2752
        );
2753
        return Ok(0);
2754
    }
2755
    println!(
2756
        "{} {}{}{}",
2757
        ui::ok(ui::glyph("●", "*")),
2758
        ui::bookmark(&name),
2759
        ui::sep(),
2760
        ui::dim(plural(heads.len(), "head"))
2761
    );
2762
    for (h, m) in &shown {
2763
        print_head(&repo, "  ", h, m);
2764
    }
2765
    if heads.len() > 1 {
2766
        println!(
2767
            "  {}",
2768
            ui::dim("None depends on another: the bookmark is all of them and their dependencies.")
2769
        );
2770
    }
2771
    Ok(0)
2772
}
2773
2774
pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result<i32> {
2775
    let repo = open()?;
2776
    let remote_only = repo.remote_only_bookmarks()?;
2777
    if as_json {
2778
        let mut items: Vec<String> = repo
2779
            .bookmarks()?
2780
            .into_iter()
2781
            .map(|b| {
2782
                json::obj([
2783
                    ("name", json::s(&b.name)),
2784
                    ("heads", json::hashes(&b.heads)),
2785
                    ("current", json::b(b.current)),
2786
                    ("ahead", json::opt(b.ahead, json::n)),
2787
                    ("behind", json::opt(b.behind, json::n)),
2788
                    ("remote", json::opt(b.remote.as_deref(), json::s)),
2789
                ])
2790
            })
2791
            .collect();
2792
        if all {
2793
            items.extend(remote_only.iter().map(|b| {
2794
                json::obj([
2795
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
2796
                    ("heads", json::hashes(&b.heads)),
2797
                    ("current", json::b(false)),
2798
                    ("ahead", "null".into()),
2799
                    ("behind", "null".into()),
2800
                    ("remote", json::s(&b.remote)),
2801
                ])
2802
            }));
2803
        }
2804
        println!("{}", json::arr(items));
2805
        return Ok(0);
2806
    }
2807
    for b in repo.bookmarks()? {
2808
        let mark = if b.current {
2809
            ui::ok(ui::glyph("●", "*"))
2810
        } else {
2811
            ui::dim(ui::glyph("○", "o"))
2812
        };
2813
        let mut tail = String::new();
2814
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
2815
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
2816
        }
2817
        if let Some(n) = b.behind.filter(|n| *n > 0) {
2818
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
2819
        }
2820
        // Which remote, when there is a choice (oxygen#83).
2821
        if !tail.is_empty() && repo.config.remotes.len() > 1 {
2822
            if let Some(r) = &b.remote {
2823
                tail += &ui::dim(format!(" {r}"));
2824
            }
2825
        }
2826
        let shown = heads_newest_first(&repo, &b.heads);
2827
        // The newest head's subject, so a busy bookmark shows its latest work.
2828
        let head = match shown.first() {
2829
            Some(_) if verbose => String::new(),
2830
            Some((_, m)) if b.heads.len() > 1 => format!(
2831
                "{} {}",
2832
                ui::dim("newest"),
2833
                ui::subject(subject_of(&m.message))
2834
            ),
2835
            Some((_, m)) => ui::subject(subject_of(&m.message)),
2836
            None => ui::dim("(empty)"),
2837
        };
2838
        let head = if head.is_empty() {
2839
            head
2840
        } else {
2841
            format!("  {head}")
2842
        };
2843
        println!(
2844
            "{mark} {}{}{}{tail}{head}",
2845
            ui::bookmark(&b.name),
2846
            ui::sep(),
2847
            ui::dim(plural(b.heads.len(), "head"))
2848
        );
2849
        if verbose {
2850
            for (h, m) in &shown {
2851
                print_head(&repo, "    ", h, m);
2852
            }
2853
        }
2854
    }
2855
    if remote_only.is_empty() {
2856
        return Ok(0);
2857
    }
2858
    if !all {
2859
        println!(
2860
            "{}",
2861
            ui::dim(format!(
2862
                "  and {} only on a remote: oxy bookmark list --all",
2863
                plural(remote_only.len(), "bookmark")
2864
            ))
2865
        );
2866
        return Ok(0);
2867
    }
2868
    for b in &remote_only {
2869
        println!(
2870
            "{} {}{}{}",
2871
            ui::dim(ui::glyph("◌", ".")),
2872
            ui::dim(format!("{}/{}", b.remote, b.name)),
2873
            ui::sep(),
2874
            ui::dim(plural(b.heads.len(), "head"))
2875
        );
2876
    }
2877
    println!(
2878
        "  {} {}",
2879
        ui::note(),
2880
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2881
    );
2882
    Ok(0)
2883
}
2884
2885
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
2886
    let mut repo = open()?;
2887
    let from = repo.config.bookmark.clone();
2888
    let (local, created_from) = repo.local_bookmark_for(name)?;
2889
    if let Some(remote) = created_from {
2890
        println!(
2891
            "{} {} from {}",
2892
            ui::done("Created"),
2893
            ui::bookmark(&local),
2894
            ui::dim(format!("{remote}/{local}"))
2895
        );
2896
    }
2897
    let name = local.as_str();
2898
    // Only behind its remote: take the remote's state, so the switch does
2899
    // not check out a stale one (oxygen#74).
2900
    if let Some(n) = repo.catch_up_bookmark(name)? {
2901
        println!(
2902
            "{} {} with {}: {} it lacked",
2903
            ui::done("Caught up"),
2904
            ui::bookmark(name),
2905
            ui::dim(format!("{}/{name}", repo.default_remote())),
2906
            plural(n, "change")
2907
        );
2908
    }
2909
    let sp = ui::spinner(&format!("Switching to {name}…"));
2910
    let (r, carried) = if carry {
2911
        repo.bookmark_switch_carry(name)?
2912
    } else {
2913
        (repo.bookmark_switch(name, discard)?, vec![])
2914
    };
2915
    sp.done(&format!(
2916
        "{} to {}: {} written, {} removed{}",
2917
        ui::done("Switched"),
2918
        ui::bookmark(name),
2919
        plural(r.written, "file"),
2920
        r.removed,
2921
        if carried.is_empty() {
2922
            String::new()
2923
        } else {
2924
            format!("; carried {}", plural(carried.len(), "changed path"))
2925
        }
2926
    ));
2927
    print_removed(&r);
2928
    print_carried(&carried);
2929
    print_kept_both(&r);
2930
    if r.conflicted {
2931
        println!(
2932
            "  {} {}",
2933
            ui::caution(),
2934
            ui::warn("this state has conflicts; see oxy status")
2935
        );
2936
    }
2937
    // Say when the new state leaves out work the old one had: a state is
2938
    // its heads and what they depend on, which can be far less than a Git
2939
    // user expects.
2940
    if r.lacks > 0 {
2941
        println!(
2942
            "  {} {}",
2943
            ui::note(),
2944
            ui::dim(format!(
2945
                "{name} lacks {} that {from} has",
2946
                plural(r.lacks, "change")
2947
            ))
2948
        );
2949
    }
2950
    super::sync::subrepos_behind(&repo);
2951
    where_now(&repo);
2952
    Ok(0)
2953
}
2954
2955
pub fn merge(bookmark: &str) -> Result<i32> {
2956
    let repo = open()?;
2957
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
2958
    let r = repo.merge(bookmark)?;
2959
    if !r.changed {
2960
        sp.done(&format!(
2961
            "{} {}",
2962
            ui::ok(ui::glyph("✔", "*")),
2963
            ui::dim(format!(
2964
                "{} already contains {bookmark}",
2965
                repo.config.bookmark
2966
            ))
2967
        ));
2968
        return Ok(0);
2969
    }
2970
    sp.done(&format!(
2971
        "{} {} into {}: now {}{}",
2972
        ui::done("Merged"),
2973
        ui::bookmark(bookmark),
2974
        ui::bookmark(&repo.config.bookmark),
2975
        plural(r.heads.len(), "head"),
2976
        ui::dim(if r.checked_out {
2977
            "; working copy updated"
2978
        } else {
2979
            "; run oxy checkout to update the working copy"
2980
        })
2981
    ));
2982
    let snap = repo.snapshot("oxy merge")?;
2983
    if snap.base_snapshot.is_conflicted() {
2984
        println!(
2985
            "  {} {}",
2986
            ui::caution(),
2987
            ui::warn("the result has conflicts; see oxy status")
2988
        );
2989
    }
2990
    where_now(&repo);
2991
    Ok(0)
2992
}
2993
2994
pub fn squash(change: &str, into: &str) -> Result<i32> {
2995
    let repo = open()?;
2996
    let c = repo.resolve_change(change)?;
2997
    let d = repo.resolve_change(into)?;
2998
    let sp = ui::spinner("Squashing…");
2999
    let h = repo.squash(&c, &d)?;
3000
    let new = repo.store().get_change_meta(&h)?;
3001
    sp.done(&format!(
3002
        "{} into {} {}  {}",
3003
        ui::done("Squashed"),
3004
        ui::id(new.change_id.short(8)),
3005
        ui::hash(format!("#{}", h.short(12))),
3006
        ui::subject(subject_of(&new.message))
3007
    ));
3008
    Ok(0)
3009
}
3010
3011
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
3012
    let repo = open()?;
3013
    let c = repo.resolve_change(change)?;
3014
    let mut heads = Vec::new();
3015
    for o in onto {
3016
        heads.extend(repo.resolve_heads(o)?);
3017
    }
3018
    let sp = ui::spinner("Rebasing…");
3019
    let h = match repo.rebase(&c, &heads) {
3020
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
3021
            let r = repo.rebase_into_working_copy(&c, &heads)?;
3022
            sp.done(&format!(
3023
                "{} {} into {}: now {}",
3024
                ui::done("Merged"),
3025
                onto.join(" "),
3026
                ui::bookmark(&repo.config.bookmark),
3027
                plural(r.heads.len(), "head"),
3028
            ));
3029
            if r.checked_out {
3030
                println!(
3031
                    "  {} {}",
3032
                    ui::caution(),
3033
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
3034
                );
3035
            } else {
3036
                println!(
3037
                    "  {} {}",
3038
                    ui::caution(),
3039
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
3040
                );
3041
            }
3042
            where_now(&repo);
3043
            return Ok(0);
3044
        }
3045
        other => other?,
3046
    };
3047
    let new = repo.store().get_change_meta(&h)?;
3048
    sp.done(&format!(
3049
        "{} {} {}  {}",
3050
        ui::done("Rebased"),
3051
        ui::id(new.change_id.short(8)),
3052
        ui::hash(format!("#{}", h.short(12))),
3053
        ui::dim(format!(
3054
            "now depends on {}",
3055
            plural(new.deps.len(), "change")
3056
        ))
3057
    ));
3058
    where_now(&repo);
3059
    Ok(0)
3060
}
3061
3062
#[cfg(test)]
3063
mod tests {
3064
    use super::*;
3065
3066
    #[test]
3067
    fn id_prefixes_agree_with_the_whole_list() {
3068
        // Ids that share long prefixes, and some that differ only in a
3069
        // half byte, from a fixed sequence.
3070
        let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
3071
        let mut next = || {
3072
            x ^= x << 13;
3073
            x ^= x >> 7;
3074
            x ^= x << 17;
3075
            x
3076
        };
3077
        let mut ids: Vec<[u8; 16]> = Vec::new();
3078
        for _ in 0..2000 {
3079
            let mut id = [0u8; 16];
3080
            id[..8].copy_from_slice(&next().to_le_bytes());
3081
            id[8..].copy_from_slice(&next().to_le_bytes());
3082
            let share = (next() % 4) as usize;
3083
            if let Some(prev) = ids.last() {
3084
                id[..share].copy_from_slice(&prev[..share]);
3085
                if next() % 2 == 0 {
3086
                    id[share] = (prev[share] & 0xf0) | (id[share] & 0x0f);
3087
                }
3088
            }
3089
            ids.push(id);
3090
        }
3091
        let hex = |id: &[u8; 16]| oxy_core::ids::ChangeId(*id).to_hex();
3092
        let whole = unique_prefixes(ids.iter().map(hex));
3093
        let some = id_prefixes(ids.clone(), ids.iter().copied());
3094
        for id in &ids {
3095
            assert_eq!(some[id], whole[&hex(id)], "{}", hex(id));
3096
        }
3097
    }
3098
}