OXYGENHUB
# a2387d547373 oxygen / src / cli / workspace.rs
88.0 KiB · Rust · last changed log and the state index without needless copies 26 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
            let (wc, base, snapshot) = repo.working_copy_with_base()?;
996
            let text = {
997
                let _t = oxy_core::timing::phase("diff: render the change");
998
                render_change(&wc, &base, &snapshot)
999
            };
1000
            print!("{text}");
1001
            // The process ends here: freeing the base's tree and graphs
1002
            // one by one would only cost time (about 27 ms on Linux).
1003
            std::mem::forget((wc, base, snapshot));
1004
        }
1005
    }
1006
    Ok(0)
1007
}
1008
1009
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
1010
    let repo = open()?;
1011
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
1012
    let bytes = repo.file_at(path, heads.as_deref())?;
1013
    use std::io::Write as _;
1014
    std::io::stdout().write_all(&bytes)?;
1015
    Ok(0)
1016
}
1017
1018
pub fn root(as_json: bool) -> Result<i32> {
1019
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
1020
        if as_json {
1021
            println!("null");
1022
        }
1023
        return Ok(1);
1024
    };
1025
    if as_json {
1026
        println!(
1027
            "{}",
1028
            json::obj([
1029
                ("root", json::s(&repo.root().to_string_lossy())),
1030
                ("workspace", json::s(&repo.workspace().to_hex())),
1031
                ("bookmark", json::s(&repo.config.bookmark))
1032
            ])
1033
        );
1034
    } else {
1035
        println!("{}", repo.root().display());
1036
    }
1037
    Ok(0)
1038
}
1039
1040
pub fn version(as_json: bool) -> Result<i32> {
1041
    if as_json {
1042
        println!(
1043
            "{}",
1044
            json::obj([
1045
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
1046
                // What was built: a release's or install's `oxy describe`,
1047
                // a Flow build's heads, or "local build".
1048
                ("build", json::s(env!("OXY_BUILD_ID"))),
1049
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
1050
                ("format", json::n(2))
1051
            ])
1052
        );
1053
    } else {
1054
        println!(
1055
            "oxy {} (repository format 2, protocol {})",
1056
            env!("OXY_VERSION_LONG"),
1057
            oxy_core::protocol::PROTOCOL_VERSION
1058
        );
1059
    }
1060
    Ok(0)
1061
}
1062
1063
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
1064
    let repo = open()?;
1065
    if paths.is_empty() && hunks.is_empty() {
1066
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
1067
    }
1068
    let mut n = 0;
1069
    if !hunks.is_empty() {
1070
        n += repo.discard_hunks(hunks)?;
1071
    }
1072
    if !paths.is_empty() {
1073
        n += repo.discard(paths)?;
1074
    }
1075
    println!(
1076
        "{} {} restored to the working copy's base",
1077
        ui::done("Discarded"),
1078
        plural(n, "path")
1079
    );
1080
    Ok(0)
1081
}
1082
1083
pub fn hunks(as_json: bool) -> Result<i32> {
1084
    let repo = open()?;
1085
    let (_, hunks) = repo.hunks()?;
1086
    if as_json {
1087
        println!(
1088
            "{}",
1089
            json::arr(hunks.iter().map(|h| json::obj([
1090
                ("index", json::n(h.index)),
1091
                ("path", json::s(&h.path)),
1092
                ("text", json::s(&h.text))
1093
            ])))
1094
        );
1095
        return Ok(0);
1096
    }
1097
    if hunks.is_empty() {
1098
        println!(
1099
            "{}",
1100
            ui::dim("No hunks: the working copy matches its base.")
1101
        );
1102
    }
1103
    for h in &hunks {
1104
        println!(
1105
            "{} {}",
1106
            ui::section(format!("hunk {}", h.index)),
1107
            ui::path(&h.path)
1108
        );
1109
        for line in h.text.lines() {
1110
            let styled = if line.starts_with('+') {
1111
                ui::ok(line)
1112
            } else if line.starts_with('-') {
1113
                ui::err(line)
1114
            } else {
1115
                ui::dim(line)
1116
            };
1117
            println!("  {styled}");
1118
        }
1119
    }
1120
    Ok(0)
1121
}
1122
1123
pub fn show(change: Option<&str>, revset: Option<&str>, as_json: bool) -> Result<i32> {
1124
    let repo = open()?;
1125
    repo.snapshot_status("oxy show")?;
1126
    let Some(r) = revset else {
1127
        let h = repo.resolve_change(change.unwrap_or("@"))?;
1128
        return show_one(&repo, h, as_json, false);
1129
    };
1130
    // Several changes: a JSON array, or the changes one after another.
1131
    let hashes = repo.revset(r)?.hashes;
1132
    if as_json {
1133
        print!("[");
1134
        for (i, h) in hashes.iter().enumerate() {
1135
            if i > 0 {
1136
                print!(",");
1137
            }
1138
            show_one(&repo, *h, true, true)?;
1139
        }
1140
        println!("]");
1141
        return Ok(0);
1142
    }
1143
    if hashes.is_empty() {
1144
        println!("{}", ui::dim(format!("No change matches {r:?}.")));
1145
        return Ok(0);
1146
    }
1147
    for (i, h) in hashes.iter().enumerate() {
1148
        if i > 0 {
1149
            println!();
1150
        }
1151
        show_one(&repo, *h, false, false)?;
1152
    }
1153
    Ok(0)
1154
}
1155
1156
/// One change, as `oxy show` prints it; `inline` JSON goes without its
1157
/// newline, for an array.
1158
fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool) -> Result<i32> {
1159
    let c = repo.store().get_change(&h)?;
1160
    if as_json {
1161
        let files = repo.diff_files(Some(&h))?;
1162
        let heads = repo.bookmark_heads()?;
1163
        let entry = oxy_core::repo::LogEntry {
1164
            hash: h,
1165
            change: oxy_core::state::ChangeMeta::of(&c),
1166
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
1167
            is_head: heads.contains(&h),
1168
        };
1169
        let mut body = log_entry_json(repo, &entry)?;
1170
        body.pop();
1171
        body.push_str(&format!(
1172
            ",{}:{}}}",
1173
            json::s("files"),
1174
            json::arr(files.iter().map(|f| json::obj([
1175
                ("path", json::s(&f.path)),
1176
                ("kind", json::s(&f.kind)),
1177
                ("from", json::opt(f.from.as_deref(), json::s))
1178
            ])))
1179
        ));
1180
        if inline {
1181
            print!("{body}");
1182
        } else {
1183
            println!("{body}");
1184
        }
1185
        return Ok(0);
1186
    }
1187
    println!(
1188
        "{} {} {}",
1189
        ui::section("change"),
1190
        ui::id(short_id(&c)),
1191
        ui::hash(format!("#{h}"))
1192
    );
1193
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1194
    // Fetched but not pulled (oxygen#56): say where it is.
1195
    if let Some(at) = repo.remote_only_location(&h)? {
1196
        println!(
1197
            "{}",
1198
            ui::kv(
1199
                "only in",
1200
                ui::warn(format!(
1201
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
1202
                ))
1203
            )
1204
        );
1205
    }
1206
    let meta = oxy_core::state::ChangeMeta::of(&c);
1207
    let status = repo.authenticate_change_known(&h, Some(&meta))?;
1208
    println!("{}", ui::kv("author", ui::author(author_name(repo, &meta))));
1209
    if let Some(agent) = via(repo, &status, &meta.author) {
1210
        println!("{}", ui::kv("via", agent.line()));
1211
    }
1212
    println!(
1213
        "{}",
1214
        ui::kv(
1215
            "date",
1216
            format!(
1217
                "{} {}",
1218
                when(c.hlc.wall_ms),
1219
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1220
            )
1221
        )
1222
    );
1223
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
1224
    println!("{}", ui::kv("sig", signature_line(repo, &h)?));
1225
    println!();
1226
    for line in (if c.message.is_empty() {
1227
        "(no description)"
1228
    } else {
1229
        &c.message
1230
    })
1231
    .lines()
1232
    {
1233
        println!("    {line}");
1234
    }
1235
    println!();
1236
    print!("{}", repo.describe_change(&h)?);
1237
    Ok(0)
1238
}
1239
1240
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
1241
    let repo = open()?;
1242
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1243
    // BRANCH` is: checking its files out under another bookmark's name
1244
    // made the next commit move the wrong bookmark (oxygen#60).
1245
    if let [name] = changes {
1246
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
1247
            drop(repo);
1248
            return bookmark_switch(name, discard, carry);
1249
        }
1250
    }
1251
    let heads = if changes.is_empty() {
1252
        repo.bookmark_heads()?
1253
    } else {
1254
        let mut heads = Vec::new();
1255
        for c in changes {
1256
            heads.extend(repo.resolve_heads(c)?);
1257
        }
1258
        heads
1259
    };
1260
    let spec = if changes.is_empty() {
1261
        repo.config.bookmark.clone()
1262
    } else {
1263
        changes.join(" ")
1264
    };
1265
    let sp = ui::spinner(&format!("Checking out {spec}…"));
1266
    let command = format!("oxy checkout {spec}");
1267
    let (r, carried) = if carry {
1268
        repo.checkout_carry(&heads, &spec, &command)?
1269
    } else {
1270
        (repo.checkout(&heads, discard, &command)?, vec![])
1271
    };
1272
    sp.done(&format!(
1273
        "{} on {}: {} written, {} removed{}",
1274
        ui::done("Working copy"),
1275
        ui::bookmark(&spec),
1276
        plural(r.written, "file"),
1277
        r.removed,
1278
        if carried.is_empty() {
1279
            String::new()
1280
        } else {
1281
            format!("; carried {}", plural(carried.len(), "changed path"))
1282
        }
1283
    ));
1284
    for n in &r.notes {
1285
        println!("  {} {n}", ui::note());
1286
    }
1287
    if r.conflicted {
1288
        println!(
1289
            "  {} {}",
1290
            ui::caution(),
1291
            ui::warn("this state has conflicts; see oxy status")
1292
        );
1293
    }
1294
    where_now(&repo);
1295
    Ok(0)
1296
}
1297
1298
pub fn resolve(as_json: bool) -> Result<i32> {
1299
    let repo = open()?;
1300
    let snap = repo.snapshot("oxy resolve")?;
1301
    if as_json {
1302
        println!("{}", repo.status_json(&snap)?);
1303
        return Ok(if snap.base_snapshot.is_conflicted() {
1304
            2
1305
        } else {
1306
            0
1307
        });
1308
    }
1309
    if !snap.base_snapshot.is_conflicted() {
1310
        println!("The working copy's base has no conflicts.");
1311
        return Ok(0);
1312
    }
1313
    let mut remaining = 0;
1314
    for (p, f) in &snap.base_snapshot.files {
1315
        if !f.is_conflicted() {
1316
            continue;
1317
        }
1318
        match snap
1319
            .statuses
1320
            .iter()
1321
            .find(|s| s.path == *p)
1322
            .map(|s| s.status)
1323
        {
1324
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
1325
            Some(ChangeStatus::ConflictEdited) => {
1326
                remaining += 1;
1327
                println!("markers    {p}");
1328
            }
1329
            _ => {
1330
                remaining += 1;
1331
                println!("unresolved {p}");
1332
            }
1333
        }
1334
    }
1335
    for c in &snap.base_snapshot.tree.conflicts {
1336
        remaining += 1;
1337
        println!("tree       {c:?}");
1338
    }
1339
    if remaining == 0 {
1340
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
1341
        Ok(0)
1342
    } else {
1343
        Ok(2)
1344
    }
1345
}
1346
1347
pub fn undo() -> Result<i32> {
1348
    let repo = open()?;
1349
    let op = repo.undo()?;
1350
    println!("{} now at: {}", ui::done("Undone;"), ui::dim(&op.command));
1351
    where_now(&repo);
1352
    Ok(0)
1353
}
1354
1355
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
1356
    let repo = open()?;
1357
    let ops = repo.op_log()?;
1358
    // What each operation changed, against the one before it.
1359
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
1360
        match ops.get(i + 1) {
1361
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
1362
            None => Ok(vec![]),
1363
        }
1364
    };
1365
    if as_json {
1366
        let mut items = Vec::new();
1367
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
1368
            let summary: Vec<String> = changes_of(i)?
1369
                .iter()
1370
                .map(|c| change_words(&repo, c))
1371
                .collect();
1372
            items.push(json::obj([
1373
                ("id", json::s(&r.to_hex())),
1374
                ("when_ms", json::n(op.hlc.wall_ms)),
1375
                ("command", json::s(&op.command)),
1376
                ("snapshot", json::b(op.is_snapshot())),
1377
                ("current", json::b(i == 0)),
1378
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1379
            ]));
1380
        }
1381
        println!("{}", json::arr(items));
1382
        return Ok(0);
1383
    }
1384
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
1385
    let id = |r: &oxy_core::hash::ObjectRef| {
1386
        let hex = r.to_hex();
1387
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
1388
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
1389
    };
1390
    let rail = ui::dim(ui::glyph("│", "|"));
1391
    let (mut i, mut shown) = (0, 0);
1392
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
1393
        let (r, op) = &ops[i];
1394
        let bullet = if i == 0 {
1395
            ui::ok(ui::glyph("@", "@"))
1396
        } else {
1397
            ui::dim(ui::glyph("○", "o"))
1398
        };
1399
        // A run of snapshots folds into one entry.
1400
        let mut run = 1;
1401
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
1402
            run += 1;
1403
        }
1404
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
1405
        if op.is_snapshot() {
1406
            let span = if run > 1 {
1407
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1408
            } else {
1409
                String::new()
1410
            };
1411
            println!(
1412
                "{bullet}  {}{} {when}",
1413
                id(r),
1414
                if span.is_empty() {
1415
                    String::new()
1416
                } else {
1417
                    format!(" {span}")
1418
                }
1419
            );
1420
            println!(
1421
                "{rail}  {}",
1422
                ui::dim(if run == 1 {
1423
                    "working-copy snapshot".to_string()
1424
                } else {
1425
                    format!("{run} working-copy snapshots")
1426
                })
1427
            );
1428
        } else {
1429
            println!("{bullet}  {} {when}", id(r));
1430
            let words: Vec<String> = changes_of(i)?
1431
                .iter()
1432
                .map(|c| change_words(&repo, c))
1433
                .collect();
1434
            let summary = if words.is_empty() {
1435
                if i + 1 == ops.len() {
1436
                    "created the repository".to_string()
1437
                } else {
1438
                    "no bookmark or working-copy change".to_string()
1439
                }
1440
            } else {
1441
                words.join("; ")
1442
            };
1443
            println!(
1444
                "{rail}  {}",
1445
                if i == 0 {
1446
                    ui::subject(&summary)
1447
                } else {
1448
                    summary
1449
                }
1450
            );
1451
            let cmd = op.command.lines().next().unwrap_or("");
1452
            let cmd: String = cmd.chars().take(100).collect();
1453
            println!("{rail}  {}", ui::dim(cmd));
1454
        }
1455
        i += run;
1456
        shown += 1;
1457
    }
1458
    if i < ops.len() {
1459
        println!(
1460
            "{}",
1461
            ui::dim(format!(
1462
                "{} {} older; pass -n to see more",
1463
                ui::glyph("…", "..."),
1464
                plural(ops.len() - i, "operation")
1465
            ))
1466
        );
1467
    }
1468
    Ok(0)
1469
}
1470
1471
/// One change an operation made, in words.
1472
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1473
    use oxy_core::repo::ViewChange::*;
1474
    match c {
1475
        BookmarkCreated { name, heads } => {
1476
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1477
        }
1478
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
1479
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
1480
        BookmarkMoved { name, from, to } => format!(
1481
            "{name}: {from} {} {}",
1482
            ui::glyph("→", "->"),
1483
            plural(*to, "head")
1484
        ),
1485
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
1486
        TagCreated { name } => format!("tagged {name}"),
1487
        TagDeleted { name } => format!("removed tag {name}"),
1488
        Policy => "trust policy changed".to_string(),
1489
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
1490
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
1491
            Err(_) => "working copy moved".to_string(),
1492
        },
1493
    }
1494
}
1495
1496
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
1497
    let repo = open()?;
1498
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
1499
    let r = repo.op_restore(op, discard)?;
1500
    sp.done(&format!(
1501
        "{} to operation {} {}",
1502
        ui::done("Restored"),
1503
        ui::hash(r.op.short(12)),
1504
        ui::dim(r.command.lines().next().unwrap_or(""))
1505
    ));
1506
    println!(
1507
        "  {} {}",
1508
        ui::note(),
1509
        ui::dim(format!(
1510
            "{} written, {} removed; oxy undo goes back again",
1511
            plural(r.checkout.written, "file"),
1512
            r.checkout.removed
1513
        ))
1514
    );
1515
    where_now(&repo);
1516
    Ok(0)
1517
}
1518
1519
pub fn op_revert(op: &str) -> Result<i32> {
1520
    let repo = open()?;
1521
    let r = repo.op_revert(op)?;
1522
    let view = repo.view()?;
1523
    let names: Vec<String> = r
1524
        .reverted
1525
        .iter()
1526
        .map(|n| {
1527
            if view.bookmarks.contains_key(n) {
1528
                ui::bookmark(n)
1529
            } else {
1530
                format!("{} (removed)", ui::bookmark(n))
1531
            }
1532
        })
1533
        .collect();
1534
    println!(
1535
        "{} operation {} {}",
1536
        ui::done("Reverted"),
1537
        ui::hash(r.op.short(12)),
1538
        ui::dim(r.command.lines().next().unwrap_or(""))
1539
    );
1540
    println!(
1541
        "  {} {}",
1542
        ui::note(),
1543
        ui::dim(format!("as before it: {}", names.join(", ")))
1544
    );
1545
    if !r.kept.is_empty() {
1546
        println!(
1547
            "  {} {}",
1548
            ui::caution(),
1549
            ui::warn(format!(
1550
                "left as they are, having moved again since: {}",
1551
                r.kept.join(", ")
1552
            ))
1553
        );
1554
    }
1555
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
1556
        println!(
1557
            "  {} {}",
1558
            ui::note(),
1559
            ui::dim("the working copy has work of its own: oxy checkout to move it")
1560
        );
1561
    }
1562
    where_now(&repo);
1563
    Ok(0)
1564
}
1565
1566
/// Where the working copy and bookmark are now, after a command moved
1567
/// them (as jj says "Working copy now at").
1568
pub fn where_now(repo: &Repo) {
1569
    let Ok((_, wc)) = repo.working_copy() else {
1570
        return;
1571
    };
1572
    let heads = repo.bookmark_heads().unwrap_or_default();
1573
    let newest = heads
1574
        .iter()
1575
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
1576
        .max_by_key(|(m, _)| m.hlc);
1577
    println!(
1578
        "  {} {}",
1579
        ui::dim(format!("{:<13}", "Working copy")),
1580
        ui::id(wc.change_id.short(8))
1581
    );
1582
    let tail = match newest {
1583
        Some((m, _)) => format!(
1584
            ", newest {} {}",
1585
            ui::id(m.change_id.short(8)),
1586
            subject_of(&m.message)
1587
        ),
1588
        None => String::new(),
1589
    };
1590
    println!(
1591
        "  {} {}: {}{tail}",
1592
        ui::dim(format!("{:<13}", "Bookmark")),
1593
        ui::bookmark(&repo.config.bookmark),
1594
        plural(heads.len(), "head")
1595
    );
1596
}
1597
1598
pub fn gc(now: bool) -> Result<i32> {
1599
    let repo = open()?;
1600
    let sp = ui::spinner("Packing and pruning…");
1601
    let r = repo.gc_with(now, &mut |phase| sp.set(&format!("{phase}…")))?;
1602
    sp.clear();
1603
    if r.packed.objects > 0 {
1604
        println!(
1605
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
1606
            plural(r.packed.objects, "object"),
1607
            r.packed.raw_bytes,
1608
            r.packed.packed_bytes,
1609
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
1610
        );
1611
    }
1612
    println!(
1613
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
1614
        plural(r.reachable, "object"),
1615
        plural(r.pruned.objects, "unreachable object"),
1616
        r.pruned.bytes,
1617
        if r.pruned.deferred > 0 {
1618
            format!(
1619
                "; {} deferred by the grace period (use --now)",
1620
                plural(r.pruned.deferred, "object")
1621
            )
1622
        } else {
1623
            String::new()
1624
        },
1625
        if r.merged_packs > 0 {
1626
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1627
        } else {
1628
            String::new()
1629
        },
1630
        plural(repo.store().pack_count(), "pack")
1631
    );
1632
    Ok(0)
1633
}
1634
1635
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
1636
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1637
    use oxy_core::repo::Health;
1638
    let repo = open()?;
1639
    let sp = ui::spinner(if offline {
1640
        "Checking…"
1641
    } else {
1642
        "Checking, and contacting remotes…"
1643
    });
1644
    let r = repo.doctor(!offline);
1645
    sp.clear();
1646
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
1647
    let word = |h: Health| match h {
1648
        Health::Ok => "ok",
1649
        Health::Warn => "warning",
1650
        Health::Fail => "fail",
1651
    };
1652
    if as_json {
1653
        let checks: Vec<String> = r
1654
            .checks
1655
            .iter()
1656
            .map(|c| {
1657
                json::obj([
1658
                    ("area", json::s(&c.area)),
1659
                    ("health", json::s(word(c.health))),
1660
                    ("message", json::s(&c.message)),
1661
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
1662
                ])
1663
            })
1664
            .collect();
1665
        println!(
1666
            "{}",
1667
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1668
        );
1669
        return Ok(code);
1670
    }
1671
    let mut last = "";
1672
    for c in &r.checks {
1673
        if c.area != last {
1674
            println!("{}", ui::section(&c.area));
1675
            last = &c.area;
1676
        }
1677
        let mark = match c.health {
1678
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
1679
            Health::Warn => ui::caution(),
1680
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1681
        };
1682
        println!("  {mark} {}", c.message);
1683
        if let Some(h) = &c.hint {
1684
            println!("    {} {}", ui::dim("→"), ui::dim(h));
1685
        }
1686
    }
1687
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
1688
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
1689
    if fails + warns == 0 {
1690
        println!("{}", ui::done("Everything looks right."));
1691
    } else {
1692
        println!(
1693
            "{} {}, {}.",
1694
            if fails > 0 {
1695
                ui::err(ui::glyph("✖", "x"))
1696
            } else {
1697
                ui::caution()
1698
            },
1699
            plural(fails, "problem"),
1700
            plural(warns, "warning")
1701
        );
1702
    }
1703
    Ok(code)
1704
}
1705
1706
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
1707
pub fn fsck(as_json: bool) -> Result<i32> {
1708
    use oxy_core::repo::Severity;
1709
    let repo = open()?;
1710
    let sp = ui::spinner("Checking every object…");
1711
    let r = repo.fsck()?;
1712
    sp.clear();
1713
    let code = if r.errors() > 0 { 1 } else { 0 };
1714
    if as_json {
1715
        let problems: Vec<String> = r
1716
            .problems
1717
            .iter()
1718
            .map(|p| {
1719
                json::obj([
1720
                    (
1721
                        "severity",
1722
                        json::s(match p.severity {
1723
                            Severity::Error => "error",
1724
                            Severity::Warning => "warning",
1725
                        }),
1726
                    ),
1727
                    (
1728
                        "object",
1729
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1730
                    ),
1731
                    ("what", json::s(&p.what)),
1732
                ])
1733
            })
1734
            .collect();
1735
        println!(
1736
            "{}",
1737
            json::obj([
1738
                ("ok", json::b(code == 0)),
1739
                ("objects", json::n(r.objects)),
1740
                ("ops", json::n(r.ops)),
1741
                ("changes", json::n(r.changes)),
1742
                ("signed", json::n(r.signed)),
1743
                ("unsigned", json::n(r.unsigned)),
1744
                ("checkpoints", json::n(r.checkpoints)),
1745
                ("attestations", json::n(r.attestations)),
1746
                ("errors", json::n(r.errors())),
1747
                ("warnings", json::n(r.warnings())),
1748
                ("problems", json::arr(problems)),
1749
            ])
1750
        );
1751
        return Ok(code);
1752
    }
1753
    println!(
1754
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
1755
        plural(r.objects, "object"),
1756
        plural(r.ops, "operation"),
1757
        plural(r.changes, "change"),
1758
        r.signed,
1759
        r.unsigned,
1760
        plural(r.checkpoints, "checkpoint"),
1761
        plural(r.attestations, "attestation"),
1762
    );
1763
    for p in &r.problems {
1764
        let obj = p
1765
            .object
1766
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
1767
            .unwrap_or_default();
1768
        match p.severity {
1769
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
1770
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1771
        }
1772
    }
1773
    if r.problems.is_empty() {
1774
        println!("{}", ui::done("No problems found."));
1775
    } else if code == 0 {
1776
        println!(
1777
            "{}",
1778
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
1779
        );
1780
    } else {
1781
        println!(
1782
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
1783
            ui::err(ui::glyph("✖", "x")),
1784
            plural(r.errors(), "error"),
1785
            plural(r.warnings(), "warning")
1786
        );
1787
    }
1788
    Ok(code)
1789
}
1790
1791
/// The head the working copy sits on, for commands that default to it. With
1792
/// several heads beneath the working copy, the most recently made one is
1793
/// chosen and announced.
1794
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
1795
    let snap = repo.snapshot_status("oxy")?;
1796
    let base = snap.base.maximal(&snap.wc.deps);
1797
    match base.as_slice() {
1798
        [] => anyhow::bail!("the working copy sits on no change yet"),
1799
        [h] => Ok(*h),
1800
        many => {
1801
            let latest = many
1802
                .iter()
1803
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
1804
                .copied()
1805
                .unwrap();
1806
            let c = repo.store().get_change(&latest)?;
1807
            println!(
1808
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
1809
                short_id(&c),
1810
                latest.short(12),
1811
                many.len()
1812
            );
1813
            Ok(latest)
1814
        }
1815
    }
1816
}
1817
1818
/// `oxy describe` without -m: the working copy's name for a build.
1819
pub fn describe_name(as_json: bool) -> Result<i32> {
1820
    let repo = open()?;
1821
    let d = repo.describe_working_copy()?;
1822
    if as_json {
1823
        println!(
1824
            "{}",
1825
            json::obj([
1826
                ("describe", json::s(&d.line())),
1827
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
1828
                ("distance", json::n(d.distance)),
1829
                ("bookmark", json::s(&d.bookmark)),
1830
                ("change", json::s(&d.change.to_hex())),
1831
                ("hash", json::s(&d.hash.to_hex())),
1832
                ("dirty", json::b(d.dirty)),
1833
            ])
1834
        );
1835
    } else {
1836
        println!("{}", d.line());
1837
    }
1838
    Ok(0)
1839
}
1840
1841
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
1842
    let repo = open()?;
1843
    let h = match change {
1844
        Some(c) => repo.resolve_change(c)?,
1845
        None => current_head(&repo)?,
1846
    };
1847
    let new = repo.describe(&h, message)?;
1848
    let c = repo.store().get_change_meta(&new)?;
1849
    println!(
1850
        "{} {} {}  {}",
1851
        ui::done("Described"),
1852
        ui::id(c.change_id.short(8)),
1853
        ui::hash(format!("#{}", new.short(12))),
1854
        ui::subject(subject_of(message))
1855
    );
1856
    Ok(0)
1857
}
1858
1859
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
1860
    let repo = open()?;
1861
    let new = match into {
1862
        Some(spec) => {
1863
            let target = repo.resolve_change(spec)?;
1864
            repo.amend_into(&target, message)?
1865
        }
1866
        None => repo.amend(message)?,
1867
    };
1868
    let c = repo.store().get_change_meta(&new)?;
1869
    println!(
1870
        "{} {} {}  {}",
1871
        ui::done("Amended"),
1872
        ui::id(c.change_id.short(8)),
1873
        ui::hash(format!("#{}", new.short(12))),
1874
        ui::subject(subject_of(&c.message))
1875
    );
1876
    where_now(&repo);
1877
    Ok(0)
1878
}
1879
1880
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
1881
    let repo = open()?;
1882
    let Some(r) = revset else {
1883
        let h = repo.resolve_change(change.unwrap_or_default())?;
1884
        abandon_one(&repo, h)?;
1885
        where_now(&repo);
1886
        return Ok(0);
1887
    };
1888
    // A revset: say what it selects, refuse an empty set, ask above a few.
1889
    let selected = repo.revset(r)?;
1890
    let wc = repo.working_copy().ok().map(|(h, _)| h);
1891
    let hashes: Vec<ChangeHash> = selected
1892
        .hashes
1893
        .iter()
1894
        .copied()
1895
        .filter(|h| Some(*h) != wc)
1896
        .collect();
1897
    if hashes.is_empty() {
1898
        anyhow::bail!("{r:?} selects no change to abandon");
1899
    }
1900
    println!(
1901
        "{} {} selects {}:",
1902
        ui::section("abandon"),
1903
        ui::id(r),
1904
        plural(hashes.len(), "change")
1905
    );
1906
    for h in &hashes {
1907
        if let Some(m) = selected.metas.get(h) {
1908
            println!(
1909
                "  {} {}  {}",
1910
                ui::id(m.change_id.short(8)),
1911
                ui::hash(format!("#{}", h.short(12))),
1912
                subject_of(&m.message)
1913
            );
1914
        }
1915
    }
1916
    const ASK_ABOVE: usize = 5;
1917
    if hashes.len() > ASK_ABOVE && !yes {
1918
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
1919
    }
1920
    // Newest first: abandoning a change rewrites what depends on it, so a
1921
    // later member is found again by its ChangeId.
1922
    let mut done = 0;
1923
    for h in &hashes {
1924
        let Some(m) = selected.metas.get(h) else {
1925
            continue;
1926
        };
1927
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
1928
            Ok(h) => h,
1929
            Err(_) => continue,
1930
        };
1931
        abandon_one(&repo, now)?;
1932
        done += 1;
1933
    }
1934
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
1935
    where_now(&repo);
1936
    Ok(0)
1937
}
1938
1939
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
1940
    let c = repo.store().get_change_meta(&h)?;
1941
    let notes = repo.abandon(&h)?;
1942
    println!(
1943
        "{} {} {}  {}",
1944
        ui::done("Abandoned"),
1945
        ui::id(c.change_id.short(8)),
1946
        ui::hash(format!("#{}", h.short(12))),
1947
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
1948
    );
1949
    for n in notes {
1950
        println!("  {} {n}", ui::note());
1951
    }
1952
    Ok(())
1953
}
1954
1955
pub fn checkpoint() -> Result<i32> {
1956
    let repo = open()?;
1957
    let sp = ui::spinner("Writing checkpoint…");
1958
    let (r, changes, bytes) = repo.checkpoint()?;
1959
    sp.done(&format!(
1960
        "{} {} of {} ({} bytes) for {}",
1961
        ui::done("Checkpoint"),
1962
        ui::hash(format!("#{}", r.short(12))),
1963
        plural(changes, "change"),
1964
        bytes,
1965
        ui::id(&repo.config.bookmark)
1966
    ));
1967
    Ok(0)
1968
}
1969
1970
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
1971
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
1972
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
1973
        return Ok(1);
1974
    };
1975
    let info = repo.quick_status()?;
1976
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
1977
        oxy_core::repo::GLYPH_PROMPT_FORMAT
1978
    } else {
1979
        format
1980
    };
1981
    let line = match color {
1982
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
1983
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
1984
        Some(_) => info.format_colored(fmt, ("", "")),
1985
        None => info.format(fmt),
1986
    };
1987
    println!("{line}");
1988
    Ok(0)
1989
}
1990
1991
pub fn sparse(paths: &[String]) -> Result<i32> {
1992
    let mut repo = open()?;
1993
    if paths.is_empty() {
1994
        if repo.config.sparse_paths.is_empty() {
1995
            println!("No sparse filter: the whole tree is materialized.");
1996
        } else {
1997
            println!("{}", ui::heading("Sparse filter"));
1998
            for p in &repo.config.sparse_paths {
1999
                println!("  {}", ui::path(p));
2000
            }
2001
        }
2002
        return Ok(0);
2003
    }
2004
    let snap = repo.snapshot("oxy sparse")?;
2005
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
2006
        anyhow::bail!(
2007
            "the working copy has changes; commit them before changing the sparse filter"
2008
        );
2009
    }
2010
    repo.config.set("filter.paths", &paths.join(","))?;
2011
    repo.save_config()?;
2012
    let heads = repo.bookmark_heads()?;
2013
    let sp = ui::spinner("Re-checking out with the new filter…");
2014
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
2015
    sp.done(&format!(
2016
        "{} {}: {} written, {} removed",
2017
        ui::done("Sparse filter set to"),
2018
        ui::path(paths.join(",")),
2019
        plural(r.written, "file"),
2020
        r.removed
2021
    ));
2022
    Ok(0)
2023
}
2024
2025
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
2026
    let repo = open()?;
2027
    repo.snapshot_status("oxy tag")?;
2028
    let heads = if changes.is_empty() {
2029
        repo.bookmark_heads()?
2030
    } else {
2031
        let mut heads = Vec::new();
2032
        for c in changes {
2033
            heads.extend(repo.resolve_heads(c)?);
2034
        }
2035
        heads
2036
    };
2037
    let t = repo.tag_create(name, &heads, message)?;
2038
    println!(
2039
        "{} {} {} {} ({}){}",
2040
        ui::done("Tagged"),
2041
        ui::bookmark(&t.name),
2042
        ui::dim(ui::glyph("→", "->")),
2043
        ui::hash(format!("#{}", t.state.short(12))),
2044
        plural(t.heads.len(), "head"),
2045
        t.signer
2046
            .map(|s| format!(", signed by {s}"))
2047
            .unwrap_or_else(|| ui::dim(", unsigned"))
2048
    );
2049
    Ok(0)
2050
}
2051
2052
pub fn tag_list(as_json: bool) -> Result<i32> {
2053
    let repo = open()?;
2054
    let tags = repo.tags()?;
2055
    if as_json {
2056
        println!(
2057
            "{}",
2058
            json::arr(tags.iter().map(|t| {
2059
                json::obj([
2060
                    ("name", json::s(&t.name)),
2061
                    ("state", json::s(&t.state.to_hex())),
2062
                    ("heads", json::hashes(&t.heads)),
2063
                    ("message", json::s(&t.message)),
2064
                    (
2065
                        "signer",
2066
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2067
                    ),
2068
                ])
2069
            }))
2070
        );
2071
        return Ok(0);
2072
    }
2073
    if tags.is_empty() {
2074
        println!("{}", ui::dim("No tags."));
2075
    }
2076
    for t in tags {
2077
        println!(
2078
            "{} {} {}{}{}{}",
2079
            ui::ok(ui::glyph("⚑", "#")),
2080
            ui::bookmark(&t.name),
2081
            // The heads, as `oxy log` shows changes, not the state hash.
2082
            ui::hash(
2083
                t.heads
2084
                    .iter()
2085
                    .map(|h| format!("#{}", h.short(12)))
2086
                    .collect::<Vec<_>>()
2087
                    .join(" ")
2088
            ),
2089
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
2090
            if t.message.is_empty() {
2091
                String::new()
2092
            } else {
2093
                format!("  {}", ui::subject(subject_of(&t.message)))
2094
            },
2095
            t.signer
2096
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
2097
                .unwrap_or_default()
2098
        );
2099
    }
2100
    Ok(0)
2101
}
2102
2103
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2104
/// and workspace add take as "be on this bookmark" (oxygen#60).
2105
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
2106
    Ok(repo.view()?.bookmarks.contains_key(name)
2107
        || repo
2108
            .remote_only_bookmarks()?
2109
            .iter()
2110
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
2111
}
2112
2113
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
2114
    let repo = open()?;
2115
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2116
    // this workspace's bookmark with that one's files.
2117
    if let [name] = changes {
2118
        if names_bookmark(&repo, name)? {
2119
            let (local, _) = repo.local_bookmark_for(name)?;
2120
            let heads = repo.resolve_heads(&local)?;
2121
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
2122
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
2123
            sp.done(&format!(
2124
                "{} {} (workspace {}) on {}",
2125
                ui::done("Workspace created at"),
2126
                ui::path(ws.root().display()),
2127
                ui::id(ws.workspace().short(8)),
2128
                ui::bookmark(&local)
2129
            ));
2130
            return Ok(0);
2131
        }
2132
    }
2133
    let heads = if changes.is_empty() {
2134
        None
2135
    } else {
2136
        let mut heads = Vec::new();
2137
        for c in changes {
2138
            heads.extend(repo.resolve_heads(c)?);
2139
        }
2140
        Some(heads)
2141
    };
2142
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
2143
    let ws = repo.workspace_add(path, heads.as_deref())?;
2144
    sp.done(&format!(
2145
        "{} {} (workspace {})",
2146
        ui::done("Workspace created at"),
2147
        ui::path(ws.root().display()),
2148
        ui::id(ws.workspace().short(8))
2149
    ));
2150
    Ok(0)
2151
}
2152
2153
pub fn workspace_list(as_json: bool) -> Result<i32> {
2154
    let repo = open()?;
2155
    if as_json {
2156
        println!(
2157
            "{}",
2158
            json::arr(repo.workspaces()?.iter().map(|w| {
2159
                json::obj([
2160
                    ("id", json::s(&w.id.to_hex())),
2161
                    ("path", json::s(&w.path.to_string_lossy())),
2162
                    ("current", json::b(w.current)),
2163
                    (
2164
                        "working_copy",
2165
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2166
                    ),
2167
                ])
2168
            }))
2169
        );
2170
        return Ok(0);
2171
    }
2172
    for w in repo.workspaces()? {
2173
        println!(
2174
            "{} {} {}{}",
2175
            if w.current {
2176
                ui::ok(ui::glyph("●", "*"))
2177
            } else {
2178
                ui::dim(ui::glyph("○", "o"))
2179
            },
2180
            ui::id(w.id.short(8)),
2181
            ui::path(w.path.display()),
2182
            w.working_copy
2183
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
2184
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2185
        );
2186
    }
2187
    Ok(0)
2188
}
2189
2190
pub fn workspace_forget(spec: &str) -> Result<i32> {
2191
    let repo = open()?;
2192
    let all = repo.workspaces()?;
2193
    let target = std::fs::canonicalize(spec).ok();
2194
    let matches: Vec<_> = all
2195
        .iter()
2196
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
2197
        .collect();
2198
    let w = match matches.as_slice() {
2199
        [w] => *w,
2200
        [] => anyhow::bail!("no workspace matches {spec:?}"),
2201
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2202
    };
2203
    repo.workspace_forget(&w.id)?;
2204
    println!(
2205
        "{} workspace {} at {}; its files were left in place.",
2206
        ui::done("Forgot"),
2207
        ui::id(w.id.short(8)),
2208
        ui::path(w.path.display())
2209
    );
2210
    Ok(0)
2211
}
2212
2213
pub fn lock(path: &str) -> Result<i32> {
2214
    let repo = open()?;
2215
    repo.lock_path(path)?;
2216
    println!(
2217
        "{} {} {}",
2218
        ui::done("Locked"),
2219
        ui::path(path),
2220
        ui::dim("(advisory, local)")
2221
    );
2222
    Ok(0)
2223
}
2224
2225
pub fn unlock(path: &str) -> Result<i32> {
2226
    let repo = open()?;
2227
    repo.unlock_path(path)?;
2228
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
2229
    Ok(0)
2230
}
2231
2232
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
2233
    let repo = open()?;
2234
    let h = repo.resolve_change(change)?;
2235
    let (h1, h2) = repo.split(&h, paths)?;
2236
    let c1 = repo.store().get_change_meta(&h1)?;
2237
    let c2 = repo.store().get_change_meta(&h2)?;
2238
    println!(
2239
        "{} into {} {} and {} {}",
2240
        ui::done("Split"),
2241
        ui::id(c1.change_id.short(8)),
2242
        ui::hash(format!("#{}", h1.short(12))),
2243
        ui::id(c2.change_id.short(8)),
2244
        ui::hash(format!("#{}", h2.short(12)))
2245
    );
2246
    Ok(0)
2247
}
2248
2249
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
2250
    let mut heads = Vec::new();
2251
    for c in changes {
2252
        heads.extend(repo.resolve_heads(c)?);
2253
    }
2254
    Ok(heads)
2255
}
2256
2257
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
2258
    let repo = open()?;
2259
    repo.snapshot_status("oxy bookmark create")?;
2260
    let heads = if changes.is_empty() {
2261
        None
2262
    } else {
2263
        let named = heads_from(&repo, changes)?;
2264
        let (_, wc) = repo.working_copy()?;
2265
        let gap = repo.state_gap(&wc.deps, &named)?;
2266
        if upto {
2267
            Some(gap.upto)
2268
        } else if only || gap.earlier.is_empty() {
2269
            Some(named)
2270
        } else {
2271
            anyhow::bail!(
2272
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2273
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2274
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2275
                 or --only for just {0} and what it depends on.",
2276
                changes.join(" "),
2277
                plural(gap.earlier.len(), "change"),
2278
                listed_changes(&repo, &gap.earlier)
2279
            );
2280
        }
2281
    };
2282
    let heads = repo.bookmark_create(name, heads.as_deref())?;
2283
    println!(
2284
        "{} bookmark {} {} {}",
2285
        ui::done("Created"),
2286
        ui::bookmark(name),
2287
        ui::dim(ui::glyph("→", "->")),
2288
        ui::dim(plural(heads.len(), "head"))
2289
    );
2290
    println!(
2291
        "  {} {}",
2292
        ui::note(),
2293
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2294
    );
2295
    Ok(0)
2296
}
2297
2298
/// Up to five changes, newest last, as `  #hash subject` lines.
2299
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
2300
    let shown = changes.len().min(5);
2301
    let mut lines: Vec<String> = changes[changes.len() - shown..]
2302
        .iter()
2303
        .map(|h| {
2304
            let subject = repo
2305
                .store()
2306
                .get_change(h)
2307
                .map(|c| subject_of(&c.message).to_string())
2308
                .unwrap_or_default();
2309
            format!("  #{} {subject}", h.short(12))
2310
        })
2311
        .collect();
2312
    if changes.len() > shown {
2313
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
2314
    }
2315
    lines.join("\n")
2316
}
2317
2318
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
2319
    let repo = open()?;
2320
    repo.snapshot_status("oxy bookmark set")?;
2321
    let named = heads_from(&repo, changes)?;
2322
    // What the bookmark holds now and the new heads would leave out.
2323
    let current = repo
2324
        .bookmarks()?
2325
        .into_iter()
2326
        .find(|b| b.name == name)
2327
        .map(|b| b.heads)
2328
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
2329
    let gap = repo.state_gap(&current, &named)?;
2330
    let heads = if upto {
2331
        gap.upto
2332
    } else if only || gap.earlier.is_empty() {
2333
        named
2334
    } else {
2335
        anyhow::bail!(
2336
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2337
             A state is its heads and what they depend on, not everything recorded before them.\n\
2338
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2339
             or --only for just {0} and what it depends on.",
2340
            changes.join(" "),
2341
            plural(gap.earlier.len(), "change"),
2342
            listed_changes(&repo, &gap.earlier)
2343
        );
2344
    };
2345
    let heads = repo.bookmark_set(name, &heads)?;
2346
    println!(
2347
        "{} bookmark {} {} {}",
2348
        ui::done("Moved"),
2349
        ui::bookmark(name),
2350
        ui::dim(ui::glyph("→", "->")),
2351
        ui::dim(plural(heads.len(), "head"))
2352
    );
2353
    Ok(0)
2354
}
2355
2356
pub fn bookmark_delete(name: &str) -> Result<i32> {
2357
    let repo = open()?;
2358
    repo.bookmark_delete(name)?;
2359
    println!(
2360
        "{} bookmark {} {}",
2361
        ui::done("Deleted"),
2362
        ui::bookmark(name),
2363
        ui::dim("(its changes stay until unreachable)")
2364
    );
2365
    Ok(0)
2366
}
2367
2368
/// Heads with their metadata, newest first.
2369
fn heads_newest_first(
2370
    repo: &Repo,
2371
    heads: &[oxy_core::hash::ChangeHash],
2372
) -> Vec<(oxy_core::hash::ChangeHash, oxy_core::state::ChangeMeta)> {
2373
    let mut out: Vec<_> = heads
2374
        .iter()
2375
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (*h, m)))
2376
        .collect();
2377
    out.sort_by_key(|(_, m)| std::cmp::Reverse(m.hlc));
2378
    out
2379
}
2380
2381
/// One head as a line: id, hash, author, when, subject.
2382
fn print_head(
2383
    repo: &Repo,
2384
    indent: &str,
2385
    h: &oxy_core::hash::ChangeHash,
2386
    m: &oxy_core::state::ChangeMeta,
2387
) {
2388
    println!(
2389
        "{indent}{} {} {}{}{}{}{}",
2390
        ui::id(m.change_id.short(8)),
2391
        ui::dim(format!("#{}", &h.to_hex()[..8])),
2392
        author_name(repo, m),
2393
        ui::sep(),
2394
        ui::dim(ui::ago(m.hlc.wall_ms)),
2395
        ui::sep(),
2396
        ui::subject(subject_of(&m.message))
2397
    );
2398
}
2399
2400
pub fn bookmark_show(name: Option<&str>, as_json: bool) -> Result<i32> {
2401
    let repo = open()?;
2402
    let name = name.unwrap_or(&repo.config.bookmark).to_string();
2403
    let view = repo.view()?;
2404
    let st = match view.bookmarks.get(&name) {
2405
        Some(st) => *st,
2406
        None => match oxy_core::repo::remote_bookmark(&view, &name) {
2407
            Some((_, _, st)) => st,
2408
            None => anyhow::bail!("no bookmark {name}: oxy bookmark list --all lists them"),
2409
        },
2410
    };
2411
    let heads = repo.store().get_state(&st)?.heads;
2412
    let shown = heads_newest_first(&repo, &heads);
2413
    if as_json {
2414
        println!(
2415
            "{}",
2416
            json::obj([
2417
                ("name", json::s(&name)),
2418
                ("current", json::b(name == repo.config.bookmark)),
2419
                (
2420
                    "heads",
2421
                    json::arr(shown.iter().map(|(h, m)| {
2422
                        json::obj([
2423
                            ("hash", json::s(&h.to_hex())),
2424
                            ("id", json::s(&m.change_id.to_string())),
2425
                            ("author", json::s(&author_name(&repo, m))),
2426
                            ("time_ms", json::n(m.hlc.wall_ms)),
2427
                            ("subject", json::s(subject_of(&m.message))),
2428
                        ])
2429
                    }))
2430
                ),
2431
            ])
2432
        );
2433
        return Ok(0);
2434
    }
2435
    println!(
2436
        "{} {}{}{}",
2437
        ui::ok(ui::glyph("●", "*")),
2438
        ui::bookmark(&name),
2439
        ui::sep(),
2440
        ui::dim(plural(heads.len(), "head"))
2441
    );
2442
    for (h, m) in &shown {
2443
        print_head(&repo, "  ", h, m);
2444
    }
2445
    if heads.len() > 1 {
2446
        println!(
2447
            "  {}",
2448
            ui::dim("None depends on another: the bookmark is all of them and their dependencies.")
2449
        );
2450
    }
2451
    Ok(0)
2452
}
2453
2454
pub fn bookmark_list(all: bool, verbose: bool, as_json: bool) -> Result<i32> {
2455
    let repo = open()?;
2456
    let remote_only = repo.remote_only_bookmarks()?;
2457
    if as_json {
2458
        let mut items: Vec<String> = repo
2459
            .bookmarks()?
2460
            .into_iter()
2461
            .map(|b| {
2462
                json::obj([
2463
                    ("name", json::s(&b.name)),
2464
                    ("heads", json::hashes(&b.heads)),
2465
                    ("current", json::b(b.current)),
2466
                    ("ahead", json::opt(b.ahead, json::n)),
2467
                    ("behind", json::opt(b.behind, json::n)),
2468
                    ("remote", json::opt(b.remote.as_deref(), json::s)),
2469
                ])
2470
            })
2471
            .collect();
2472
        if all {
2473
            items.extend(remote_only.iter().map(|b| {
2474
                json::obj([
2475
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
2476
                    ("heads", json::hashes(&b.heads)),
2477
                    ("current", json::b(false)),
2478
                    ("ahead", "null".into()),
2479
                    ("behind", "null".into()),
2480
                    ("remote", json::s(&b.remote)),
2481
                ])
2482
            }));
2483
        }
2484
        println!("{}", json::arr(items));
2485
        return Ok(0);
2486
    }
2487
    for b in repo.bookmarks()? {
2488
        let mark = if b.current {
2489
            ui::ok(ui::glyph("●", "*"))
2490
        } else {
2491
            ui::dim(ui::glyph("○", "o"))
2492
        };
2493
        let mut tail = String::new();
2494
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
2495
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
2496
        }
2497
        if let Some(n) = b.behind.filter(|n| *n > 0) {
2498
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
2499
        }
2500
        // Which remote, when there is a choice (oxygen#83).
2501
        if !tail.is_empty() && repo.config.remotes.len() > 1 {
2502
            if let Some(r) = &b.remote {
2503
                tail += &ui::dim(format!(" {r}"));
2504
            }
2505
        }
2506
        let shown = heads_newest_first(&repo, &b.heads);
2507
        // The newest head's subject, so a busy bookmark shows its latest work.
2508
        let head = match shown.first() {
2509
            Some(_) if verbose => String::new(),
2510
            Some((_, m)) if b.heads.len() > 1 => format!(
2511
                "{} {}",
2512
                ui::dim("newest"),
2513
                ui::subject(subject_of(&m.message))
2514
            ),
2515
            Some((_, m)) => ui::subject(subject_of(&m.message)),
2516
            None => ui::dim("(empty)"),
2517
        };
2518
        let head = if head.is_empty() {
2519
            head
2520
        } else {
2521
            format!("  {head}")
2522
        };
2523
        println!(
2524
            "{mark} {}{}{}{tail}{head}",
2525
            ui::bookmark(&b.name),
2526
            ui::sep(),
2527
            ui::dim(plural(b.heads.len(), "head"))
2528
        );
2529
        if verbose {
2530
            for (h, m) in &shown {
2531
                print_head(&repo, "    ", h, m);
2532
            }
2533
        }
2534
    }
2535
    if remote_only.is_empty() {
2536
        return Ok(0);
2537
    }
2538
    if !all {
2539
        println!(
2540
            "{}",
2541
            ui::dim(format!(
2542
                "  and {} only on a remote: oxy bookmark list --all",
2543
                plural(remote_only.len(), "bookmark")
2544
            ))
2545
        );
2546
        return Ok(0);
2547
    }
2548
    for b in &remote_only {
2549
        println!(
2550
            "{} {}{}{}",
2551
            ui::dim(ui::glyph("◌", ".")),
2552
            ui::dim(format!("{}/{}", b.remote, b.name)),
2553
            ui::sep(),
2554
            ui::dim(plural(b.heads.len(), "head"))
2555
        );
2556
    }
2557
    println!(
2558
        "  {} {}",
2559
        ui::note(),
2560
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2561
    );
2562
    Ok(0)
2563
}
2564
2565
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
2566
    let mut repo = open()?;
2567
    let from = repo.config.bookmark.clone();
2568
    let (local, created_from) = repo.local_bookmark_for(name)?;
2569
    if let Some(remote) = created_from {
2570
        println!(
2571
            "{} {} from {}",
2572
            ui::done("Created"),
2573
            ui::bookmark(&local),
2574
            ui::dim(format!("{remote}/{local}"))
2575
        );
2576
    }
2577
    let name = local.as_str();
2578
    // Only behind its remote: take the remote's state, so the switch does
2579
    // not check out a stale one (oxygen#74).
2580
    if let Some(n) = repo.catch_up_bookmark(name)? {
2581
        println!(
2582
            "{} {} with {}: {} it lacked",
2583
            ui::done("Caught up"),
2584
            ui::bookmark(name),
2585
            ui::dim(format!("{}/{name}", repo.default_remote())),
2586
            plural(n, "change")
2587
        );
2588
    }
2589
    let sp = ui::spinner(&format!("Switching to {name}…"));
2590
    let (r, carried) = if carry {
2591
        repo.bookmark_switch_carry(name)?
2592
    } else {
2593
        (repo.bookmark_switch(name, discard)?, vec![])
2594
    };
2595
    sp.done(&format!(
2596
        "{} to {}: {} written, {} removed{}",
2597
        ui::done("Switched"),
2598
        ui::bookmark(name),
2599
        plural(r.written, "file"),
2600
        r.removed,
2601
        if carried.is_empty() {
2602
            String::new()
2603
        } else {
2604
            format!("; carried {}", plural(carried.len(), "changed path"))
2605
        }
2606
    ));
2607
    if r.conflicted {
2608
        println!(
2609
            "  {} {}",
2610
            ui::caution(),
2611
            ui::warn("this state has conflicts; see oxy status")
2612
        );
2613
    }
2614
    // Say when the new state leaves out work the old one had: a state is
2615
    // its heads and what they depend on, which can be far less than a Git
2616
    // user expects.
2617
    if r.lacks > 0 {
2618
        println!(
2619
            "  {} {}",
2620
            ui::note(),
2621
            ui::dim(format!(
2622
                "{name} lacks {} that {from} has",
2623
                plural(r.lacks, "change")
2624
            ))
2625
        );
2626
    }
2627
    super::sync::subrepos_behind(&repo);
2628
    where_now(&repo);
2629
    Ok(0)
2630
}
2631
2632
pub fn merge(bookmark: &str) -> Result<i32> {
2633
    let repo = open()?;
2634
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
2635
    let r = repo.merge(bookmark)?;
2636
    if !r.changed {
2637
        sp.done(&format!(
2638
            "{} {}",
2639
            ui::ok(ui::glyph("✔", "*")),
2640
            ui::dim(format!(
2641
                "{} already contains {bookmark}",
2642
                repo.config.bookmark
2643
            ))
2644
        ));
2645
        return Ok(0);
2646
    }
2647
    sp.done(&format!(
2648
        "{} {} into {}: now {}{}",
2649
        ui::done("Merged"),
2650
        ui::bookmark(bookmark),
2651
        ui::bookmark(&repo.config.bookmark),
2652
        plural(r.heads.len(), "head"),
2653
        ui::dim(if r.checked_out {
2654
            "; working copy updated"
2655
        } else {
2656
            "; run oxy checkout to update the working copy"
2657
        })
2658
    ));
2659
    let snap = repo.snapshot("oxy merge")?;
2660
    if snap.base_snapshot.is_conflicted() {
2661
        println!(
2662
            "  {} {}",
2663
            ui::caution(),
2664
            ui::warn("the result has conflicts; see oxy status")
2665
        );
2666
    }
2667
    where_now(&repo);
2668
    Ok(0)
2669
}
2670
2671
pub fn squash(change: &str, into: &str) -> Result<i32> {
2672
    let repo = open()?;
2673
    let c = repo.resolve_change(change)?;
2674
    let d = repo.resolve_change(into)?;
2675
    let sp = ui::spinner("Squashing…");
2676
    let h = repo.squash(&c, &d)?;
2677
    let new = repo.store().get_change_meta(&h)?;
2678
    sp.done(&format!(
2679
        "{} into {} {}  {}",
2680
        ui::done("Squashed"),
2681
        ui::id(new.change_id.short(8)),
2682
        ui::hash(format!("#{}", h.short(12))),
2683
        ui::subject(subject_of(&new.message))
2684
    ));
2685
    Ok(0)
2686
}
2687
2688
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
2689
    let repo = open()?;
2690
    let c = repo.resolve_change(change)?;
2691
    let mut heads = Vec::new();
2692
    for o in onto {
2693
        heads.extend(repo.resolve_heads(o)?);
2694
    }
2695
    let sp = ui::spinner("Rebasing…");
2696
    let h = match repo.rebase(&c, &heads) {
2697
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
2698
            let r = repo.rebase_into_working_copy(&c, &heads)?;
2699
            sp.done(&format!(
2700
                "{} {} into {}: now {}",
2701
                ui::done("Merged"),
2702
                onto.join(" "),
2703
                ui::bookmark(&repo.config.bookmark),
2704
                plural(r.heads.len(), "head"),
2705
            ));
2706
            if r.checked_out {
2707
                println!(
2708
                    "  {} {}",
2709
                    ui::caution(),
2710
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
2711
                );
2712
            } else {
2713
                println!(
2714
                    "  {} {}",
2715
                    ui::caution(),
2716
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
2717
                );
2718
            }
2719
            where_now(&repo);
2720
            return Ok(0);
2721
        }
2722
        other => other?,
2723
    };
2724
    let new = repo.store().get_change_meta(&h)?;
2725
    sp.done(&format!(
2726
        "{} {} {}  {}",
2727
        ui::done("Rebased"),
2728
        ui::id(new.change_id.short(8)),
2729
        ui::hash(format!("#{}", h.short(12))),
2730
        ui::dim(format!(
2731
            "now depends on {}",
2732
            plural(new.deps.len(), "change")
2733
        ))
2734
    ));
2735
    where_now(&repo);
2736
    Ok(0)
2737
}
2738
2739
#[cfg(test)]
2740
mod tests {
2741
    use super::*;
2742
2743
    #[test]
2744
    fn id_prefixes_agree_with_the_whole_list() {
2745
        // Ids that share long prefixes, and some that differ only in a
2746
        // half byte, from a fixed sequence.
2747
        let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
2748
        let mut next = || {
2749
            x ^= x << 13;
2750
            x ^= x >> 7;
2751
            x ^= x << 17;
2752
            x
2753
        };
2754
        let mut ids: Vec<[u8; 16]> = Vec::new();
2755
        for _ in 0..2000 {
2756
            let mut id = [0u8; 16];
2757
            id[..8].copy_from_slice(&next().to_le_bytes());
2758
            id[8..].copy_from_slice(&next().to_le_bytes());
2759
            let share = (next() % 4) as usize;
2760
            if let Some(prev) = ids.last() {
2761
                id[..share].copy_from_slice(&prev[..share]);
2762
                if next() % 2 == 0 {
2763
                    id[share] = (prev[share] & 0xf0) | (id[share] & 0x0f);
2764
                }
2765
            }
2766
            ids.push(id);
2767
        }
2768
        let hex = |id: &[u8; 16]| oxy_core::ids::ChangeId(*id).to_hex();
2769
        let whole = unique_prefixes(ids.iter().map(hex));
2770
        let some = id_prefixes(ids.clone(), ids.iter().copied());
2771
        for id in &ids {
2772
            assert_eq!(some[id], whole[&hex(id)], "{}", hex(id));
2773
        }
2774
    }
2775
}