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