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