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