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