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