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