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