OXYGENHUB
# c71a5777509a oxygen / src / cli / workspace.rs
76.5 KiB · Rust · last changed checkout BOOKMARK switches to it; workspace add takes a bookmark and its subrepos 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
    limit: Option<usize>,
581
    verbose: bool,
582
    path: Option<&str>,
583
    lines: Option<&str>,
584
    as_json: bool,
585
) -> Result<i32> {
586
    let repo = open()?;
587
    // Whether the working copy is clean and conflicted: from the manifest
588
    // when it proves the working copy clean, else from a snapshot.
589
    // The working copy as last recorded, without looking at the files (as
590
    // Git's log does not): whether its change holds edits, and whether its
591
    // base was conflicted. `oxy status` is what checks the disk.
592
    let conflicted = !repo.is_at_op() && repo.recorded_conflicted()?;
593
    let listing = oxy_core::timing::phase("log: entries");
594
    let entries = match (path, lines) {
595
        (_, Some(spec)) => {
596
            let (first, last, p) = parse_line_range(spec)?;
597
            let (_, wc) = repo.working_copy()?;
598
            let base = repo.load_state_history(&wc.deps)?.maximal(&wc.deps);
599
            repo.line_history(&base, p, first, last)?
600
        }
601
        (Some(p), None) => repo.log_for_path(p)?,
602
        (None, None) => repo.log()?,
603
    };
604
    drop(listing);
605
    let _print = oxy_core::timing::phase("log: print");
606
    if as_json {
607
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
608
        let mut items = Vec::new();
609
        for e in entries.iter().take(shown) {
610
            items.push(log_entry_json(&repo, e)?);
611
        }
612
        println!(
613
            "{}",
614
            json::obj([
615
                ("bookmark", json::s(&repo.config.bookmark)),
616
                ("total", json::n(entries.len())),
617
                ("changes", json::arr(items))
618
            ])
619
        );
620
        return Ok(0);
621
    }
622
    let total = entries.len();
623
    let shown = limit.unwrap_or(total).min(total);
624
    // Lay out a little past what is shown, so edges into the cut are drawn.
625
    let window: Vec<(ChangeHash, Vec<ChangeHash>)> = entries
626
        .iter()
627
        .take((shown + MAX_EDGE).min(total))
628
        .map(|e| (e.hash, e.change.deps.clone()))
629
        .collect();
630
    let rows = oxy_core::lanes::graph(&window, MAX_EDGE);
631
    // Highlight the shortest prefix that names each change: against the
632
    // whole log, which is what `resolve_change` searches.
633
    let everything;
634
    let all = if path.is_some() || lines.is_some() {
635
        everything = repo.log()?;
636
        &everything
637
    } else {
638
        &entries
639
    };
640
    let id_prefix = unique_prefixes(all.iter().map(|e| e.change.change_id.to_hex()));
641
    let labels = reference_labels(&repo)?;
642
    for (e, row) in entries.iter().take(shown).zip(&rows) {
643
        let c = &e.change;
644
        let bullet = ui::log_bullet(
645
            e.is_working_copy,
646
            e.is_head,
647
            e.is_working_copy && conflicted,
648
        );
649
        let id = c.change_id.to_hex();
650
        let n = id_prefix.get(&id).copied().unwrap_or(8).min(8);
651
        let mut head = vec![format!("{}{}", ui::id(&id[..n]), ui::dim(&id[n..8]))];
652
        head.push(ui::author(author_name(&repo, c)));
653
        head.push(ui::dim(ui::ago(c.hlc.wall_ms)));
654
        if let Some(names) = labels.get(&e.hash) {
655
            head.push(names.join(" "));
656
        }
657
        if c.kind == ChangeKind::Resolution {
658
            head.push(ui::warn("resolution"));
659
        }
660
        if !e.is_working_copy {
661
            head.push(ui::hash(format!("#{}", e.hash.short(8))));
662
            head.push(signature_mark(&repo, &e.hash, Some(c))?);
663
        }
664
        println!("{}{}", node_line(row, &bullet), head.join(" "));
665
        let subject = if e.is_working_copy && c.message.is_empty() {
666
            let edited = repo
667
                .store()
668
                .get_change(&e.hash)
669
                .is_ok_and(|w| !w.tree_ops.is_empty() || !w.edits.is_empty());
670
            ui::dim(if edited {
671
                "(working copy, uncommitted changes)"
672
            } else {
673
                "(working copy)"
674
            })
675
        } else if c.message.trim().is_empty() {
676
            ui::dim("(no description)")
677
        } else {
678
            subject_of(&c.message).to_string()
679
        };
680
        println!("{}{subject}", below_line(row));
681
        if verbose {
682
            let rail = continuation(row);
683
            if !e.is_working_copy {
684
                println!(
685
                    "{rail}{}",
686
                    ui::dim(format!(
687
                        "{} {}",
688
                        when(c.hlc.wall_ms),
689
                        signature_line(&repo, &e.hash)?
690
                    ))
691
                );
692
            }
693
            if !c.deps.is_empty() {
694
                println!(
695
                    "{rail}{} {}",
696
                    ui::dim(ui::glyph("↳", "->")),
697
                    ui::dim(deps_of(&c.deps))
698
                );
699
            }
700
            let body: Vec<&str> = c
701
                .message
702
                .lines()
703
                .skip(1)
704
                .skip_while(|l| l.trim().is_empty())
705
                .collect();
706
            for line in body {
707
                println!("{rail}  {line}");
708
            }
709
        }
710
    }
711
    if shown < total {
712
        if let Some(last) = rows.get(shown.saturating_sub(1)) {
713
            let cut: String = last
714
                .below
715
                .iter()
716
                .map(|c| match c {
717
                    Cell::Blank | Cell::Elided | Cell::JoinRight => "  ",
718
                    _ => "~ ",
719
                })
720
                .collect();
721
            if cut.trim().is_empty() {
722
                println!("{}", ui::dim("~"));
723
            } else {
724
                println!("{}", ui::dim(cut.trim_end()));
725
            }
726
        }
727
        println!(
728
            "{}",
729
            ui::dim(format!(
730
                "{} {} more; pass -n to see them",
731
                ui::glyph("…", "..."),
732
                total - shown
733
            ))
734
        );
735
    }
736
    Ok(0)
737
}
738
739
/// Rows a drawn edge may span in `oxy log`; a longer one is elided (`~`).
740
const MAX_EDGE: usize = 12;
741
742
use oxy_core::hash::ChangeHash;
743
use oxy_core::lanes::{Cell, GraphRow};
744
745
/// A graph cell, two columns wide.
746
fn cell(c: Cell) -> &'static str {
747
    match c {
748
        Cell::Blank => "  ",
749
        Cell::Line => ui::glyph("│ ", "| "),
750
        Cell::Elided => "~ ",
751
        Cell::JoinLeft => ui::glyph("├─", "|-"),
752
        Cell::JoinPass => ui::glyph("──", "--"),
753
        Cell::JoinCross => ui::glyph("┼─", "+-"),
754
        Cell::JoinRight => ui::glyph("╯ ", "' "),
755
    }
756
}
757
758
/// The graph part of a change's own line, its bullet in its column.
759
fn node_line(row: &GraphRow, bullet: &str) -> String {
760
    let width = row
761
        .passing
762
        .iter()
763
        .copied()
764
        .max()
765
        .unwrap_or(0)
766
        .max(row.column)
767
        + 1;
768
    let mut out = String::new();
769
    for c in 0..width {
770
        if c == row.column {
771
            out.push_str(bullet);
772
            out.push(' ');
773
        } else if row.passing.contains(&c) {
774
            out.push_str(&ui::dim(cell(Cell::Line)));
775
        } else {
776
            out.push_str("  ");
777
        }
778
    }
779
    out.push(' ');
780
    out
781
}
782
783
/// The graph part of the line under a change: lanes carrying on, a join,
784
/// or `~` for an elided edge.
785
fn below_line(row: &GraphRow) -> String {
786
    let g: String = row.below.iter().map(|c| cell(*c)).collect();
787
    format!("{} ", ui::dim(g))
788
}
789
790
/// The graph part of any further line of a change (`-v`).
791
fn continuation(row: &GraphRow) -> String {
792
    let g: String = row
793
        .below
794
        .iter()
795
        .map(|c| match c {
796
            Cell::Line | Cell::JoinLeft | Cell::JoinCross => cell(Cell::Line),
797
            _ => "  ",
798
        })
799
        .collect();
800
    format!("{} ", ui::dim(g))
801
}
802
803
/// For each hex ID, the length of its shortest prefix no other ID shares.
804
fn unique_prefixes(ids: impl Iterator<Item = String>) -> std::collections::HashMap<String, usize> {
805
    let mut v: Vec<String> = ids.collect();
806
    v.sort();
807
    v.dedup();
808
    let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
809
    let mut out = std::collections::HashMap::with_capacity(v.len());
810
    for i in 0..v.len() {
811
        let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 };
812
        let after = if i + 1 < v.len() {
813
            common(&v[i], &v[i + 1])
814
        } else {
815
            0
816
        };
817
        out.insert(v[i].clone(), before.max(after) + 1);
818
    }
819
    out
820
}
821
822
/// Bookmark, remote bookmark and tag names to show beside the changes they
823
/// point at. A name is shown on each head of its state; one with more than
824
/// three heads names too much of the log to help, so it is left out (oxy
825
/// bookmark list shows it). A remote bookmark at the same state as the
826
/// local one of that name is not repeated.
827
fn reference_labels(repo: &Repo) -> Result<std::collections::HashMap<ChangeHash, Vec<String>>> {
828
    const MAX_HEADS: usize = 3;
829
    let view = repo.view()?;
830
    let mut out: std::collections::HashMap<ChangeHash, Vec<String>> = Default::default();
831
    let mut add = |heads: Vec<ChangeHash>, label: String| {
832
        if heads.len() <= MAX_HEADS {
833
            for h in heads {
834
                out.entry(h).or_default().push(label.clone());
835
            }
836
        }
837
    };
838
    for (name, st) in &view.bookmarks {
839
        add(repo.store().get_state(st)?.heads, ui::bookmark(name));
840
    }
841
    for (remote, bookmarks) in &view.remotes {
842
        for (name, st) in bookmarks {
843
            if view.bookmarks.get(name) == Some(st) {
844
                continue;
845
            }
846
            add(
847
                repo.store().get_state(st)?.heads,
848
                ui::dim(format!("{remote}/{name}")),
849
            );
850
        }
851
    }
852
    for t in repo.tags()? {
853
        add(t.heads.clone(), ui::warn(&t.name));
854
    }
855
    Ok(out)
856
}
857
858
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
859
    let repo = open()?;
860
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
861
    if as_json {
862
        let files = repo.diff_files(hash.as_ref())?;
863
        let items = files.iter().map(|f| {
864
            json::obj([
865
                ("path", json::s(&f.path)),
866
                ("kind", json::s(&f.kind)),
867
                ("from", json::opt(f.from.as_deref(), json::s)),
868
                (
869
                    "hunks",
870
                    json::arr(f.hunks.iter().map(|h| {
871
                        json::obj([
872
                            ("base_line", json::n(h.base_line)),
873
                            (
874
                                "added",
875
                                json::arr(
876
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
877
                                ),
878
                            ),
879
                            (
880
                                "removed",
881
                                json::arr(h.removed.iter().map(|(n, l)| {
882
                                    json::obj([
883
                                        ("line", json::n(*n)),
884
                                        ("text", json::s(&String::from_utf8_lossy(l))),
885
                                    ])
886
                                })),
887
                            ),
888
                        ])
889
                    })),
890
                ),
891
            ])
892
        });
893
        println!(
894
            "{}",
895
            json::obj([
896
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
897
                ("files", json::arr(items))
898
            ])
899
        );
900
        return Ok(0);
901
    }
902
    match hash {
903
        Some(h) => {
904
            let c = repo.store().get_change(&h)?;
905
            let (base, snapshot) = repo.change_base(&c)?;
906
            print!("{}", render_change(&c, &base, &snapshot));
907
        }
908
        None => {
909
            let (wc, base, snapshot) = repo.working_copy_with_base()?;
910
            let text = {
911
                let _t = oxy_core::timing::phase("diff: render the change");
912
                render_change(&wc, &base, &snapshot)
913
            };
914
            print!("{text}");
915
            // The process ends here: freeing the base's tree and graphs
916
            // one by one would only cost time (about 27 ms on Linux).
917
            std::mem::forget((wc, base, snapshot));
918
        }
919
    }
920
    Ok(0)
921
}
922
923
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
924
    let repo = open()?;
925
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
926
    let bytes = repo.file_at(path, heads.as_deref())?;
927
    use std::io::Write as _;
928
    std::io::stdout().write_all(&bytes)?;
929
    Ok(0)
930
}
931
932
pub fn root(as_json: bool) -> Result<i32> {
933
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
934
        if as_json {
935
            println!("null");
936
        }
937
        return Ok(1);
938
    };
939
    if as_json {
940
        println!(
941
            "{}",
942
            json::obj([
943
                ("root", json::s(&repo.root().to_string_lossy())),
944
                ("workspace", json::s(&repo.workspace().to_hex())),
945
                ("bookmark", json::s(&repo.config.bookmark))
946
            ])
947
        );
948
    } else {
949
        println!("{}", repo.root().display());
950
    }
951
    Ok(0)
952
}
953
954
pub fn version(as_json: bool) -> Result<i32> {
955
    if as_json {
956
        println!(
957
            "{}",
958
            json::obj([
959
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
960
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
961
                ("format", json::n(2))
962
            ])
963
        );
964
    } else {
965
        println!(
966
            "oxy {} (repository format 2, protocol {})",
967
            env!("CARGO_PKG_VERSION"),
968
            oxy_core::protocol::PROTOCOL_VERSION
969
        );
970
    }
971
    Ok(0)
972
}
973
974
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
975
    let repo = open()?;
976
    if paths.is_empty() && hunks.is_empty() {
977
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
978
    }
979
    let mut n = 0;
980
    if !hunks.is_empty() {
981
        n += repo.discard_hunks(hunks)?;
982
    }
983
    if !paths.is_empty() {
984
        n += repo.discard(paths)?;
985
    }
986
    println!(
987
        "{} {} restored to the working copy's base",
988
        ui::done("Discarded"),
989
        plural(n, "path")
990
    );
991
    Ok(0)
992
}
993
994
pub fn hunks(as_json: bool) -> Result<i32> {
995
    let repo = open()?;
996
    let (_, hunks) = repo.hunks()?;
997
    if as_json {
998
        println!(
999
            "{}",
1000
            json::arr(hunks.iter().map(|h| json::obj([
1001
                ("index", json::n(h.index)),
1002
                ("path", json::s(&h.path)),
1003
                ("text", json::s(&h.text))
1004
            ])))
1005
        );
1006
        return Ok(0);
1007
    }
1008
    if hunks.is_empty() {
1009
        println!(
1010
            "{}",
1011
            ui::dim("No hunks: the working copy matches its base.")
1012
        );
1013
    }
1014
    for h in &hunks {
1015
        println!(
1016
            "{} {}",
1017
            ui::section(format!("hunk {}", h.index)),
1018
            ui::path(&h.path)
1019
        );
1020
        for line in h.text.lines() {
1021
            let styled = if line.starts_with('+') {
1022
                ui::ok(line)
1023
            } else if line.starts_with('-') {
1024
                ui::err(line)
1025
            } else {
1026
                ui::dim(line)
1027
            };
1028
            println!("  {styled}");
1029
        }
1030
    }
1031
    Ok(0)
1032
}
1033
1034
pub fn show(change: &str, as_json: bool) -> Result<i32> {
1035
    let repo = open()?;
1036
    repo.snapshot_status("oxy show")?;
1037
    let h = repo.resolve_change(change)?;
1038
    let c = repo.store().get_change(&h)?;
1039
    if as_json {
1040
        let files = repo.diff_files(Some(&h))?;
1041
        let heads = repo.bookmark_heads()?;
1042
        let entry = oxy_core::repo::LogEntry {
1043
            hash: h,
1044
            change: oxy_core::state::ChangeMeta::of(&c),
1045
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
1046
            is_head: heads.contains(&h),
1047
        };
1048
        let mut body = log_entry_json(&repo, &entry)?;
1049
        body.pop();
1050
        body.push_str(&format!(
1051
            ",{}:{}}}",
1052
            json::s("files"),
1053
            json::arr(files.iter().map(|f| json::obj([
1054
                ("path", json::s(&f.path)),
1055
                ("kind", json::s(&f.kind)),
1056
                ("from", json::opt(f.from.as_deref(), json::s))
1057
            ])))
1058
        ));
1059
        println!("{body}");
1060
        return Ok(0);
1061
    }
1062
    println!(
1063
        "{} {} {}",
1064
        ui::section("change"),
1065
        ui::id(short_id(&c)),
1066
        ui::hash(format!("#{h}"))
1067
    );
1068
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1069
    // Fetched but not pulled (oxygen#56): say where it is.
1070
    if let Some(at) = repo.remote_only_location(&h)? {
1071
        println!(
1072
            "{}",
1073
            ui::kv(
1074
                "only in",
1075
                ui::warn(format!(
1076
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
1077
                ))
1078
            )
1079
        );
1080
    }
1081
    println!(
1082
        "{}",
1083
        ui::kv(
1084
            "author",
1085
            ui::author(author_name(&repo, &oxy_core::state::ChangeMeta::of(&c)))
1086
        )
1087
    );
1088
    println!(
1089
        "{}",
1090
        ui::kv(
1091
            "date",
1092
            format!(
1093
                "{} {}",
1094
                when(c.hlc.wall_ms),
1095
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1096
            )
1097
        )
1098
    );
1099
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
1100
    println!("{}", ui::kv("sig", signature_line(&repo, &h)?));
1101
    println!();
1102
    for line in (if c.message.is_empty() {
1103
        "(no description)"
1104
    } else {
1105
        &c.message
1106
    })
1107
    .lines()
1108
    {
1109
        println!("    {line}");
1110
    }
1111
    println!();
1112
    print!("{}", repo.describe_change(&h)?);
1113
    Ok(0)
1114
}
1115
1116
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
1117
    let repo = open()?;
1118
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1119
    // BRANCH` is: checking its files out under another bookmark's name
1120
    // made the next commit move the wrong bookmark (oxygen#60).
1121
    if let [name] = changes {
1122
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
1123
            drop(repo);
1124
            return bookmark_switch(name, discard, carry);
1125
        }
1126
    }
1127
    let heads = if changes.is_empty() {
1128
        repo.bookmark_heads()?
1129
    } else {
1130
        let mut heads = Vec::new();
1131
        for c in changes {
1132
            heads.extend(repo.resolve_heads(c)?);
1133
        }
1134
        heads
1135
    };
1136
    let spec = if changes.is_empty() {
1137
        repo.config.bookmark.clone()
1138
    } else {
1139
        changes.join(" ")
1140
    };
1141
    let sp = ui::spinner(&format!("Checking out {spec}…"));
1142
    let command = format!("oxy checkout {spec}");
1143
    let (r, carried) = if carry {
1144
        repo.checkout_carry(&heads, &spec, &command)?
1145
    } else {
1146
        (repo.checkout(&heads, discard, &command)?, vec![])
1147
    };
1148
    sp.done(&format!(
1149
        "{} on {}: {} written, {} removed{}",
1150
        ui::done("Working copy"),
1151
        ui::bookmark(&spec),
1152
        plural(r.written, "file"),
1153
        r.removed,
1154
        if carried.is_empty() {
1155
            String::new()
1156
        } else {
1157
            format!("; carried {}", plural(carried.len(), "changed path"))
1158
        }
1159
    ));
1160
    for n in &r.notes {
1161
        println!("  {} {n}", ui::note());
1162
    }
1163
    if r.conflicted {
1164
        println!(
1165
            "  {} {}",
1166
            ui::caution(),
1167
            ui::warn("this state has conflicts; see oxy status")
1168
        );
1169
    }
1170
    where_now(&repo);
1171
    Ok(0)
1172
}
1173
1174
pub fn resolve(as_json: bool) -> Result<i32> {
1175
    let repo = open()?;
1176
    let snap = repo.snapshot("oxy resolve")?;
1177
    if as_json {
1178
        println!("{}", repo.status_json(&snap)?);
1179
        return Ok(if snap.base_snapshot.is_conflicted() {
1180
            2
1181
        } else {
1182
            0
1183
        });
1184
    }
1185
    if !snap.base_snapshot.is_conflicted() {
1186
        println!("The working copy's base has no conflicts.");
1187
        return Ok(0);
1188
    }
1189
    let mut remaining = 0;
1190
    for (p, f) in &snap.base_snapshot.files {
1191
        if !f.is_conflicted() {
1192
            continue;
1193
        }
1194
        match snap
1195
            .statuses
1196
            .iter()
1197
            .find(|s| s.path == *p)
1198
            .map(|s| s.status)
1199
        {
1200
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
1201
            Some(ChangeStatus::ConflictEdited) => {
1202
                remaining += 1;
1203
                println!("markers    {p}");
1204
            }
1205
            _ => {
1206
                remaining += 1;
1207
                println!("unresolved {p}");
1208
            }
1209
        }
1210
    }
1211
    for c in &snap.base_snapshot.tree.conflicts {
1212
        remaining += 1;
1213
        println!("tree       {c:?}");
1214
    }
1215
    if remaining == 0 {
1216
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
1217
        Ok(0)
1218
    } else {
1219
        Ok(2)
1220
    }
1221
}
1222
1223
pub fn undo() -> Result<i32> {
1224
    let repo = open()?;
1225
    let op = repo.undo()?;
1226
    println!("{} now at: {}", ui::done("Undone;"), ui::dim(&op.command));
1227
    where_now(&repo);
1228
    Ok(0)
1229
}
1230
1231
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
1232
    let repo = open()?;
1233
    let ops = repo.op_log()?;
1234
    // What each operation changed, against the one before it.
1235
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
1236
        match ops.get(i + 1) {
1237
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
1238
            None => Ok(vec![]),
1239
        }
1240
    };
1241
    if as_json {
1242
        let mut items = Vec::new();
1243
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
1244
            let summary: Vec<String> = changes_of(i)?
1245
                .iter()
1246
                .map(|c| change_words(&repo, c))
1247
                .collect();
1248
            items.push(json::obj([
1249
                ("id", json::s(&r.to_hex())),
1250
                ("when_ms", json::n(op.hlc.wall_ms)),
1251
                ("command", json::s(&op.command)),
1252
                ("snapshot", json::b(op.is_snapshot())),
1253
                ("current", json::b(i == 0)),
1254
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1255
            ]));
1256
        }
1257
        println!("{}", json::arr(items));
1258
        return Ok(0);
1259
    }
1260
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
1261
    let id = |r: &oxy_core::hash::ObjectRef| {
1262
        let hex = r.to_hex();
1263
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
1264
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
1265
    };
1266
    let rail = ui::dim(ui::glyph("│", "|"));
1267
    let (mut i, mut shown) = (0, 0);
1268
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
1269
        let (r, op) = &ops[i];
1270
        let bullet = if i == 0 {
1271
            ui::ok(ui::glyph("@", "@"))
1272
        } else {
1273
            ui::dim(ui::glyph("○", "o"))
1274
        };
1275
        // A run of snapshots folds into one entry.
1276
        let mut run = 1;
1277
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
1278
            run += 1;
1279
        }
1280
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
1281
        if op.is_snapshot() {
1282
            let span = if run > 1 {
1283
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1284
            } else {
1285
                String::new()
1286
            };
1287
            println!(
1288
                "{bullet}  {}{} {when}",
1289
                id(r),
1290
                if span.is_empty() {
1291
                    String::new()
1292
                } else {
1293
                    format!(" {span}")
1294
                }
1295
            );
1296
            println!(
1297
                "{rail}  {}",
1298
                ui::dim(if run == 1 {
1299
                    "working-copy snapshot".to_string()
1300
                } else {
1301
                    format!("{run} working-copy snapshots")
1302
                })
1303
            );
1304
        } else {
1305
            println!("{bullet}  {} {when}", id(r));
1306
            let words: Vec<String> = changes_of(i)?
1307
                .iter()
1308
                .map(|c| change_words(&repo, c))
1309
                .collect();
1310
            let summary = if words.is_empty() {
1311
                if i + 1 == ops.len() {
1312
                    "created the repository".to_string()
1313
                } else {
1314
                    "no bookmark or working-copy change".to_string()
1315
                }
1316
            } else {
1317
                words.join("; ")
1318
            };
1319
            println!(
1320
                "{rail}  {}",
1321
                if i == 0 {
1322
                    ui::subject(&summary)
1323
                } else {
1324
                    summary
1325
                }
1326
            );
1327
            let cmd = op.command.lines().next().unwrap_or("");
1328
            let cmd: String = cmd.chars().take(100).collect();
1329
            println!("{rail}  {}", ui::dim(cmd));
1330
        }
1331
        i += run;
1332
        shown += 1;
1333
    }
1334
    if i < ops.len() {
1335
        println!(
1336
            "{}",
1337
            ui::dim(format!(
1338
                "{} {} older; pass -n to see more",
1339
                ui::glyph("…", "..."),
1340
                plural(ops.len() - i, "operation")
1341
            ))
1342
        );
1343
    }
1344
    Ok(0)
1345
}
1346
1347
/// One change an operation made, in words.
1348
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1349
    use oxy_core::repo::ViewChange::*;
1350
    match c {
1351
        BookmarkCreated { name, heads } => {
1352
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1353
        }
1354
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
1355
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
1356
        BookmarkMoved { name, from, to } => format!(
1357
            "{name}: {from} {} {}",
1358
            ui::glyph("→", "->"),
1359
            plural(*to, "head")
1360
        ),
1361
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
1362
        TagCreated { name } => format!("tagged {name}"),
1363
        TagDeleted { name } => format!("removed tag {name}"),
1364
        Policy => "trust policy changed".to_string(),
1365
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
1366
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
1367
            Err(_) => "working copy moved".to_string(),
1368
        },
1369
    }
1370
}
1371
1372
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
1373
    let repo = open()?;
1374
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
1375
    let r = repo.op_restore(op, discard)?;
1376
    sp.done(&format!(
1377
        "{} to operation {} {}",
1378
        ui::done("Restored"),
1379
        ui::hash(r.op.short(12)),
1380
        ui::dim(r.command.lines().next().unwrap_or(""))
1381
    ));
1382
    println!(
1383
        "  {} {}",
1384
        ui::note(),
1385
        ui::dim(format!(
1386
            "{} written, {} removed; oxy undo goes back again",
1387
            plural(r.checkout.written, "file"),
1388
            r.checkout.removed
1389
        ))
1390
    );
1391
    where_now(&repo);
1392
    Ok(0)
1393
}
1394
1395
pub fn op_revert(op: &str) -> Result<i32> {
1396
    let repo = open()?;
1397
    let r = repo.op_revert(op)?;
1398
    let view = repo.view()?;
1399
    let names: Vec<String> = r
1400
        .reverted
1401
        .iter()
1402
        .map(|n| {
1403
            if view.bookmarks.contains_key(n) {
1404
                ui::bookmark(n)
1405
            } else {
1406
                format!("{} (removed)", ui::bookmark(n))
1407
            }
1408
        })
1409
        .collect();
1410
    println!(
1411
        "{} operation {} {}",
1412
        ui::done("Reverted"),
1413
        ui::hash(r.op.short(12)),
1414
        ui::dim(r.command.lines().next().unwrap_or(""))
1415
    );
1416
    println!(
1417
        "  {} {}",
1418
        ui::note(),
1419
        ui::dim(format!("as before it: {}", names.join(", ")))
1420
    );
1421
    if !r.kept.is_empty() {
1422
        println!(
1423
            "  {} {}",
1424
            ui::caution(),
1425
            ui::warn(format!(
1426
                "left as they are, having moved again since: {}",
1427
                r.kept.join(", ")
1428
            ))
1429
        );
1430
    }
1431
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
1432
        println!(
1433
            "  {} {}",
1434
            ui::note(),
1435
            ui::dim("the working copy has work of its own: oxy checkout to move it")
1436
        );
1437
    }
1438
    where_now(&repo);
1439
    Ok(0)
1440
}
1441
1442
/// Where the working copy and bookmark are now, after a command moved
1443
/// them (as jj says "Working copy now at").
1444
pub fn where_now(repo: &Repo) {
1445
    let Ok((_, wc)) = repo.working_copy() else {
1446
        return;
1447
    };
1448
    let heads = repo.bookmark_heads().unwrap_or_default();
1449
    let newest = heads
1450
        .iter()
1451
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
1452
        .max_by_key(|(m, _)| m.hlc);
1453
    println!(
1454
        "  {} {}",
1455
        ui::dim(format!("{:<13}", "Working copy")),
1456
        ui::id(wc.change_id.short(8))
1457
    );
1458
    let tail = match newest {
1459
        Some((m, _)) => format!(
1460
            ", newest {} {}",
1461
            ui::id(m.change_id.short(8)),
1462
            subject_of(&m.message)
1463
        ),
1464
        None => String::new(),
1465
    };
1466
    println!(
1467
        "  {} {}: {}{tail}",
1468
        ui::dim(format!("{:<13}", "Bookmark")),
1469
        ui::bookmark(&repo.config.bookmark),
1470
        plural(heads.len(), "head")
1471
    );
1472
}
1473
1474
pub fn gc(now: bool) -> Result<i32> {
1475
    let repo = open()?;
1476
    let sp = ui::spinner("Packing and pruning…");
1477
    let r = repo.gc(now)?;
1478
    sp.clear();
1479
    if r.packed.objects > 0 {
1480
        println!(
1481
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
1482
            plural(r.packed.objects, "object"),
1483
            r.packed.raw_bytes,
1484
            r.packed.packed_bytes,
1485
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
1486
        );
1487
    }
1488
    println!(
1489
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
1490
        plural(r.reachable, "object"),
1491
        plural(r.pruned.objects, "unreachable object"),
1492
        r.pruned.bytes,
1493
        if r.pruned.deferred > 0 {
1494
            format!(
1495
                "; {} deferred by the grace period (use --now)",
1496
                plural(r.pruned.deferred, "object")
1497
            )
1498
        } else {
1499
            String::new()
1500
        },
1501
        if r.merged_packs > 0 {
1502
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1503
        } else {
1504
            String::new()
1505
        },
1506
        plural(repo.store().pack_count(), "pack")
1507
    );
1508
    Ok(0)
1509
}
1510
1511
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
1512
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1513
    use oxy_core::repo::Health;
1514
    let repo = open()?;
1515
    let sp = ui::spinner(if offline {
1516
        "Checking…"
1517
    } else {
1518
        "Checking, and contacting remotes…"
1519
    });
1520
    let r = repo.doctor(!offline);
1521
    sp.clear();
1522
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
1523
    let word = |h: Health| match h {
1524
        Health::Ok => "ok",
1525
        Health::Warn => "warning",
1526
        Health::Fail => "fail",
1527
    };
1528
    if as_json {
1529
        let checks: Vec<String> = r
1530
            .checks
1531
            .iter()
1532
            .map(|c| {
1533
                json::obj([
1534
                    ("area", json::s(&c.area)),
1535
                    ("health", json::s(word(c.health))),
1536
                    ("message", json::s(&c.message)),
1537
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
1538
                ])
1539
            })
1540
            .collect();
1541
        println!(
1542
            "{}",
1543
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1544
        );
1545
        return Ok(code);
1546
    }
1547
    let mut last = "";
1548
    for c in &r.checks {
1549
        if c.area != last {
1550
            println!("{}", ui::section(&c.area));
1551
            last = &c.area;
1552
        }
1553
        let mark = match c.health {
1554
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
1555
            Health::Warn => ui::caution(),
1556
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1557
        };
1558
        println!("  {mark} {}", c.message);
1559
        if let Some(h) = &c.hint {
1560
            println!("    {} {}", ui::dim("→"), ui::dim(h));
1561
        }
1562
    }
1563
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
1564
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
1565
    if fails + warns == 0 {
1566
        println!("{}", ui::done("Everything looks right."));
1567
    } else {
1568
        println!(
1569
            "{} {}, {}.",
1570
            if fails > 0 {
1571
                ui::err(ui::glyph("✖", "x"))
1572
            } else {
1573
                ui::caution()
1574
            },
1575
            plural(fails, "problem"),
1576
            plural(warns, "warning")
1577
        );
1578
    }
1579
    Ok(code)
1580
}
1581
1582
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
1583
pub fn fsck(as_json: bool) -> Result<i32> {
1584
    use oxy_core::repo::Severity;
1585
    let repo = open()?;
1586
    let sp = ui::spinner("Checking every object…");
1587
    let r = repo.fsck()?;
1588
    sp.clear();
1589
    let code = if r.errors() > 0 { 1 } else { 0 };
1590
    if as_json {
1591
        let problems: Vec<String> = r
1592
            .problems
1593
            .iter()
1594
            .map(|p| {
1595
                json::obj([
1596
                    (
1597
                        "severity",
1598
                        json::s(match p.severity {
1599
                            Severity::Error => "error",
1600
                            Severity::Warning => "warning",
1601
                        }),
1602
                    ),
1603
                    (
1604
                        "object",
1605
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1606
                    ),
1607
                    ("what", json::s(&p.what)),
1608
                ])
1609
            })
1610
            .collect();
1611
        println!(
1612
            "{}",
1613
            json::obj([
1614
                ("ok", json::b(code == 0)),
1615
                ("objects", json::n(r.objects)),
1616
                ("ops", json::n(r.ops)),
1617
                ("changes", json::n(r.changes)),
1618
                ("signed", json::n(r.signed)),
1619
                ("unsigned", json::n(r.unsigned)),
1620
                ("checkpoints", json::n(r.checkpoints)),
1621
                ("attestations", json::n(r.attestations)),
1622
                ("errors", json::n(r.errors())),
1623
                ("warnings", json::n(r.warnings())),
1624
                ("problems", json::arr(problems)),
1625
            ])
1626
        );
1627
        return Ok(code);
1628
    }
1629
    println!(
1630
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
1631
        plural(r.objects, "object"),
1632
        plural(r.ops, "operation"),
1633
        plural(r.changes, "change"),
1634
        r.signed,
1635
        r.unsigned,
1636
        plural(r.checkpoints, "checkpoint"),
1637
        plural(r.attestations, "attestation"),
1638
    );
1639
    for p in &r.problems {
1640
        let obj = p
1641
            .object
1642
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
1643
            .unwrap_or_default();
1644
        match p.severity {
1645
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
1646
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1647
        }
1648
    }
1649
    if r.problems.is_empty() {
1650
        println!("{}", ui::done("No problems found."));
1651
    } else if code == 0 {
1652
        println!(
1653
            "{}",
1654
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
1655
        );
1656
    } else {
1657
        println!(
1658
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
1659
            ui::err(ui::glyph("✖", "x")),
1660
            plural(r.errors(), "error"),
1661
            plural(r.warnings(), "warning")
1662
        );
1663
    }
1664
    Ok(code)
1665
}
1666
1667
/// The head the working copy sits on, for commands that default to it. With
1668
/// several heads beneath the working copy, the most recently made one is
1669
/// chosen and announced.
1670
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
1671
    let snap = repo.snapshot_status("oxy")?;
1672
    let base = snap.base.maximal(&snap.wc.deps);
1673
    match base.as_slice() {
1674
        [] => anyhow::bail!("the working copy sits on no change yet"),
1675
        [h] => Ok(*h),
1676
        many => {
1677
            let latest = many
1678
                .iter()
1679
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
1680
                .copied()
1681
                .unwrap();
1682
            let c = repo.store().get_change(&latest)?;
1683
            println!(
1684
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
1685
                short_id(&c),
1686
                latest.short(12),
1687
                many.len()
1688
            );
1689
            Ok(latest)
1690
        }
1691
    }
1692
}
1693
1694
/// `oxy describe` without -m: the working copy's name for a build.
1695
pub fn describe_name(as_json: bool) -> Result<i32> {
1696
    let repo = open()?;
1697
    let d = repo.describe_working_copy()?;
1698
    if as_json {
1699
        println!(
1700
            "{}",
1701
            json::obj([
1702
                ("describe", json::s(&d.line())),
1703
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
1704
                ("distance", json::n(d.distance)),
1705
                ("bookmark", json::s(&d.bookmark)),
1706
                ("change", json::s(&d.change.to_hex())),
1707
                ("hash", json::s(&d.hash.to_hex())),
1708
                ("dirty", json::b(d.dirty)),
1709
            ])
1710
        );
1711
    } else {
1712
        println!("{}", d.line());
1713
    }
1714
    Ok(0)
1715
}
1716
1717
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
1718
    let repo = open()?;
1719
    let h = match change {
1720
        Some(c) => repo.resolve_change(c)?,
1721
        None => current_head(&repo)?,
1722
    };
1723
    let new = repo.describe(&h, message)?;
1724
    let c = repo.store().get_change(&new)?;
1725
    println!(
1726
        "{} {} {}  {}",
1727
        ui::done("Described"),
1728
        ui::id(short_id(&c)),
1729
        ui::hash(format!("#{}", new.short(12))),
1730
        ui::subject(subject_of(message))
1731
    );
1732
    Ok(0)
1733
}
1734
1735
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
1736
    let repo = open()?;
1737
    let new = match into {
1738
        Some(spec) => {
1739
            let target = repo.resolve_change(spec)?;
1740
            repo.amend_into(&target, message)?
1741
        }
1742
        None => repo.amend(message)?,
1743
    };
1744
    let c = repo.store().get_change(&new)?;
1745
    println!(
1746
        "{} {} {}  {}",
1747
        ui::done("Amended"),
1748
        ui::id(short_id(&c)),
1749
        ui::hash(format!("#{}", new.short(12))),
1750
        ui::subject(subject_of(&c.message))
1751
    );
1752
    where_now(&repo);
1753
    Ok(0)
1754
}
1755
1756
pub fn abandon(change: &str) -> Result<i32> {
1757
    let repo = open()?;
1758
    let h = repo.resolve_change(change)?;
1759
    let c = repo.store().get_change(&h)?;
1760
    let notes = repo.abandon(&h)?;
1761
    println!(
1762
        "{} {} {}  {}",
1763
        ui::done("Abandoned"),
1764
        ui::id(short_id(&c)),
1765
        ui::hash(format!("#{}", h.short(12))),
1766
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
1767
    );
1768
    for n in notes {
1769
        println!("  {} {n}", ui::note());
1770
    }
1771
    where_now(&repo);
1772
    Ok(0)
1773
}
1774
1775
pub fn checkpoint() -> Result<i32> {
1776
    let repo = open()?;
1777
    let sp = ui::spinner("Writing checkpoint…");
1778
    let (r, changes, bytes) = repo.checkpoint()?;
1779
    sp.done(&format!(
1780
        "{} {} of {} ({} bytes) for {}",
1781
        ui::done("Checkpoint"),
1782
        ui::hash(format!("#{}", r.short(12))),
1783
        plural(changes, "change"),
1784
        bytes,
1785
        ui::id(&repo.config.bookmark)
1786
    ));
1787
    Ok(0)
1788
}
1789
1790
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
1791
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
1792
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
1793
        return Ok(1);
1794
    };
1795
    let info = repo.quick_status()?;
1796
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
1797
        oxy_core::repo::GLYPH_PROMPT_FORMAT
1798
    } else {
1799
        format
1800
    };
1801
    let line = match color {
1802
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
1803
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
1804
        Some(_) => info.format_colored(fmt, ("", "")),
1805
        None => info.format(fmt),
1806
    };
1807
    println!("{line}");
1808
    Ok(0)
1809
}
1810
1811
pub fn sparse(paths: &[String]) -> Result<i32> {
1812
    let mut repo = open()?;
1813
    if paths.is_empty() {
1814
        if repo.config.sparse_paths.is_empty() {
1815
            println!("No sparse filter: the whole tree is materialized.");
1816
        } else {
1817
            println!("{}", ui::heading("Sparse filter"));
1818
            for p in &repo.config.sparse_paths {
1819
                println!("  {}", ui::path(p));
1820
            }
1821
        }
1822
        return Ok(0);
1823
    }
1824
    let snap = repo.snapshot("oxy sparse")?;
1825
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
1826
        anyhow::bail!(
1827
            "the working copy has changes; commit them before changing the sparse filter"
1828
        );
1829
    }
1830
    repo.config.set("filter.paths", &paths.join(","))?;
1831
    repo.save_config()?;
1832
    let heads = repo.bookmark_heads()?;
1833
    let sp = ui::spinner("Re-checking out with the new filter…");
1834
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
1835
    sp.done(&format!(
1836
        "{} {}: {} written, {} removed",
1837
        ui::done("Sparse filter set to"),
1838
        ui::path(paths.join(",")),
1839
        plural(r.written, "file"),
1840
        r.removed
1841
    ));
1842
    Ok(0)
1843
}
1844
1845
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
1846
    let repo = open()?;
1847
    repo.snapshot_status("oxy tag")?;
1848
    let heads = if changes.is_empty() {
1849
        repo.bookmark_heads()?
1850
    } else {
1851
        let mut heads = Vec::new();
1852
        for c in changes {
1853
            heads.extend(repo.resolve_heads(c)?);
1854
        }
1855
        heads
1856
    };
1857
    let t = repo.tag_create(name, &heads, message)?;
1858
    println!(
1859
        "{} {} {} {} ({}){}",
1860
        ui::done("Tagged"),
1861
        ui::bookmark(&t.name),
1862
        ui::dim(ui::glyph("→", "->")),
1863
        ui::hash(format!("#{}", t.state.short(12))),
1864
        plural(t.heads.len(), "head"),
1865
        t.signer
1866
            .map(|s| format!(", signed by {s}"))
1867
            .unwrap_or_else(|| ui::dim(", unsigned"))
1868
    );
1869
    Ok(0)
1870
}
1871
1872
pub fn tag_list(as_json: bool) -> Result<i32> {
1873
    let repo = open()?;
1874
    let tags = repo.tags()?;
1875
    if as_json {
1876
        println!(
1877
            "{}",
1878
            json::arr(tags.iter().map(|t| {
1879
                json::obj([
1880
                    ("name", json::s(&t.name)),
1881
                    ("state", json::s(&t.state.to_hex())),
1882
                    ("heads", json::hashes(&t.heads)),
1883
                    ("message", json::s(&t.message)),
1884
                    (
1885
                        "signer",
1886
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
1887
                    ),
1888
                ])
1889
            }))
1890
        );
1891
        return Ok(0);
1892
    }
1893
    if tags.is_empty() {
1894
        println!("{}", ui::dim("No tags."));
1895
    }
1896
    for t in tags {
1897
        println!(
1898
            "{} {} {}{}{}{}",
1899
            ui::ok(ui::glyph("⚑", "#")),
1900
            ui::bookmark(&t.name),
1901
            // The heads, as `oxy log` shows changes, not the state hash.
1902
            ui::hash(
1903
                t.heads
1904
                    .iter()
1905
                    .map(|h| format!("#{}", h.short(12)))
1906
                    .collect::<Vec<_>>()
1907
                    .join(" ")
1908
            ),
1909
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
1910
            if t.message.is_empty() {
1911
                String::new()
1912
            } else {
1913
                format!("  {}", ui::subject(subject_of(&t.message)))
1914
            },
1915
            t.signer
1916
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
1917
                .unwrap_or_default()
1918
        );
1919
    }
1920
    Ok(0)
1921
}
1922
1923
/// Whether `name` is a bookmark, here or only on a remote: what checkout
1924
/// and workspace add take as "be on this bookmark" (oxygen#60).
1925
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
1926
    Ok(repo.view()?.bookmarks.contains_key(name)
1927
        || repo
1928
            .remote_only_bookmarks()?
1929
            .iter()
1930
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
1931
}
1932
1933
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
1934
    let repo = open()?;
1935
    // One bookmark named: the new workspace is on it (oxygen#60), not on
1936
    // this workspace's bookmark with that one's files.
1937
    if let [name] = changes {
1938
        if names_bookmark(&repo, name)? {
1939
            let (local, _) = repo.local_bookmark_for(name)?;
1940
            let heads = repo.resolve_heads(&local)?;
1941
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
1942
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
1943
            sp.done(&format!(
1944
                "{} {} (workspace {}) on {}",
1945
                ui::done("Workspace created at"),
1946
                ui::path(ws.root().display()),
1947
                ui::id(ws.workspace().short(8)),
1948
                ui::bookmark(&local)
1949
            ));
1950
            return Ok(0);
1951
        }
1952
    }
1953
    let heads = if changes.is_empty() {
1954
        None
1955
    } else {
1956
        let mut heads = Vec::new();
1957
        for c in changes {
1958
            heads.extend(repo.resolve_heads(c)?);
1959
        }
1960
        Some(heads)
1961
    };
1962
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
1963
    let ws = repo.workspace_add(path, heads.as_deref())?;
1964
    sp.done(&format!(
1965
        "{} {} (workspace {})",
1966
        ui::done("Workspace created at"),
1967
        ui::path(ws.root().display()),
1968
        ui::id(ws.workspace().short(8))
1969
    ));
1970
    Ok(0)
1971
}
1972
1973
pub fn workspace_list(as_json: bool) -> Result<i32> {
1974
    let repo = open()?;
1975
    if as_json {
1976
        println!(
1977
            "{}",
1978
            json::arr(repo.workspaces()?.iter().map(|w| {
1979
                json::obj([
1980
                    ("id", json::s(&w.id.to_hex())),
1981
                    ("path", json::s(&w.path.to_string_lossy())),
1982
                    ("current", json::b(w.current)),
1983
                    (
1984
                        "working_copy",
1985
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
1986
                    ),
1987
                ])
1988
            }))
1989
        );
1990
        return Ok(0);
1991
    }
1992
    for w in repo.workspaces()? {
1993
        println!(
1994
            "{} {} {}{}",
1995
            if w.current {
1996
                ui::ok(ui::glyph("●", "*"))
1997
            } else {
1998
                ui::dim(ui::glyph("○", "o"))
1999
            },
2000
            ui::id(w.id.short(8)),
2001
            ui::path(w.path.display()),
2002
            w.working_copy
2003
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
2004
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2005
        );
2006
    }
2007
    Ok(0)
2008
}
2009
2010
pub fn workspace_forget(spec: &str) -> Result<i32> {
2011
    let repo = open()?;
2012
    let all = repo.workspaces()?;
2013
    let target = std::fs::canonicalize(spec).ok();
2014
    let matches: Vec<_> = all
2015
        .iter()
2016
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
2017
        .collect();
2018
    let w = match matches.as_slice() {
2019
        [w] => *w,
2020
        [] => anyhow::bail!("no workspace matches {spec:?}"),
2021
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2022
    };
2023
    repo.workspace_forget(&w.id)?;
2024
    println!(
2025
        "{} workspace {} at {}; its files were left in place.",
2026
        ui::done("Forgot"),
2027
        ui::id(w.id.short(8)),
2028
        ui::path(w.path.display())
2029
    );
2030
    Ok(0)
2031
}
2032
2033
pub fn lock(path: &str) -> Result<i32> {
2034
    let repo = open()?;
2035
    repo.lock_path(path)?;
2036
    println!(
2037
        "{} {} {}",
2038
        ui::done("Locked"),
2039
        ui::path(path),
2040
        ui::dim("(advisory, local)")
2041
    );
2042
    Ok(0)
2043
}
2044
2045
pub fn unlock(path: &str) -> Result<i32> {
2046
    let repo = open()?;
2047
    repo.unlock_path(path)?;
2048
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
2049
    Ok(0)
2050
}
2051
2052
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
2053
    let repo = open()?;
2054
    let h = repo.resolve_change(change)?;
2055
    let (h1, h2) = repo.split(&h, paths)?;
2056
    let c1 = repo.store().get_change(&h1)?;
2057
    let c2 = repo.store().get_change(&h2)?;
2058
    println!(
2059
        "{} into {} {} and {} {}",
2060
        ui::done("Split"),
2061
        ui::id(short_id(&c1)),
2062
        ui::hash(format!("#{}", h1.short(12))),
2063
        ui::id(short_id(&c2)),
2064
        ui::hash(format!("#{}", h2.short(12)))
2065
    );
2066
    Ok(0)
2067
}
2068
2069
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
2070
    let mut heads = Vec::new();
2071
    for c in changes {
2072
        heads.extend(repo.resolve_heads(c)?);
2073
    }
2074
    Ok(heads)
2075
}
2076
2077
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
2078
    let repo = open()?;
2079
    repo.snapshot_status("oxy bookmark create")?;
2080
    let heads = if changes.is_empty() {
2081
        None
2082
    } else {
2083
        let named = heads_from(&repo, changes)?;
2084
        let (_, wc) = repo.working_copy()?;
2085
        let gap = repo.state_gap(&wc.deps, &named)?;
2086
        if upto {
2087
            Some(gap.upto)
2088
        } else if only || gap.earlier.is_empty() {
2089
            Some(named)
2090
        } else {
2091
            anyhow::bail!(
2092
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2093
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2094
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2095
                 or --only for just {0} and what it depends on.",
2096
                changes.join(" "),
2097
                plural(gap.earlier.len(), "change"),
2098
                listed_changes(&repo, &gap.earlier)
2099
            );
2100
        }
2101
    };
2102
    let heads = repo.bookmark_create(name, heads.as_deref())?;
2103
    println!(
2104
        "{} bookmark {} {} {}",
2105
        ui::done("Created"),
2106
        ui::bookmark(name),
2107
        ui::dim(ui::glyph("→", "->")),
2108
        ui::dim(plural(heads.len(), "head"))
2109
    );
2110
    println!(
2111
        "  {} {}",
2112
        ui::note(),
2113
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2114
    );
2115
    Ok(0)
2116
}
2117
2118
/// Up to five changes, newest last, as `  #hash subject` lines.
2119
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
2120
    let shown = changes.len().min(5);
2121
    let mut lines: Vec<String> = changes[changes.len() - shown..]
2122
        .iter()
2123
        .map(|h| {
2124
            let subject = repo
2125
                .store()
2126
                .get_change(h)
2127
                .map(|c| subject_of(&c.message).to_string())
2128
                .unwrap_or_default();
2129
            format!("  #{} {subject}", h.short(12))
2130
        })
2131
        .collect();
2132
    if changes.len() > shown {
2133
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
2134
    }
2135
    lines.join("\n")
2136
}
2137
2138
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
2139
    let repo = open()?;
2140
    repo.snapshot_status("oxy bookmark set")?;
2141
    let named = heads_from(&repo, changes)?;
2142
    // What the bookmark holds now and the new heads would leave out.
2143
    let current = repo
2144
        .bookmarks()?
2145
        .into_iter()
2146
        .find(|b| b.name == name)
2147
        .map(|b| b.heads)
2148
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
2149
    let gap = repo.state_gap(&current, &named)?;
2150
    let heads = if upto {
2151
        gap.upto
2152
    } else if only || gap.earlier.is_empty() {
2153
        named
2154
    } else {
2155
        anyhow::bail!(
2156
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2157
             A state is its heads and what they depend on, not everything recorded before them.\n\
2158
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2159
             or --only for just {0} and what it depends on.",
2160
            changes.join(" "),
2161
            plural(gap.earlier.len(), "change"),
2162
            listed_changes(&repo, &gap.earlier)
2163
        );
2164
    };
2165
    let heads = repo.bookmark_set(name, &heads)?;
2166
    println!(
2167
        "{} bookmark {} {} {}",
2168
        ui::done("Moved"),
2169
        ui::bookmark(name),
2170
        ui::dim(ui::glyph("→", "->")),
2171
        ui::dim(plural(heads.len(), "head"))
2172
    );
2173
    Ok(0)
2174
}
2175
2176
pub fn bookmark_delete(name: &str) -> Result<i32> {
2177
    let repo = open()?;
2178
    repo.bookmark_delete(name)?;
2179
    println!(
2180
        "{} bookmark {} {}",
2181
        ui::done("Deleted"),
2182
        ui::bookmark(name),
2183
        ui::dim("(its changes stay until unreachable)")
2184
    );
2185
    Ok(0)
2186
}
2187
2188
pub fn bookmark_list(all: bool, as_json: bool) -> Result<i32> {
2189
    let repo = open()?;
2190
    let remote_only = repo.remote_only_bookmarks()?;
2191
    if as_json {
2192
        let mut items: Vec<String> = repo
2193
            .bookmarks()?
2194
            .into_iter()
2195
            .map(|b| {
2196
                json::obj([
2197
                    ("name", json::s(&b.name)),
2198
                    ("heads", json::hashes(&b.heads)),
2199
                    ("current", json::b(b.current)),
2200
                    ("ahead", json::opt(b.ahead, json::n)),
2201
                    ("behind", json::opt(b.behind, json::n)),
2202
                ])
2203
            })
2204
            .collect();
2205
        if all {
2206
            items.extend(remote_only.iter().map(|b| {
2207
                json::obj([
2208
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
2209
                    ("heads", json::hashes(&b.heads)),
2210
                    ("current", json::b(false)),
2211
                    ("ahead", "null".into()),
2212
                    ("behind", "null".into()),
2213
                    ("remote", json::s(&b.remote)),
2214
                ])
2215
            }));
2216
        }
2217
        println!("{}", json::arr(items));
2218
        return Ok(0);
2219
    }
2220
    for b in repo.bookmarks()? {
2221
        let mark = if b.current {
2222
            ui::ok(ui::glyph("●", "*"))
2223
        } else {
2224
            ui::dim(ui::glyph("○", "o"))
2225
        };
2226
        let mut tail = String::new();
2227
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
2228
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
2229
        }
2230
        if let Some(n) = b.behind.filter(|n| *n > 0) {
2231
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
2232
        }
2233
        let head = b
2234
            .heads
2235
            .first()
2236
            .map(|h| {
2237
                repo.store()
2238
                    .get_change(h)
2239
                    .map(|c| ui::subject(subject_of(&c.message)))
2240
                    .unwrap_or_default()
2241
            })
2242
            .unwrap_or_else(|| ui::dim("(empty)"));
2243
        println!(
2244
            "{mark} {}{}{}{tail}  {head}",
2245
            ui::bookmark(&b.name),
2246
            ui::sep(),
2247
            ui::dim(plural(b.heads.len(), "head"))
2248
        );
2249
    }
2250
    if remote_only.is_empty() {
2251
        return Ok(0);
2252
    }
2253
    if !all {
2254
        println!(
2255
            "{}",
2256
            ui::dim(format!(
2257
                "  and {} only on a remote: oxy bookmark list --all",
2258
                plural(remote_only.len(), "bookmark")
2259
            ))
2260
        );
2261
        return Ok(0);
2262
    }
2263
    for b in &remote_only {
2264
        println!(
2265
            "{} {}{}{}",
2266
            ui::dim(ui::glyph("◌", ".")),
2267
            ui::dim(format!("{}/{}", b.remote, b.name)),
2268
            ui::sep(),
2269
            ui::dim(plural(b.heads.len(), "head"))
2270
        );
2271
    }
2272
    println!(
2273
        "  {} {}",
2274
        ui::note(),
2275
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2276
    );
2277
    Ok(0)
2278
}
2279
2280
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
2281
    let mut repo = open()?;
2282
    let from = repo.config.bookmark.clone();
2283
    let (local, created_from) = repo.local_bookmark_for(name)?;
2284
    if let Some(remote) = created_from {
2285
        println!(
2286
            "{} {} from {}",
2287
            ui::done("Created"),
2288
            ui::bookmark(&local),
2289
            ui::dim(format!("{remote}/{local}"))
2290
        );
2291
    }
2292
    let name = local.as_str();
2293
    let sp = ui::spinner(&format!("Switching to {name}…"));
2294
    let (r, carried) = if carry {
2295
        repo.bookmark_switch_carry(name)?
2296
    } else {
2297
        (repo.bookmark_switch(name, discard)?, vec![])
2298
    };
2299
    sp.done(&format!(
2300
        "{} to {}: {} written, {} removed{}",
2301
        ui::done("Switched"),
2302
        ui::bookmark(name),
2303
        plural(r.written, "file"),
2304
        r.removed,
2305
        if carried.is_empty() {
2306
            String::new()
2307
        } else {
2308
            format!("; carried {}", plural(carried.len(), "changed path"))
2309
        }
2310
    ));
2311
    if r.conflicted {
2312
        println!(
2313
            "  {} {}",
2314
            ui::caution(),
2315
            ui::warn("this state has conflicts; see oxy status")
2316
        );
2317
    }
2318
    // Say when the new state leaves out work the old one had: a state is
2319
    // its heads and what they depend on, which can be far less than a Git
2320
    // user expects.
2321
    if r.lacks > 0 {
2322
        println!(
2323
            "  {} {}",
2324
            ui::note(),
2325
            ui::dim(format!(
2326
                "{name} lacks {} that {from} has",
2327
                plural(r.lacks, "change")
2328
            ))
2329
        );
2330
    }
2331
    super::sync::subrepos_behind(&repo);
2332
    where_now(&repo);
2333
    Ok(0)
2334
}
2335
2336
pub fn merge(bookmark: &str) -> Result<i32> {
2337
    let repo = open()?;
2338
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
2339
    let r = repo.merge(bookmark)?;
2340
    if !r.changed {
2341
        sp.done(&format!(
2342
            "{} {}",
2343
            ui::ok(ui::glyph("✔", "*")),
2344
            ui::dim(format!(
2345
                "{} already contains {bookmark}",
2346
                repo.config.bookmark
2347
            ))
2348
        ));
2349
        return Ok(0);
2350
    }
2351
    sp.done(&format!(
2352
        "{} {} into {}: now {}{}",
2353
        ui::done("Merged"),
2354
        ui::bookmark(bookmark),
2355
        ui::bookmark(&repo.config.bookmark),
2356
        plural(r.heads.len(), "head"),
2357
        ui::dim(if r.checked_out {
2358
            "; working copy updated"
2359
        } else {
2360
            "; run oxy checkout to update the working copy"
2361
        })
2362
    ));
2363
    let snap = repo.snapshot("oxy merge")?;
2364
    if snap.base_snapshot.is_conflicted() {
2365
        println!(
2366
            "  {} {}",
2367
            ui::caution(),
2368
            ui::warn("the result has conflicts; see oxy status")
2369
        );
2370
    }
2371
    where_now(&repo);
2372
    Ok(0)
2373
}
2374
2375
pub fn squash(change: &str, into: &str) -> Result<i32> {
2376
    let repo = open()?;
2377
    let c = repo.resolve_change(change)?;
2378
    let d = repo.resolve_change(into)?;
2379
    let sp = ui::spinner("Squashing…");
2380
    let h = repo.squash(&c, &d)?;
2381
    let new = repo.store().get_change(&h)?;
2382
    sp.done(&format!(
2383
        "{} into {} {}  {}",
2384
        ui::done("Squashed"),
2385
        ui::id(short_id(&new)),
2386
        ui::hash(format!("#{}", h.short(12))),
2387
        ui::subject(subject_of(&new.message))
2388
    ));
2389
    Ok(0)
2390
}
2391
2392
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
2393
    let repo = open()?;
2394
    let c = repo.resolve_change(change)?;
2395
    let mut heads = Vec::new();
2396
    for o in onto {
2397
        heads.extend(repo.resolve_heads(o)?);
2398
    }
2399
    let sp = ui::spinner("Rebasing…");
2400
    let h = match repo.rebase(&c, &heads) {
2401
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
2402
            let r = repo.rebase_into_working_copy(&c, &heads)?;
2403
            sp.done(&format!(
2404
                "{} {} into {}: now {}",
2405
                ui::done("Merged"),
2406
                onto.join(" "),
2407
                ui::bookmark(&repo.config.bookmark),
2408
                plural(r.heads.len(), "head"),
2409
            ));
2410
            if r.checked_out {
2411
                println!(
2412
                    "  {} {}",
2413
                    ui::caution(),
2414
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
2415
                );
2416
            } else {
2417
                println!(
2418
                    "  {} {}",
2419
                    ui::caution(),
2420
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
2421
                );
2422
            }
2423
            where_now(&repo);
2424
            return Ok(0);
2425
        }
2426
        other => other?,
2427
    };
2428
    let new = repo.store().get_change(&h)?;
2429
    sp.done(&format!(
2430
        "{} {} {}  {}",
2431
        ui::done("Rebased"),
2432
        ui::id(short_id(&new)),
2433
        ui::hash(format!("#{}", h.short(12))),
2434
        ui::dim(format!(
2435
            "now depends on {}",
2436
            plural(new.deps.len(), "change")
2437
        ))
2438
    ));
2439
    where_now(&repo);
2440
    Ok(0)
2441
}