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