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