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