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