OXYGENHUB
# b5e98094eb8f oxygen / src / cli / workspace.rs
98.0 KiB · Rust · last changed merge=union: a checkout keeps both sides of a union file's adjacent insertions (refs #145) 9 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
        println!(
1463
            "  {} kept both sides in {} (merge=union); the next commit records it",
1464
            ui::note(),
1465
            ui::path(&k.path)
1466
        );
1467
    }
1468
}
1469
1470
pub fn resolve(paths: &[String], both: bool, reverse: bool, as_json: bool) -> Result<i32> {
1471
    let repo = open()?;
1472
    let mut snap = repo.snapshot("oxy resolve")?;
1473
    let paths: Vec<String> = paths
1474
        .iter()
1475
        .map(|p| p.trim_start_matches("./").trim_end_matches('/').to_string())
1476
        .collect();
1477
    if both {
1478
        // Adjacent insertions (oxygen#121): every side kept, in order.
1479
        let kept = repo.keep_both(&snap, &paths, reverse)?;
1480
        if !as_json {
1481
            for k in &kept {
1482
                if !k.settled.is_empty() {
1483
                    let n: Vec<String> = k.settled.iter().map(|n| n.to_string()).collect();
1484
                    println!("kept both  {}: conflict {}", k.path, n.join(", "));
1485
                }
1486
                for (n, why) in &k.left {
1487
                    println!("markers    {}: conflict {n}: {why}", k.path);
1488
                }
1489
            }
1490
        }
1491
        snap = repo.snapshot("oxy resolve")?;
1492
    } else if !paths.is_empty() {
1493
        // A replace conflict has no markers to edit out: the user says which
1494
        // content wins (oxygen#140, spec §9.3), and the snapshot builds it.
1495
        repo.choose_resolutions(&snap.base_snapshot, &paths)?;
1496
        snap = repo.snapshot("oxy resolve")?;
1497
    }
1498
    if as_json {
1499
        println!("{}", repo.status_json(&snap)?);
1500
        return Ok(if snap.base_snapshot.is_conflicted() {
1501
            2
1502
        } else {
1503
            0
1504
        });
1505
    }
1506
    if !snap.base_snapshot.is_conflicted() {
1507
        println!("The working copy's base has no conflicts.");
1508
        return Ok(0);
1509
    }
1510
    let mut remaining = 0;
1511
    for (p, f) in &snap.base_snapshot.files {
1512
        if !f.is_conflicted() {
1513
            continue;
1514
        }
1515
        match snap
1516
            .statuses
1517
            .iter()
1518
            .find(|s| s.path == *p)
1519
            .map(|s| s.status)
1520
        {
1521
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
1522
            Some(ChangeStatus::ConflictEdited) => {
1523
                remaining += 1;
1524
                println!("markers    {p}");
1525
            }
1526
            _ => {
1527
                remaining += 1;
1528
                println!("unresolved {p}");
1529
            }
1530
        }
1531
    }
1532
    for c in &snap.base_snapshot.tree.conflicts {
1533
        remaining += 1;
1534
        println!("tree       {c:?}");
1535
    }
1536
    if remaining == 0 {
1537
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
1538
        Ok(0)
1539
    } else {
1540
        Ok(2)
1541
    }
1542
}
1543
1544
pub fn undo() -> Result<i32> {
1545
    let repo = open()?;
1546
    let u = repo.undo()?;
1547
    println!("{} {}", ui::done("Undone:"), u.command);
1548
    for c in &u.changes {
1549
        println!("  {} {}", ui::note(), change_words(&repo, c));
1550
    }
1551
    if u.others_kept > 0 {
1552
        let s = if u.others_kept == 1 { "" } else { "s" };
1553
        println!(
1554
            "  {} {}",
1555
            ui::note(),
1556
            ui::dim(format!(
1557
                "{} newer operation{s} from other workspaces left as they are",
1558
                u.others_kept
1559
            ))
1560
        );
1561
    }
1562
    for (bookmark, remote) in &u.pushed {
1563
        println!(
1564
            "  {} {}",
1565
            ui::caution(),
1566
            ui::warn(format!(
1567
                "{remote}/{bookmark} already has what this undid: undone here only; the next push of {bookmark} needs --force to take it back there"
1568
            ))
1569
        );
1570
    }
1571
    where_now(&repo);
1572
    Ok(0)
1573
}
1574
1575
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
1576
    let repo = open()?;
1577
    let ops = repo.op_log()?;
1578
    // What each operation changed, against the one before it.
1579
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
1580
        match ops.get(i + 1) {
1581
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
1582
            None => Ok(vec![]),
1583
        }
1584
    };
1585
    if as_json {
1586
        let mut items = Vec::new();
1587
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
1588
            let summary: Vec<String> = changes_of(i)?
1589
                .iter()
1590
                .map(|c| change_words(&repo, c))
1591
                .collect();
1592
            items.push(json::obj([
1593
                ("id", json::s(&r.to_hex())),
1594
                ("when_ms", json::n(op.hlc.wall_ms)),
1595
                ("command", json::s(&op.command)),
1596
                ("snapshot", json::b(op.is_snapshot())),
1597
                ("current", json::b(i == 0)),
1598
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1599
            ]));
1600
        }
1601
        println!("{}", json::arr(items));
1602
        return Ok(0);
1603
    }
1604
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
1605
    let id = |r: &oxy_core::hash::ObjectRef| {
1606
        let hex = r.to_hex();
1607
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
1608
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
1609
    };
1610
    let rail = ui::dim(ui::glyph("│", "|"));
1611
    let (mut i, mut shown) = (0, 0);
1612
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
1613
        let (r, op) = &ops[i];
1614
        let bullet = if i == 0 {
1615
            ui::ok(ui::glyph("@", "@"))
1616
        } else {
1617
            ui::dim(ui::glyph("○", "o"))
1618
        };
1619
        // A run of snapshots folds into one entry.
1620
        let mut run = 1;
1621
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
1622
            run += 1;
1623
        }
1624
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
1625
        if op.is_snapshot() {
1626
            let span = if run > 1 {
1627
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1628
            } else {
1629
                String::new()
1630
            };
1631
            println!(
1632
                "{bullet}  {}{} {when}",
1633
                id(r),
1634
                if span.is_empty() {
1635
                    String::new()
1636
                } else {
1637
                    format!(" {span}")
1638
                }
1639
            );
1640
            println!(
1641
                "{rail}  {}",
1642
                ui::dim(if run == 1 {
1643
                    "working-copy snapshot".to_string()
1644
                } else {
1645
                    format!("{run} working-copy snapshots")
1646
                })
1647
            );
1648
        } else {
1649
            println!("{bullet}  {} {when}", id(r));
1650
            let words: Vec<String> = changes_of(i)?
1651
                .iter()
1652
                .map(|c| change_words(&repo, c))
1653
                .collect();
1654
            let summary = if words.is_empty() {
1655
                if i + 1 == ops.len() {
1656
                    "created the repository".to_string()
1657
                } else {
1658
                    "no bookmark or working-copy change".to_string()
1659
                }
1660
            } else {
1661
                words.join("; ")
1662
            };
1663
            println!(
1664
                "{rail}  {}",
1665
                if i == 0 {
1666
                    ui::subject(&summary)
1667
                } else {
1668
                    summary
1669
                }
1670
            );
1671
            let cmd = op.command.lines().next().unwrap_or("");
1672
            let cmd: String = cmd.chars().take(100).collect();
1673
            println!("{rail}  {}", ui::dim(cmd));
1674
        }
1675
        i += run;
1676
        shown += 1;
1677
    }
1678
    if i < ops.len() {
1679
        println!(
1680
            "{}",
1681
            ui::dim(format!(
1682
                "{} {} older; pass -n to see more",
1683
                ui::glyph("…", "..."),
1684
                plural(ops.len() - i, "operation")
1685
            ))
1686
        );
1687
    }
1688
    Ok(0)
1689
}
1690
1691
/// One change an operation made, in words.
1692
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1693
    use oxy_core::repo::ViewChange::*;
1694
    match c {
1695
        BookmarkCreated { name, heads } => {
1696
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1697
        }
1698
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
1699
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
1700
        BookmarkMoved { name, from, to } => format!(
1701
            "{name}: {from} {} {}",
1702
            ui::glyph("→", "->"),
1703
            plural(*to, "head")
1704
        ),
1705
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
1706
        TagCreated { name } => format!("tagged {name}"),
1707
        TagDeleted { name } => format!("removed tag {name}"),
1708
        Policy => "trust policy changed".to_string(),
1709
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
1710
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
1711
            Err(_) => "working copy moved".to_string(),
1712
        },
1713
    }
1714
}
1715
1716
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
1717
    let repo = open()?;
1718
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
1719
    let r = repo.op_restore(op, discard)?;
1720
    sp.done(&format!(
1721
        "{} to operation {} {}",
1722
        ui::done("Restored"),
1723
        ui::hash(r.op.short(12)),
1724
        ui::dim(r.command.lines().next().unwrap_or(""))
1725
    ));
1726
    println!(
1727
        "  {} {}",
1728
        ui::note(),
1729
        ui::dim(format!(
1730
            "{} written, {} removed; oxy undo goes back again",
1731
            plural(r.checkout.written, "file"),
1732
            r.checkout.removed
1733
        ))
1734
    );
1735
    where_now(&repo);
1736
    Ok(0)
1737
}
1738
1739
pub fn op_revert(op: &str) -> Result<i32> {
1740
    let repo = open()?;
1741
    let r = repo.op_revert(op)?;
1742
    let view = repo.view()?;
1743
    let names: Vec<String> = r
1744
        .reverted
1745
        .iter()
1746
        .map(|n| {
1747
            if view.bookmarks.contains_key(n) {
1748
                ui::bookmark(n)
1749
            } else {
1750
                format!("{} (removed)", ui::bookmark(n))
1751
            }
1752
        })
1753
        .collect();
1754
    println!(
1755
        "{} operation {} {}",
1756
        ui::done("Reverted"),
1757
        ui::hash(r.op.short(12)),
1758
        ui::dim(r.command.lines().next().unwrap_or(""))
1759
    );
1760
    println!(
1761
        "  {} {}",
1762
        ui::note(),
1763
        ui::dim(format!("as before it: {}", names.join(", ")))
1764
    );
1765
    if !r.kept.is_empty() {
1766
        println!(
1767
            "  {} {}",
1768
            ui::caution(),
1769
            ui::warn(format!(
1770
                "left as they are, having moved again since: {}",
1771
                r.kept.join(", ")
1772
            ))
1773
        );
1774
    }
1775
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
1776
        println!(
1777
            "  {} {}",
1778
            ui::note(),
1779
            ui::dim("the working copy has work of its own: oxy checkout to move it")
1780
        );
1781
    }
1782
    where_now(&repo);
1783
    Ok(0)
1784
}
1785
1786
/// Where the working copy and bookmark are now, after a command moved
1787
/// them (as jj says "Working copy now at").
1788
pub fn where_now(repo: &Repo) {
1789
    let Ok((_, wc)) = repo.working_copy() else {
1790
        return;
1791
    };
1792
    let heads = repo.bookmark_heads().unwrap_or_default();
1793
    let newest = heads
1794
        .iter()
1795
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
1796
        .max_by_key(|(m, _)| m.hlc);
1797
    println!(
1798
        "  {} {}",
1799
        ui::dim(format!("{:<13}", "Working copy")),
1800
        ui::id(wc.change_id.short(8))
1801
    );
1802
    let tail = match newest {
1803
        Some((m, _)) => format!(
1804
            ", newest {} {}",
1805
            ui::id(m.change_id.short(8)),
1806
            subject_of(&m.message)
1807
        ),
1808
        None => String::new(),
1809
    };
1810
    println!(
1811
        "  {} {}: {}{tail}",
1812
        ui::dim(format!("{:<13}", "Bookmark")),
1813
        ui::bookmark(&repo.config.bookmark),
1814
        plural(heads.len(), "head")
1815
    );
1816
}
1817
1818
pub fn gc(now: bool, expire_snapshots: bool) -> Result<i32> {
1819
    let mut repo = open()?;
1820
    if expire_snapshots {
1821
        repo.config.snapshot_retention_days = 0;
1822
    }
1823
    let sp = ui::spinner("Packing and pruning…");
1824
    let r = repo.gc_with(now, &mut |phase| sp.set(&format!("{phase}…")))?;
1825
    sp.clear();
1826
    if r.packed.objects > 0 {
1827
        println!(
1828
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
1829
            plural(r.packed.objects, "object"),
1830
            r.packed.raw_bytes,
1831
            r.packed.packed_bytes,
1832
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
1833
        );
1834
    }
1835
    println!(
1836
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
1837
        plural(r.reachable, "object"),
1838
        plural(r.pruned.objects, "unreachable object"),
1839
        r.pruned.bytes,
1840
        if r.pruned.deferred > 0 {
1841
            format!(
1842
                "; {} deferred by the grace period (use --now)",
1843
                plural(r.pruned.deferred, "object")
1844
            )
1845
        } else {
1846
            String::new()
1847
        },
1848
        if r.merged_packs > 0 {
1849
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1850
        } else {
1851
            String::new()
1852
        },
1853
        plural(repo.store().pack_count(), "pack")
1854
    );
1855
    // What earlier repacks replaced stays an hour for readers still using
1856
    // it (oxygenhub#249); a collection after that deletes it.
1857
    let kept = if r.retired.kept > 0 {
1858
        format!(
1859
            "{} retired less than an hour ago kept for readers",
1860
            plural(r.retired.kept, "file")
1861
        )
1862
    } else {
1863
        String::new()
1864
    };
1865
    if r.retired.packs + r.retired.loose > 0 {
1866
        println!(
1867
            "Deleted {} and {} retired by earlier repacks{}.",
1868
            plural(r.retired.packs, "pack"),
1869
            plural(r.retired.loose, "loose object"),
1870
            if kept.is_empty() {
1871
                String::new()
1872
            } else {
1873
                format!("; {kept}")
1874
            }
1875
        );
1876
    } else if !kept.is_empty() {
1877
        println!("{kept}.");
1878
    }
1879
    Ok(0)
1880
}
1881
1882
/// `oxy gc --remote NAME`: fold a store remote's bundles into one.
1883
pub fn gc_remote(name: &str, now: bool) -> Result<i32> {
1884
    let repo = open()?;
1885
    let sp = ui::spinner(&format!("Folding {name}'s bundles…"));
1886
    let r = repo.gc_remote(name, now)?;
1887
    sp.clear();
1888
    if r.merged > 0 {
1889
        println!(
1890
            "{} {} into one of {} bytes ({})",
1891
            ui::done("Folded"),
1892
            plural(r.merged, "bundle"),
1893
            r.bundle_bytes,
1894
            plural(r.changes, "change")
1895
        );
1896
    } else {
1897
        println!(
1898
            "{} {}",
1899
            ui::note(),
1900
            ui::dim("nothing to fold: one bundle holds everything")
1901
        );
1902
    }
1903
    println!(
1904
        "  {} {}",
1905
        ui::note(),
1906
        ui::dim(format!(
1907
            "removed {}{}",
1908
            plural(r.deleted, "superseded bundle"),
1909
            if r.deferred > 0 {
1910
                format!(
1911
                    "; {} kept for readers that may still fetch them (use --now)",
1912
                    plural(r.deferred, "bundle")
1913
                )
1914
            } else {
1915
                String::new()
1916
            }
1917
        ))
1918
    );
1919
    Ok(0)
1920
}
1921
1922
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
1923
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1924
    use oxy_core::repo::Health;
1925
    let repo = open()?;
1926
    let sp = ui::spinner(if offline {
1927
        "Checking…"
1928
    } else {
1929
        "Checking, and contacting remotes…"
1930
    });
1931
    let r = repo.doctor(!offline);
1932
    sp.clear();
1933
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
1934
    let word = |h: Health| match h {
1935
        Health::Ok => "ok",
1936
        Health::Warn => "warning",
1937
        Health::Fail => "fail",
1938
    };
1939
    if as_json {
1940
        let checks: Vec<String> = r
1941
            .checks
1942
            .iter()
1943
            .map(|c| {
1944
                json::obj([
1945
                    ("area", json::s(&c.area)),
1946
                    ("health", json::s(word(c.health))),
1947
                    ("message", json::s(&c.message)),
1948
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
1949
                ])
1950
            })
1951
            .collect();
1952
        println!(
1953
            "{}",
1954
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1955
        );
1956
        return Ok(code);
1957
    }
1958
    let mut last = "";
1959
    for c in &r.checks {
1960
        if c.area != last {
1961
            println!("{}", ui::section(&c.area));
1962
            last = &c.area;
1963
        }
1964
        let mark = match c.health {
1965
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
1966
            Health::Warn => ui::caution(),
1967
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1968
        };
1969
        println!("  {mark} {}", c.message);
1970
        if let Some(h) = &c.hint {
1971
            println!("    {} {}", ui::dim("→"), ui::dim(h));
1972
        }
1973
    }
1974
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
1975
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
1976
    if fails + warns == 0 {
1977
        println!("{}", ui::done("Everything looks right."));
1978
    } else {
1979
        println!(
1980
            "{} {}, {}.",
1981
            if fails > 0 {
1982
                ui::err(ui::glyph("✖", "x"))
1983
            } else {
1984
                ui::caution()
1985
            },
1986
            plural(fails, "problem"),
1987
            plural(warns, "warning")
1988
        );
1989
    }
1990
    Ok(code)
1991
}
1992
1993
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
1994
pub fn fsck(as_json: bool) -> Result<i32> {
1995
    use oxy_core::repo::Severity;
1996
    let repo = open()?;
1997
    let sp = ui::spinner("Checking every object…");
1998
    let r = repo.fsck()?;
1999
    sp.clear();
2000
    let code = if r.errors() > 0 { 1 } else { 0 };
2001
    if as_json {
2002
        let problems: Vec<String> = r
2003
            .problems
2004
            .iter()
2005
            .map(|p| {
2006
                json::obj([
2007
                    (
2008
                        "severity",
2009
                        json::s(match p.severity {
2010
                            Severity::Error => "error",
2011
                            Severity::Warning => "warning",
2012
                        }),
2013
                    ),
2014
                    (
2015
                        "object",
2016
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
2017
                    ),
2018
                    ("what", json::s(&p.what)),
2019
                ])
2020
            })
2021
            .collect();
2022
        println!(
2023
            "{}",
2024
            json::obj([
2025
                ("ok", json::b(code == 0)),
2026
                ("objects", json::n(r.objects)),
2027
                ("ops", json::n(r.ops)),
2028
                ("changes", json::n(r.changes)),
2029
                ("signed", json::n(r.signed)),
2030
                ("unsigned", json::n(r.unsigned)),
2031
                ("checkpoints", json::n(r.checkpoints)),
2032
                ("attestations", json::n(r.attestations)),
2033
                ("errors", json::n(r.errors())),
2034
                ("warnings", json::n(r.warnings())),
2035
                ("problems", json::arr(problems)),
2036
            ])
2037
        );
2038
        return Ok(code);
2039
    }
2040
    println!(
2041
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
2042
        plural(r.objects, "object"),
2043
        plural(r.ops, "operation"),
2044
        plural(r.changes, "change"),
2045
        r.signed,
2046
        r.unsigned,
2047
        plural(r.checkpoints, "checkpoint"),
2048
        plural(r.attestations, "attestation"),
2049
    );
2050
    for p in &r.problems {
2051
        let obj = p
2052
            .object
2053
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
2054
            .unwrap_or_default();
2055
        match p.severity {
2056
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
2057
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
2058
        }
2059
    }
2060
    if r.problems.is_empty() {
2061
        println!("{}", ui::done("No problems found."));
2062
    } else if code == 0 {
2063
        println!(
2064
            "{}",
2065
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
2066
        );
2067
    } else {
2068
        println!(
2069
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
2070
            ui::err(ui::glyph("✖", "x")),
2071
            plural(r.errors(), "error"),
2072
            plural(r.warnings(), "warning")
2073
        );
2074
    }
2075
    Ok(code)
2076
}
2077
2078
/// The head the working copy sits on, for commands that default to it. With
2079
/// several heads beneath the working copy, the most recently made one is
2080
/// chosen and announced.
2081
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
2082
    let snap = repo.snapshot_status("oxy")?;
2083
    let base = snap.base.maximal(&snap.wc.deps);
2084
    match base.as_slice() {
2085
        [] => anyhow::bail!("the working copy sits on no change yet"),
2086
        [h] => Ok(*h),
2087
        many => {
2088
            let latest = many
2089
                .iter()
2090
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
2091
                .copied()
2092
                .unwrap();
2093
            let c = repo.store().get_change(&latest)?;
2094
            println!(
2095
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
2096
                short_id(&c),
2097
                latest.short(12),
2098
                many.len()
2099
            );
2100
            Ok(latest)
2101
        }
2102
    }
2103
}
2104
2105
/// `oxy describe` without -m: the working copy's name for a build.
2106
pub fn describe_name(as_json: bool) -> Result<i32> {
2107
    let repo = open()?;
2108
    let d = repo.describe_working_copy()?;
2109
    if as_json {
2110
        println!(
2111
            "{}",
2112
            json::obj([
2113
                ("describe", json::s(&d.line())),
2114
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
2115
                ("distance", json::n(d.distance)),
2116
                ("bookmark", json::s(&d.bookmark)),
2117
                ("change", json::s(&d.change.to_hex())),
2118
                ("hash", json::s(&d.hash.to_hex())),
2119
                ("dirty", json::b(d.dirty)),
2120
            ])
2121
        );
2122
    } else {
2123
        println!("{}", d.line());
2124
    }
2125
    Ok(0)
2126
}
2127
2128
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
2129
    let repo = open()?;
2130
    let h = match change {
2131
        Some(c) => repo.resolve_change(c)?,
2132
        None => current_head(&repo)?,
2133
    };
2134
    let new = repo.describe(&h, message)?;
2135
    let c = repo.store().get_change_meta(&new)?;
2136
    println!(
2137
        "{} {} {}  {}",
2138
        ui::done("Described"),
2139
        ui::id(c.change_id.short(8)),
2140
        ui::hash(format!("#{}", new.short(12))),
2141
        ui::subject(subject_of(message))
2142
    );
2143
    Ok(0)
2144
}
2145
2146
pub fn amend(message: Option<&str>, into: Option<&str>, paths: &[String]) -> Result<i32> {
2147
    let repo = open()?;
2148
    let before = repo.view()?;
2149
    let new = match into {
2150
        Some(spec) => {
2151
            let target = repo.resolve_change(spec)?;
2152
            repo.amend_into(&target, message)?
2153
        }
2154
        None if !paths.is_empty() => repo.amend_paths(message, paths)?,
2155
        None => repo.amend(message)?,
2156
    };
2157
    let c = repo.store().get_change_meta(&new)?;
2158
    println!(
2159
        "{} {} {}  {}",
2160
        ui::done("Amended"),
2161
        ui::id(c.change_id.short(8)),
2162
        ui::hash(format!("#{}", new.short(12))),
2163
        ui::subject(subject_of(&c.message))
2164
    );
2165
    // Rewriting what a remote already has means the next push replaces it
2166
    // there (oxygen#99): say so now, not when the push is refused.
2167
    let bookmark = repo.config.bookmark.clone();
2168
    let (had, has) = (
2169
        repo.heads_of(&before, &bookmark)?,
2170
        repo.heads_of(&repo.view()?, &bookmark)?,
2171
    );
2172
    for (remote, bookmarks) in &before.remotes {
2173
        let Some(st) = bookmarks.get(&bookmark) else {
2174
            continue;
2175
        };
2176
        let theirs = repo.store().get_state(st)?.heads;
2177
        if theirs.iter().any(|h| had.contains(h) && !has.contains(h)) {
2178
            println!(
2179
                "  {} {}",
2180
                ui::caution(),
2181
                ui::warn(format!(
2182
                    "{remote}/{bookmark} has the change as it was: the next push of {bookmark} needs --force to replace it"
2183
                ))
2184
            );
2185
        }
2186
    }
2187
    where_now(&repo);
2188
    Ok(0)
2189
}
2190
2191
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
2192
    let repo = open()?;
2193
    let Some(r) = revset else {
2194
        let h = repo.resolve_change(change.unwrap_or_default())?;
2195
        abandon_one(&repo, h)?;
2196
        where_now(&repo);
2197
        return Ok(0);
2198
    };
2199
    // A revset: say what it selects, refuse an empty set, ask above a few.
2200
    let selected = repo.revset(r)?;
2201
    let wc = repo.working_copy().ok().map(|(h, _)| h);
2202
    let hashes: Vec<ChangeHash> = selected
2203
        .hashes
2204
        .iter()
2205
        .copied()
2206
        .filter(|h| Some(*h) != wc)
2207
        .collect();
2208
    if hashes.is_empty() {
2209
        anyhow::bail!("{r:?} selects no change to abandon");
2210
    }
2211
    println!(
2212
        "{} {} selects {}:",
2213
        ui::section("abandon"),
2214
        ui::id(r),
2215
        plural(hashes.len(), "change")
2216
    );
2217
    for h in &hashes {
2218
        if let Some(m) = selected.metas.get(h) {
2219
            println!(
2220
                "  {} {}  {}",
2221
                ui::id(m.change_id.short(8)),
2222
                ui::hash(format!("#{}", h.short(12))),
2223
                subject_of(&m.message)
2224
            );
2225
        }
2226
    }
2227
    const ASK_ABOVE: usize = 5;
2228
    if hashes.len() > ASK_ABOVE && !yes {
2229
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
2230
    }
2231
    // Newest first: abandoning a change rewrites what depends on it, so a
2232
    // later member is found again by its ChangeId.
2233
    let mut done = 0;
2234
    for h in &hashes {
2235
        let Some(m) = selected.metas.get(h) else {
2236
            continue;
2237
        };
2238
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
2239
            Ok(h) => h,
2240
            Err(_) => continue,
2241
        };
2242
        abandon_one(&repo, now)?;
2243
        done += 1;
2244
    }
2245
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
2246
    where_now(&repo);
2247
    Ok(0)
2248
}
2249
2250
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
2251
    let c = repo.store().get_change_meta(&h)?;
2252
    let notes = repo.abandon(&h)?;
2253
    println!(
2254
        "{} {} {}  {}",
2255
        ui::done("Abandoned"),
2256
        ui::id(c.change_id.short(8)),
2257
        ui::hash(format!("#{}", h.short(12))),
2258
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
2259
    );
2260
    for n in notes {
2261
        println!("  {} {n}", ui::note());
2262
    }
2263
    Ok(())
2264
}
2265
2266
pub fn checkpoint() -> Result<i32> {
2267
    let repo = open()?;
2268
    let sp = ui::spinner("Writing checkpoint…");
2269
    let (r, changes, bytes) = repo.checkpoint()?;
2270
    sp.done(&format!(
2271
        "{} {} of {} ({} bytes) for {}",
2272
        ui::done("Checkpoint"),
2273
        ui::hash(format!("#{}", r.short(12))),
2274
        plural(changes, "change"),
2275
        bytes,
2276
        ui::id(&repo.config.bookmark)
2277
    ));
2278
    Ok(0)
2279
}
2280
2281
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
2282
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
2283
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
2284
        return Ok(1);
2285
    };
2286
    let info = repo.quick_status()?;
2287
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
2288
        oxy_core::repo::GLYPH_PROMPT_FORMAT
2289
    } else {
2290
        format
2291
    };
2292
    let line = match color {
2293
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
2294
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
2295
        Some(_) => info.format_colored(fmt, ("", "")),
2296
        None => info.format(fmt),
2297
    };
2298
    println!("{line}");
2299
    Ok(0)
2300
}
2301
2302
pub fn sparse(paths: &[String]) -> Result<i32> {
2303
    let mut repo = open()?;
2304
    if paths.is_empty() {
2305
        if repo.config.sparse_paths.is_empty() {
2306
            println!("No sparse filter: the whole tree is materialized.");
2307
        } else {
2308
            println!("{}", ui::heading("Sparse filter"));
2309
            for p in &repo.config.sparse_paths {
2310
                println!("  {}", ui::path(p));
2311
            }
2312
        }
2313
        return Ok(0);
2314
    }
2315
    let snap = repo.snapshot("oxy sparse")?;
2316
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
2317
        anyhow::bail!(
2318
            "the working copy has changes; commit them before changing the sparse filter"
2319
        );
2320
    }
2321
    repo.config.set("filter.paths", &paths.join(","))?;
2322
    repo.save_config()?;
2323
    let heads = repo.bookmark_heads()?;
2324
    let sp = ui::spinner("Re-checking out with the new filter…");
2325
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
2326
    sp.done(&format!(
2327
        "{} {}: {} written, {} removed",
2328
        ui::done("Sparse filter set to"),
2329
        ui::path(paths.join(",")),
2330
        plural(r.written, "file"),
2331
        r.removed
2332
    ));
2333
    Ok(0)
2334
}
2335
2336
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
2337
    let repo = open()?;
2338
    repo.snapshot_status("oxy tag")?;
2339
    let heads = if changes.is_empty() {
2340
        repo.bookmark_heads()?
2341
    } else {
2342
        let mut heads = Vec::new();
2343
        for c in changes {
2344
            heads.extend(repo.resolve_heads(c)?);
2345
        }
2346
        heads
2347
    };
2348
    let t = repo.tag_create(name, &heads, message)?;
2349
    println!(
2350
        "{} {} {} {} ({}){}",
2351
        ui::done("Tagged"),
2352
        ui::bookmark(&t.name),
2353
        ui::dim(ui::glyph("→", "->")),
2354
        ui::hash(format!("#{}", t.state.short(12))),
2355
        plural(t.heads.len(), "head"),
2356
        t.signer
2357
            .map(|s| format!(", signed by {s}"))
2358
            .unwrap_or_else(|| ui::dim(", unsigned"))
2359
    );
2360
    Ok(0)
2361
}
2362
2363
pub fn tag_list(as_json: bool) -> Result<i32> {
2364
    let repo = open()?;
2365
    let tags = repo.tags()?;
2366
    if as_json {
2367
        println!(
2368
            "{}",
2369
            json::arr(tags.iter().map(|t| {
2370
                json::obj([
2371
                    ("name", json::s(&t.name)),
2372
                    ("state", json::s(&t.state.to_hex())),
2373
                    ("heads", json::hashes(&t.heads)),
2374
                    ("message", json::s(&t.message)),
2375
                    (
2376
                        "signer",
2377
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2378
                    ),
2379
                ])
2380
            }))
2381
        );
2382
        return Ok(0);
2383
    }
2384
    if tags.is_empty() {
2385
        println!("{}", ui::dim("No tags."));
2386
    }
2387
    for t in tags {
2388
        println!(
2389
            "{} {} {}{}{}{}",
2390
            ui::ok(ui::glyph("⚑", "#")),
2391
            ui::bookmark(&t.name),
2392
            // The heads, as `oxy log` shows changes, not the state hash.
2393
            ui::hash(
2394
                t.heads
2395
                    .iter()
2396
                    .map(|h| format!("#{}", h.short(12)))
2397
                    .collect::<Vec<_>>()
2398
                    .join(" ")
2399
            ),
2400
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
2401
            if t.message.is_empty() {
2402
                String::new()
2403
            } else {
2404
                format!("  {}", ui::subject(subject_of(&t.message)))
2405
            },
2406
            t.signer
2407
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
2408
                .unwrap_or_default()
2409
        );
2410
    }
2411
    Ok(0)
2412
}
2413
2414
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2415
/// and workspace add take as "be on this bookmark" (oxygen#60).
2416
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
2417
    Ok(repo.view()?.bookmarks.contains_key(name)
2418
        || repo
2419
            .remote_only_bookmarks()?
2420
            .iter()
2421
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
2422
}
2423
2424
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
2425
    let repo = open()?;
2426
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2427
    // this workspace's bookmark with that one's files.
2428
    if let [name] = changes {
2429
        if names_bookmark(&repo, name)? {
2430
            let (local, _) = repo.local_bookmark_for(name)?;
2431
            let heads = repo.resolve_heads(&local)?;
2432
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
2433
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
2434
            sp.done(&format!(
2435
                "{} {} (workspace {}) on {}",
2436
                ui::done("Workspace created at"),
2437
                ui::path(ws.root().display()),
2438
                ui::id(ws.workspace().short(8)),
2439
                ui::bookmark(&local)
2440
            ));
2441
            return Ok(0);
2442
        }
2443
    }
2444
    let heads = if changes.is_empty() {
2445
        None
2446
    } else {
2447
        let mut heads = Vec::new();
2448
        for c in changes {
2449
            heads.extend(repo.resolve_heads(c)?);
2450
        }
2451
        Some(heads)
2452
    };
2453
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
2454
    let ws = repo.workspace_add(path, heads.as_deref())?;
2455
    sp.done(&format!(
2456
        "{} {} (workspace {})",
2457
        ui::done("Workspace created at"),
2458
        ui::path(ws.root().display()),
2459
        ui::id(ws.workspace().short(8))
2460
    ));
2461
    Ok(0)
2462
}
2463
2464
pub fn workspace_list(as_json: bool) -> Result<i32> {
2465
    let repo = open()?;
2466
    if as_json {
2467
        println!(
2468
            "{}",
2469
            json::arr(repo.workspaces()?.iter().map(|w| {
2470
                json::obj([
2471
                    ("id", json::s(&w.id.to_hex())),
2472
                    ("path", json::s(&w.path.to_string_lossy())),
2473
                    ("current", json::b(w.current)),
2474
                    (
2475
                        "working_copy",
2476
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2477
                    ),
2478
                ])
2479
            }))
2480
        );
2481
        return Ok(0);
2482
    }
2483
    for w in repo.workspaces()? {
2484
        println!(
2485
            "{} {} {}{}",
2486
            if w.current {
2487
                ui::ok(ui::glyph("●", "*"))
2488
            } else {
2489
                ui::dim(ui::glyph("○", "o"))
2490
            },
2491
            ui::id(w.id.short(8)),
2492
            ui::path(w.path.display()),
2493
            w.working_copy
2494
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
2495
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2496
        );
2497
    }
2498
    Ok(0)
2499
}
2500
2501
pub fn workspace_forget(spec: &str) -> Result<i32> {
2502
    let repo = open()?;
2503
    let all = repo.workspaces()?;
2504
    let target = std::fs::canonicalize(spec).ok();
2505
    let matches: Vec<_> = all
2506
        .iter()
2507
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
2508
        .collect();
2509
    let w = match matches.as_slice() {
2510
        [w] => *w,
2511
        [] => anyhow::bail!("no workspace matches {spec:?}"),
2512
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2513
    };
2514
    repo.workspace_forget(&w.id)?;
2515
    println!(
2516
        "{} workspace {} at {}; its files were left in place.",
2517
        ui::done("Forgot"),
2518
        ui::id(w.id.short(8)),
2519
        ui::path(w.path.display())
2520
    );
2521
    Ok(0)
2522
}
2523
2524
pub fn lock(path: &str) -> Result<i32> {
2525
    let repo = open()?;
2526
    repo.lock_path(path)?;
2527
    println!(
2528
        "{} {} {}",
2529
        ui::done("Locked"),
2530
        ui::path(path),
2531
        ui::dim("(advisory, local)")
2532
    );
2533
    Ok(0)
2534
}
2535
2536
pub fn unlock(path: &str) -> Result<i32> {
2537
    let repo = open()?;
2538
    repo.unlock_path(path)?;
2539
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
2540
    Ok(0)
2541
}
2542
2543
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
2544
    let repo = open()?;
2545
    let h = repo.resolve_change(change)?;
2546
    let (h1, h2) = repo.split(&h, paths)?;
2547
    let c1 = repo.store().get_change_meta(&h1)?;
2548
    let c2 = repo.store().get_change_meta(&h2)?;
2549
    println!(
2550
        "{} into {} {} and {} {}",
2551
        ui::done("Split"),
2552
        ui::id(c1.change_id.short(8)),
2553
        ui::hash(format!("#{}", h1.short(12))),
2554
        ui::id(c2.change_id.short(8)),
2555
        ui::hash(format!("#{}", h2.short(12)))
2556
    );
2557
    Ok(0)
2558
}
2559
2560
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
2561
    let mut heads = Vec::new();
2562
    for c in changes {
2563
        heads.extend(repo.resolve_heads(c)?);
2564
    }
2565
    Ok(heads)
2566
}
2567
2568
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
2569
    let repo = open()?;
2570
    repo.snapshot_status("oxy bookmark create")?;
2571
    let heads = if changes.is_empty() {
2572
        None
2573
    } else {
2574
        let named = heads_from(&repo, changes)?;
2575
        let (_, wc) = repo.working_copy()?;
2576
        let gap = repo.state_gap(&wc.deps, &named)?;
2577
        if upto {
2578
            Some(gap.upto)
2579
        } else if only || gap.earlier.is_empty() {
2580
            Some(named)
2581
        } else {
2582
            anyhow::bail!(
2583
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2584
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2585
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2586
                 or --only for just {0} and what it depends on.",
2587
                changes.join(" "),
2588
                plural(gap.earlier.len(), "change"),
2589
                listed_changes(&repo, &gap.earlier)
2590
            );
2591
        }
2592
    };
2593
    let heads = repo.bookmark_create(name, heads.as_deref())?;
2594
    println!(
2595
        "{} bookmark {} {} {}",
2596
        ui::done("Created"),
2597
        ui::bookmark(name),
2598
        ui::dim(ui::glyph("→", "->")),
2599
        ui::dim(plural(heads.len(), "head"))
2600
    );
2601
    println!(
2602
        "  {} {}",
2603
        ui::note(),
2604
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2605
    );
2606
    Ok(0)
2607
}
2608
2609
/// Up to five changes, newest last, as `  #hash subject` lines.
2610
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
2611
    let shown = changes.len().min(5);
2612
    let mut lines: Vec<String> = changes[changes.len() - shown..]
2613
        .iter()
2614
        .map(|h| {
2615
            let subject = repo
2616
                .store()
2617
                .get_change(h)
2618
                .map(|c| subject_of(&c.message).to_string())
2619
                .unwrap_or_default();
2620
            format!("  #{} {subject}", h.short(12))
2621
        })
2622
        .collect();
2623
    if changes.len() > shown {
2624
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
2625
    }
2626
    lines.join("\n")
2627
}
2628
2629
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
2630
    let repo = open()?;
2631
    repo.snapshot_status("oxy bookmark set")?;
2632
    let named = heads_from(&repo, changes)?;
2633
    // What the bookmark holds now and the new heads would leave out.
2634
    let current = repo
2635
        .bookmarks()?
2636
        .into_iter()
2637
        .find(|b| b.name == name)
2638
        .map(|b| b.heads)
2639
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
2640
    let gap = repo.state_gap(&current, &named)?;
2641
    let heads = if upto {
2642
        gap.upto
2643
    } else if only || gap.earlier.is_empty() {
2644
        named
2645
    } else {
2646
        anyhow::bail!(
2647
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2648
             A state is its heads and what they depend on, not everything recorded before them.\n\
2649
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2650
             or --only for just {0} and what it depends on.",
2651
            changes.join(" "),
2652
            plural(gap.earlier.len(), "change"),
2653
            listed_changes(&repo, &gap.earlier)
2654
        );
2655
    };
2656
    let heads = repo.bookmark_set(name, &heads)?;
2657
    println!(
2658
        "{} bookmark {} {} {}",
2659
        ui::done("Moved"),
2660
        ui::bookmark(name),
2661
        ui::dim(ui::glyph("→", "->")),
2662
        ui::dim(plural(heads.len(), "head"))
2663
    );
2664
    Ok(0)
2665
}
2666
2667
pub fn bookmark_delete(name: &str) -> Result<i32> {
2668
    let repo = open()?;
2669
    repo.bookmark_delete(name)?;
2670
    println!(
2671
        "{} bookmark {} {}",
2672
        ui::done("Deleted"),
2673
        ui::bookmark(name),
2674
        ui::dim("(its changes stay until unreachable)")
2675
    );
2676
    Ok(0)
2677
}
2678
2679
/// Heads with their metadata, newest first.
2680
fn heads_newest_first(
2681
    repo: &Repo,
2682
    heads: &[oxy_core::hash::ChangeHash],
2683
) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> {
2684
    let mut out: Vec<_> = heads
2685
        .iter()
2686
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m)))
2687
        .collect();
2688
    out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc));
2689
    out
2690
}
2691
2692
/// One head as a line: id, hash, author, when, subject.
2693
fn print_head(
2694
    repo: &Repo,
2695
    indent: &str,
2696
    h: &oxy_core::hash::ChangeHash,
2697
    m: &oxy_core::state::ChangeMeta,
2698
) {
2699
    println!(
2700
        "{indent}{} {} {}{}{}{}{}",
2701
        ui::id(m.change_id.short(8)),
2702
        ui::dim(format!("#{}", &h.to_hex()[..8])),
2703
        author_name(repo, m),
2704
        ui::sep(),
2705
        ui::dim(ui::ago(m.hlc.wall_ms)),
2706
        ui::sep(),
2707
        ui::subject(subject_of(&m.message))
2708
    );
2709
}
2710
2711
pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result<i32> {
2712
    let repo = open()?;
2713
    let name = name.unwrap_or(&repo.config.bookmark).to_string();
2714
    let view = repo.view()?;
2715
    let st = match view.bookmarks.get(&name) {
2716
        Some(st) => *st,
2717
        None => match oxy_core::repo::remote_bookmark(&view, &name) {
2718
            Some((_, _, st)) => st,
2719
            None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"),
2720
        },
2721
    };
2722
    let heads = repo.store().get_state(&st)?.heads;
2723
    let shown = heads_newest_first(&repo, &heads);
2724
    if as_json {
2725
        println!(
2726
            "{}",
2727
            json::obj([
2728
                ("name", json::s(&name)),
2729
                ("current", json::b(name == repo.config.bookmark)),
2730
                (
2731
                    "heads",
2732
                    json::arr(shown.iter().map(|(h, m)| {
2733
                        json::obj([
2734
                            ("hash", json::s(&h.to_hex())),
2735
                            ("id", json::s(&m.change_id.to_string())),
2736
                            ("author", json::s(&author_name(&repo, m))),
2737
                            ("time_ms", json::n(m.hlc.wall_ms)),
2738
                            ("subject", json::s(subject_of(&m.message))),
2739
                        ])
2740
                    }))
2741
                ),
2742
            ])
2743
        );
2744
        return Ok(0);
2745
    }
2746
    println!(
2747
        "{} {}{}{}",
2748
        ui::ok(ui::glyph("●", "*")),
2749
        ui::bookmark(&name),
2750
        ui::sep(),
2751
        ui::dim(plural(heads.len(), "head"))
2752
    );
2753
    for (h, m) in &shown {
2754
        print_head(&repo, "  ", h, m);
2755
    }
2756
    if heads.len() > 1 {
2757
        println!(
2758
            "  {}",
2759
            ui::dim("None depends on another: the bookmark is all of them and their dependencies.")
2760
        );
2761
    }
2762
    Ok(0)
2763
}
2764
2765
pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result<i32> {
2766
    let repo = open()?;
2767
    let remote_only = repo.remote_only_bookmarks()?;
2768
    if as_json {
2769
        let mut items: Vec<String> = repo
2770
            .bookmarks()?
2771
            .into_iter()
2772
            .map(|b| {
2773
                json::obj([
2774
                    ("name", json::s(&b.name)),
2775
                    ("heads", json::hashes(&b.heads)),
2776
                    ("current", json::b(b.current)),
2777
                    ("ahead", json::opt(b.ahead, json::n)),
2778
                    ("behind", json::opt(b.behind, json::n)),
2779
                    ("remote", json::opt(b.remote.as_deref(), json::s)),
2780
                ])
2781
            })
2782
            .collect();
2783
        if all {
2784
            items.extend(remote_only.iter().map(|b| {
2785
                json::obj([
2786
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
2787
                    ("heads", json::hashes(&b.heads)),
2788
                    ("current", json::b(false)),
2789
                    ("ahead", "null".into()),
2790
                    ("behind", "null".into()),
2791
                    ("remote", json::s(&b.remote)),
2792
                ])
2793
            }));
2794
        }
2795
        println!("{}", json::arr(items));
2796
        return Ok(0);
2797
    }
2798
    for b in repo.bookmarks()? {
2799
        let mark = if b.current {
2800
            ui::ok(ui::glyph("●", "*"))
2801
        } else {
2802
            ui::dim(ui::glyph("○", "o"))
2803
        };
2804
        let mut tail = String::new();
2805
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
2806
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
2807
        }
2808
        if let Some(n) = b.behind.filter(|n| *n > 0) {
2809
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
2810
        }
2811
        // Which remote, when there is a choice (oxygen#83).
2812
        if !tail.is_empty() && repo.config.remotes.len() > 1 {
2813
            if let Some(r) = &b.remote {
2814
                tail += &ui::dim(format!(" {r}"));
2815
            }
2816
        }
2817
        let shown = heads_newest_first(&repo, &b.heads);
2818
        // The newest head's subject, so a busy bookmark shows its latest work.
2819
        let head = match shown.first() {
2820
            Some(_) if verbose => String::new(),
2821
            Some((_, m)) if b.heads.len() > 1 => format!(
2822
                "{} {}",
2823
                ui::dim("newest"),
2824
                ui::subject(subject_of(&m.message))
2825
            ),
2826
            Some((_, m)) => ui::subject(subject_of(&m.message)),
2827
            None => ui::dim("(empty)"),
2828
        };
2829
        let head = if head.is_empty() {
2830
            head
2831
        } else {
2832
            format!("  {head}")
2833
        };
2834
        println!(
2835
            "{mark} {}{}{}{tail}{head}",
2836
            ui::bookmark(&b.name),
2837
            ui::sep(),
2838
            ui::dim(plural(b.heads.len(), "head"))
2839
        );
2840
        if verbose {
2841
            for (h, m) in &shown {
2842
                print_head(&repo, "    ", h, m);
2843
            }
2844
        }
2845
    }
2846
    if remote_only.is_empty() {
2847
        return Ok(0);
2848
    }
2849
    if !all {
2850
        println!(
2851
            "{}",
2852
            ui::dim(format!(
2853
                "  and {} only on a remote: oxy bookmark list --all",
2854
                plural(remote_only.len(), "bookmark")
2855
            ))
2856
        );
2857
        return Ok(0);
2858
    }
2859
    for b in &remote_only {
2860
        println!(
2861
            "{} {}{}{}",
2862
            ui::dim(ui::glyph("◌", ".")),
2863
            ui::dim(format!("{}/{}", b.remote, b.name)),
2864
            ui::sep(),
2865
            ui::dim(plural(b.heads.len(), "head"))
2866
        );
2867
    }
2868
    println!(
2869
        "  {} {}",
2870
        ui::note(),
2871
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2872
    );
2873
    Ok(0)
2874
}
2875
2876
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
2877
    let mut repo = open()?;
2878
    let from = repo.config.bookmark.clone();
2879
    let (local, created_from) = repo.local_bookmark_for(name)?;
2880
    if let Some(remote) = created_from {
2881
        println!(
2882
            "{} {} from {}",
2883
            ui::done("Created"),
2884
            ui::bookmark(&local),
2885
            ui::dim(format!("{remote}/{local}"))
2886
        );
2887
    }
2888
    let name = local.as_str();
2889
    // Only behind its remote: take the remote's state, so the switch does
2890
    // not check out a stale one (oxygen#74).
2891
    if let Some(n) = repo.catch_up_bookmark(name)? {
2892
        println!(
2893
            "{} {} with {}: {} it lacked",
2894
            ui::done("Caught up"),
2895
            ui::bookmark(name),
2896
            ui::dim(format!("{}/{name}", repo.default_remote())),
2897
            plural(n, "change")
2898
        );
2899
    }
2900
    let sp = ui::spinner(&format!("Switching to {name}…"));
2901
    let (r, carried) = if carry {
2902
        repo.bookmark_switch_carry(name)?
2903
    } else {
2904
        (repo.bookmark_switch(name, discard)?, vec![])
2905
    };
2906
    sp.done(&format!(
2907
        "{} to {}: {} written, {} removed{}",
2908
        ui::done("Switched"),
2909
        ui::bookmark(name),
2910
        plural(r.written, "file"),
2911
        r.removed,
2912
        if carried.is_empty() {
2913
            String::new()
2914
        } else {
2915
            format!("; carried {}", plural(carried.len(), "changed path"))
2916
        }
2917
    ));
2918
    print_removed(&r);
2919
    print_carried(&carried);
2920
    print_kept_both(&r);
2921
    if r.conflicted {
2922
        println!(
2923
            "  {} {}",
2924
            ui::caution(),
2925
            ui::warn("this state has conflicts; see oxy status")
2926
        );
2927
    }
2928
    // Say when the new state leaves out work the old one had: a state is
2929
    // its heads and what they depend on, which can be far less than a Git
2930
    // user expects.
2931
    if r.lacks > 0 {
2932
        println!(
2933
            "  {} {}",
2934
            ui::note(),
2935
            ui::dim(format!(
2936
                "{name} lacks {} that {from} has",
2937
                plural(r.lacks, "change")
2938
            ))
2939
        );
2940
    }
2941
    super::sync::subrepos_behind(&repo);
2942
    where_now(&repo);
2943
    Ok(0)
2944
}
2945
2946
pub fn merge(bookmark: &str) -> Result<i32> {
2947
    let repo = open()?;
2948
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
2949
    let r = repo.merge(bookmark)?;
2950
    if !r.changed {
2951
        sp.done(&format!(
2952
            "{} {}",
2953
            ui::ok(ui::glyph("✔", "*")),
2954
            ui::dim(format!(
2955
                "{} already contains {bookmark}",
2956
                repo.config.bookmark
2957
            ))
2958
        ));
2959
        return Ok(0);
2960
    }
2961
    sp.done(&format!(
2962
        "{} {} into {}: now {}{}",
2963
        ui::done("Merged"),
2964
        ui::bookmark(bookmark),
2965
        ui::bookmark(&repo.config.bookmark),
2966
        plural(r.heads.len(), "head"),
2967
        ui::dim(if r.checked_out {
2968
            "; working copy updated"
2969
        } else {
2970
            "; run oxy checkout to update the working copy"
2971
        })
2972
    ));
2973
    let snap = repo.snapshot("oxy merge")?;
2974
    if snap.base_snapshot.is_conflicted() {
2975
        println!(
2976
            "  {} {}",
2977
            ui::caution(),
2978
            ui::warn("the result has conflicts; see oxy status")
2979
        );
2980
    }
2981
    where_now(&repo);
2982
    Ok(0)
2983
}
2984
2985
pub fn squash(change: &str, into: &str) -> Result<i32> {
2986
    let repo = open()?;
2987
    let c = repo.resolve_change(change)?;
2988
    let d = repo.resolve_change(into)?;
2989
    let sp = ui::spinner("Squashing…");
2990
    let h = repo.squash(&c, &d)?;
2991
    let new = repo.store().get_change_meta(&h)?;
2992
    sp.done(&format!(
2993
        "{} into {} {}  {}",
2994
        ui::done("Squashed"),
2995
        ui::id(new.change_id.short(8)),
2996
        ui::hash(format!("#{}", h.short(12))),
2997
        ui::subject(subject_of(&new.message))
2998
    ));
2999
    Ok(0)
3000
}
3001
3002
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
3003
    let repo = open()?;
3004
    let c = repo.resolve_change(change)?;
3005
    let mut heads = Vec::new();
3006
    for o in onto {
3007
        heads.extend(repo.resolve_heads(o)?);
3008
    }
3009
    let sp = ui::spinner("Rebasing…");
3010
    let h = match repo.rebase(&c, &heads) {
3011
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
3012
            let r = repo.rebase_into_working_copy(&c, &heads)?;
3013
            sp.done(&format!(
3014
                "{} {} into {}: now {}",
3015
                ui::done("Merged"),
3016
                onto.join(" "),
3017
                ui::bookmark(&repo.config.bookmark),
3018
                plural(r.heads.len(), "head"),
3019
            ));
3020
            if r.checked_out {
3021
                println!(
3022
                    "  {} {}",
3023
                    ui::caution(),
3024
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
3025
                );
3026
            } else {
3027
                println!(
3028
                    "  {} {}",
3029
                    ui::caution(),
3030
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
3031
                );
3032
            }
3033
            where_now(&repo);
3034
            return Ok(0);
3035
        }
3036
        other => other?,
3037
    };
3038
    let new = repo.store().get_change_meta(&h)?;
3039
    sp.done(&format!(
3040
        "{} {} {}  {}",
3041
        ui::done("Rebased"),
3042
        ui::id(new.change_id.short(8)),
3043
        ui::hash(format!("#{}", h.short(12))),
3044
        ui::dim(format!(
3045
            "now depends on {}",
3046
            plural(new.deps.len(), "change")
3047
        ))
3048
    ));
3049
    where_now(&repo);
3050
    Ok(0)
3051
}
3052
3053
#[cfg(test)]
3054
mod tests {
3055
    use super::*;
3056
3057
    #[test]
3058
    fn id_prefixes_agree_with_the_whole_list() {
3059
        // Ids that share long prefixes, and some that differ only in a
3060
        // half byte, from a fixed sequence.
3061
        let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
3062
        let mut next = || {
3063
            x ^= x << 13;
3064
            x ^= x >> 7;
3065
            x ^= x << 17;
3066
            x
3067
        };
3068
        let mut ids: Vec<[u8; 16]> = Vec::new();
3069
        for _ in 0..2000 {
3070
            let mut id = [0u8; 16];
3071
            id[..8].copy_from_slice(&next().to_le_bytes());
3072
            id[8..].copy_from_slice(&next().to_le_bytes());
3073
            let share = (next() % 4) as usize;
3074
            if let Some(prev) = ids.last() {
3075
                id[..share].copy_from_slice(&prev[..share]);
3076
                if next() % 2 == 0 {
3077
                    id[share] = (prev[share] & 0xf0) | (id[share] & 0x0f);
3078
                }
3079
            }
3080
            ids.push(id);
3081
        }
3082
        let hex = |id: &[u8; 16]| oxy_core::ids::ChangeId(*id).to_hex();
3083
        let whole = unique_prefixes(ids.iter().map(hex));
3084
        let some = id_prefixes(ids.clone(), ids.iter().copied());
3085
        for id in &ids {
3086
            assert_eq!(some[id], whole[&hex(id)], "{}", hex(id));
3087
        }
3088
    }
3089
}