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