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