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