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