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