OXYGENHUB
# 9935d490ddfb oxygen / src / cli / workspace.rs
80.7 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
                // What was built: a release's or install's `oxy describe`,
985
                // a Flow build's heads, or "local build".
986
                ("build", json::s(env!("OXY_BUILD_ID"))),
987
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
988
                ("format", json::n(2))
989
            ])
990
        );
991
    } else {
992
        println!(
993
            "oxy {} (repository format 2, protocol {})",
994
            env!("OXY_VERSION_LONG"),
995
            oxy_core::protocol::PROTOCOL_VERSION
996
        );
997
    }
998
    Ok(0)
999
}
1000
1001
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
1002
    let repo = open()?;
1003
    if paths.is_empty() && hunks.is_empty() {
1004
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
1005
    }
1006
    let mut n = 0;
1007
    if !hunks.is_empty() {
1008
        n += repo.discard_hunks(hunks)?;
1009
    }
1010
    if !paths.is_empty() {
1011
        n += repo.discard(paths)?;
1012
    }
1013
    println!(
1014
        "{} {} restored to the working copy's base",
1015
        ui::done("Discarded"),
1016
        plural(n, "path")
1017
    );
1018
    Ok(0)
1019
}
1020
1021
pub fn hunks(as_json: bool) -> Result<i32> {
1022
    let repo = open()?;
1023
    let (_, hunks) = repo.hunks()?;
1024
    if as_json {
1025
        println!(
1026
            "{}",
1027
            json::arr(hunks.iter().map(|h| json::obj([
1028
                ("index", json::n(h.index)),
1029
                ("path", json::s(&h.path)),
1030
                ("text", json::s(&h.text))
1031
            ])))
1032
        );
1033
        return Ok(0);
1034
    }
1035
    if hunks.is_empty() {
1036
        println!(
1037
            "{}",
1038
            ui::dim("No hunks: the working copy matches its base.")
1039
        );
1040
    }
1041
    for h in &hunks {
1042
        println!(
1043
            "{} {}",
1044
            ui::section(format!("hunk {}", h.index)),
1045
            ui::path(&h.path)
1046
        );
1047
        for line in h.text.lines() {
1048
            let styled = if line.starts_with('+') {
1049
                ui::ok(line)
1050
            } else if line.starts_with('-') {
1051
                ui::err(line)
1052
            } else {
1053
                ui::dim(line)
1054
            };
1055
            println!("  {styled}");
1056
        }
1057
    }
1058
    Ok(0)
1059
}
1060
1061
pub fn show(change: Option<&str>, revset: Option<&str>, as_json: bool) -> Result<i32> {
1062
    let repo = open()?;
1063
    repo.snapshot_status("oxy show")?;
1064
    let Some(r) = revset else {
1065
        let h = repo.resolve_change(change.unwrap_or("@"))?;
1066
        return show_one(&repo, h, as_json, false);
1067
    };
1068
    // Several changes: a JSON array, or the changes one after another.
1069
    let hashes = repo.revset(r)?.hashes;
1070
    if as_json {
1071
        print!("[");
1072
        for (i, h) in hashes.iter().enumerate() {
1073
            if i > 0 {
1074
                print!(",");
1075
            }
1076
            show_one(&repo, *h, true, true)?;
1077
        }
1078
        println!("]");
1079
        return Ok(0);
1080
    }
1081
    if hashes.is_empty() {
1082
        println!("{}", ui::dim(format!("No change matches {r:?}.")));
1083
        return Ok(0);
1084
    }
1085
    for (i, h) in hashes.iter().enumerate() {
1086
        if i > 0 {
1087
            println!();
1088
        }
1089
        show_one(&repo, *h, false, false)?;
1090
    }
1091
    Ok(0)
1092
}
1093
1094
/// One change, as `oxy show` prints it; `inline` JSON goes without its
1095
/// newline, for an array.
1096
fn show_one(repo: &Repo, h: ChangeHash, as_json: bool, inline: bool) -> Result<i32> {
1097
    let c = repo.store().get_change(&h)?;
1098
    if as_json {
1099
        let files = repo.diff_files(Some(&h))?;
1100
        let heads = repo.bookmark_heads()?;
1101
        let entry = oxy_core::repo::LogEntry {
1102
            hash: h,
1103
            change: oxy_core::state::ChangeMeta::of(&c),
1104
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
1105
            is_head: heads.contains(&h),
1106
        };
1107
        let mut body = log_entry_json(repo, &entry)?;
1108
        body.pop();
1109
        body.push_str(&format!(
1110
            ",{}:{}}}",
1111
            json::s("files"),
1112
            json::arr(files.iter().map(|f| json::obj([
1113
                ("path", json::s(&f.path)),
1114
                ("kind", json::s(&f.kind)),
1115
                ("from", json::opt(f.from.as_deref(), json::s))
1116
            ])))
1117
        ));
1118
        if inline {
1119
            print!("{body}");
1120
        } else {
1121
            println!("{body}");
1122
        }
1123
        return Ok(0);
1124
    }
1125
    println!(
1126
        "{} {} {}",
1127
        ui::section("change"),
1128
        ui::id(short_id(&c)),
1129
        ui::hash(format!("#{h}"))
1130
    );
1131
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
1132
    // Fetched but not pulled (oxygen#56): say where it is.
1133
    if let Some(at) = repo.remote_only_location(&h)? {
1134
        println!(
1135
            "{}",
1136
            ui::kv(
1137
                "only in",
1138
                ui::warn(format!(
1139
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
1140
                ))
1141
            )
1142
        );
1143
    }
1144
    let meta = oxy_core::state::ChangeMeta::of(&c);
1145
    let status = repo.authenticate_change_known(&h, Some(&meta))?;
1146
    println!("{}", ui::kv("author", ui::author(author_name(repo, &meta))));
1147
    if let Some(agent) = via(repo, &status, &meta.author) {
1148
        println!("{}", ui::kv("via", agent.line()));
1149
    }
1150
    println!(
1151
        "{}",
1152
        ui::kv(
1153
            "date",
1154
            format!(
1155
                "{} {}",
1156
                when(c.hlc.wall_ms),
1157
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1158
            )
1159
        )
1160
    );
1161
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
1162
    println!("{}", ui::kv("sig", signature_line(repo, &h)?));
1163
    println!();
1164
    for line in (if c.message.is_empty() {
1165
        "(no description)"
1166
    } else {
1167
        &c.message
1168
    })
1169
    .lines()
1170
    {
1171
        println!("    {line}");
1172
    }
1173
    println!();
1174
    print!("{}", repo.describe_change(&h)?);
1175
    Ok(0)
1176
}
1177
1178
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
1179
    let repo = open()?;
1180
    // `oxy checkout BOOKMARK` is being on that bookmark, as `git checkout
1181
    // BRANCH` is: checking its files out under another bookmark's name
1182
    // made the next commit move the wrong bookmark (oxygen#60).
1183
    if let [name] = changes {
1184
        if *name != repo.config.bookmark && names_bookmark(&repo, name)? {
1185
            drop(repo);
1186
            return bookmark_switch(name, discard, carry);
1187
        }
1188
    }
1189
    let heads = if changes.is_empty() {
1190
        repo.bookmark_heads()?
1191
    } else {
1192
        let mut heads = Vec::new();
1193
        for c in changes {
1194
            heads.extend(repo.resolve_heads(c)?);
1195
        }
1196
        heads
1197
    };
1198
    let spec = if changes.is_empty() {
1199
        repo.config.bookmark.clone()
1200
    } else {
1201
        changes.join(" ")
1202
    };
1203
    let sp = ui::spinner(&format!("Checking out {spec}…"));
1204
    let command = format!("oxy checkout {spec}");
1205
    let (r, carried) = if carry {
1206
        repo.checkout_carry(&heads, &spec, &command)?
1207
    } else {
1208
        (repo.checkout(&heads, discard, &command)?, vec![])
1209
    };
1210
    sp.done(&format!(
1211
        "{} on {}: {} written, {} removed{}",
1212
        ui::done("Working copy"),
1213
        ui::bookmark(&spec),
1214
        plural(r.written, "file"),
1215
        r.removed,
1216
        if carried.is_empty() {
1217
            String::new()
1218
        } else {
1219
            format!("; carried {}", plural(carried.len(), "changed path"))
1220
        }
1221
    ));
1222
    for n in &r.notes {
1223
        println!("  {} {n}", ui::note());
1224
    }
1225
    if r.conflicted {
1226
        println!(
1227
            "  {} {}",
1228
            ui::caution(),
1229
            ui::warn("this state has conflicts; see oxy status")
1230
        );
1231
    }
1232
    where_now(&repo);
1233
    Ok(0)
1234
}
1235
1236
pub fn resolve(as_json: bool) -> Result<i32> {
1237
    let repo = open()?;
1238
    let snap = repo.snapshot("oxy resolve")?;
1239
    if as_json {
1240
        println!("{}", repo.status_json(&snap)?);
1241
        return Ok(if snap.base_snapshot.is_conflicted() {
1242
            2
1243
        } else {
1244
            0
1245
        });
1246
    }
1247
    if !snap.base_snapshot.is_conflicted() {
1248
        println!("The working copy's base has no conflicts.");
1249
        return Ok(0);
1250
    }
1251
    let mut remaining = 0;
1252
    for (p, f) in &snap.base_snapshot.files {
1253
        if !f.is_conflicted() {
1254
            continue;
1255
        }
1256
        match snap
1257
            .statuses
1258
            .iter()
1259
            .find(|s| s.path == *p)
1260
            .map(|s| s.status)
1261
        {
1262
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
1263
            Some(ChangeStatus::ConflictEdited) => {
1264
                remaining += 1;
1265
                println!("markers    {p}");
1266
            }
1267
            _ => {
1268
                remaining += 1;
1269
                println!("unresolved {p}");
1270
            }
1271
        }
1272
    }
1273
    for c in &snap.base_snapshot.tree.conflicts {
1274
        remaining += 1;
1275
        println!("tree       {c:?}");
1276
    }
1277
    if remaining == 0 {
1278
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
1279
        Ok(0)
1280
    } else {
1281
        Ok(2)
1282
    }
1283
}
1284
1285
pub fn undo() -> Result<i32> {
1286
    let repo = open()?;
1287
    let op = repo.undo()?;
1288
    println!("{} now at: {}", ui::done("Undone;"), ui::dim(&op.command));
1289
    where_now(&repo);
1290
    Ok(0)
1291
}
1292
1293
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
1294
    let repo = open()?;
1295
    let ops = repo.op_log()?;
1296
    // What each operation changed, against the one before it.
1297
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
1298
        match ops.get(i + 1) {
1299
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
1300
            None => Ok(vec![]),
1301
        }
1302
    };
1303
    if as_json {
1304
        let mut items = Vec::new();
1305
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
1306
            let summary: Vec<String> = changes_of(i)?
1307
                .iter()
1308
                .map(|c| change_words(&repo, c))
1309
                .collect();
1310
            items.push(json::obj([
1311
                ("id", json::s(&r.to_hex())),
1312
                ("when_ms", json::n(op.hlc.wall_ms)),
1313
                ("command", json::s(&op.command)),
1314
                ("snapshot", json::b(op.is_snapshot())),
1315
                ("current", json::b(i == 0)),
1316
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1317
            ]));
1318
        }
1319
        println!("{}", json::arr(items));
1320
        return Ok(0);
1321
    }
1322
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
1323
    let id = |r: &oxy_core::hash::ObjectRef| {
1324
        let hex = r.to_hex();
1325
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
1326
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
1327
    };
1328
    let rail = ui::dim(ui::glyph("│", "|"));
1329
    let (mut i, mut shown) = (0, 0);
1330
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
1331
        let (r, op) = &ops[i];
1332
        let bullet = if i == 0 {
1333
            ui::ok(ui::glyph("@", "@"))
1334
        } else {
1335
            ui::dim(ui::glyph("○", "o"))
1336
        };
1337
        // A run of snapshots folds into one entry.
1338
        let mut run = 1;
1339
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
1340
            run += 1;
1341
        }
1342
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
1343
        if op.is_snapshot() {
1344
            let span = if run > 1 {
1345
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1346
            } else {
1347
                String::new()
1348
            };
1349
            println!(
1350
                "{bullet}  {}{} {when}",
1351
                id(r),
1352
                if span.is_empty() {
1353
                    String::new()
1354
                } else {
1355
                    format!(" {span}")
1356
                }
1357
            );
1358
            println!(
1359
                "{rail}  {}",
1360
                ui::dim(if run == 1 {
1361
                    "working-copy snapshot".to_string()
1362
                } else {
1363
                    format!("{run} working-copy snapshots")
1364
                })
1365
            );
1366
        } else {
1367
            println!("{bullet}  {} {when}", id(r));
1368
            let words: Vec<String> = changes_of(i)?
1369
                .iter()
1370
                .map(|c| change_words(&repo, c))
1371
                .collect();
1372
            let summary = if words.is_empty() {
1373
                if i + 1 == ops.len() {
1374
                    "created the repository".to_string()
1375
                } else {
1376
                    "no bookmark or working-copy change".to_string()
1377
                }
1378
            } else {
1379
                words.join("; ")
1380
            };
1381
            println!(
1382
                "{rail}  {}",
1383
                if i == 0 {
1384
                    ui::subject(&summary)
1385
                } else {
1386
                    summary
1387
                }
1388
            );
1389
            let cmd = op.command.lines().next().unwrap_or("");
1390
            let cmd: String = cmd.chars().take(100).collect();
1391
            println!("{rail}  {}", ui::dim(cmd));
1392
        }
1393
        i += run;
1394
        shown += 1;
1395
    }
1396
    if i < ops.len() {
1397
        println!(
1398
            "{}",
1399
            ui::dim(format!(
1400
                "{} {} older; pass -n to see more",
1401
                ui::glyph("…", "..."),
1402
                plural(ops.len() - i, "operation")
1403
            ))
1404
        );
1405
    }
1406
    Ok(0)
1407
}
1408
1409
/// One change an operation made, in words.
1410
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1411
    use oxy_core::repo::ViewChange::*;
1412
    match c {
1413
        BookmarkCreated { name, heads } => {
1414
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1415
        }
1416
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
1417
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
1418
        BookmarkMoved { name, from, to } => format!(
1419
            "{name}: {from} {} {}",
1420
            ui::glyph("→", "->"),
1421
            plural(*to, "head")
1422
        ),
1423
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
1424
        TagCreated { name } => format!("tagged {name}"),
1425
        TagDeleted { name } => format!("removed tag {name}"),
1426
        Policy => "trust policy changed".to_string(),
1427
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
1428
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
1429
            Err(_) => "working copy moved".to_string(),
1430
        },
1431
    }
1432
}
1433
1434
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
1435
    let repo = open()?;
1436
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
1437
    let r = repo.op_restore(op, discard)?;
1438
    sp.done(&format!(
1439
        "{} to operation {} {}",
1440
        ui::done("Restored"),
1441
        ui::hash(r.op.short(12)),
1442
        ui::dim(r.command.lines().next().unwrap_or(""))
1443
    ));
1444
    println!(
1445
        "  {} {}",
1446
        ui::note(),
1447
        ui::dim(format!(
1448
            "{} written, {} removed; oxy undo goes back again",
1449
            plural(r.checkout.written, "file"),
1450
            r.checkout.removed
1451
        ))
1452
    );
1453
    where_now(&repo);
1454
    Ok(0)
1455
}
1456
1457
pub fn op_revert(op: &str) -> Result<i32> {
1458
    let repo = open()?;
1459
    let r = repo.op_revert(op)?;
1460
    let view = repo.view()?;
1461
    let names: Vec<String> = r
1462
        .reverted
1463
        .iter()
1464
        .map(|n| {
1465
            if view.bookmarks.contains_key(n) {
1466
                ui::bookmark(n)
1467
            } else {
1468
                format!("{} (removed)", ui::bookmark(n))
1469
            }
1470
        })
1471
        .collect();
1472
    println!(
1473
        "{} operation {} {}",
1474
        ui::done("Reverted"),
1475
        ui::hash(r.op.short(12)),
1476
        ui::dim(r.command.lines().next().unwrap_or(""))
1477
    );
1478
    println!(
1479
        "  {} {}",
1480
        ui::note(),
1481
        ui::dim(format!("as before it: {}", names.join(", ")))
1482
    );
1483
    if !r.kept.is_empty() {
1484
        println!(
1485
            "  {} {}",
1486
            ui::caution(),
1487
            ui::warn(format!(
1488
                "left as they are, having moved again since: {}",
1489
                r.kept.join(", ")
1490
            ))
1491
        );
1492
    }
1493
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
1494
        println!(
1495
            "  {} {}",
1496
            ui::note(),
1497
            ui::dim("the working copy has work of its own: oxy checkout to move it")
1498
        );
1499
    }
1500
    where_now(&repo);
1501
    Ok(0)
1502
}
1503
1504
/// Where the working copy and bookmark are now, after a command moved
1505
/// them (as jj says "Working copy now at").
1506
pub fn where_now(repo: &Repo) {
1507
    let Ok((_, wc)) = repo.working_copy() else {
1508
        return;
1509
    };
1510
    let heads = repo.bookmark_heads().unwrap_or_default();
1511
    let newest = heads
1512
        .iter()
1513
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
1514
        .max_by_key(|(m, _)| m.hlc);
1515
    println!(
1516
        "  {} {}",
1517
        ui::dim(format!("{:<13}", "Working copy")),
1518
        ui::id(wc.change_id.short(8))
1519
    );
1520
    let tail = match newest {
1521
        Some((m, _)) => format!(
1522
            ", newest {} {}",
1523
            ui::id(m.change_id.short(8)),
1524
            subject_of(&m.message)
1525
        ),
1526
        None => String::new(),
1527
    };
1528
    println!(
1529
        "  {} {}: {}{tail}",
1530
        ui::dim(format!("{:<13}", "Bookmark")),
1531
        ui::bookmark(&repo.config.bookmark),
1532
        plural(heads.len(), "head")
1533
    );
1534
}
1535
1536
pub fn gc(now: bool) -> Result<i32> {
1537
    let repo = open()?;
1538
    let sp = ui::spinner("Packing and pruning…");
1539
    let r = repo.gc(now)?;
1540
    sp.clear();
1541
    if r.packed.objects > 0 {
1542
        println!(
1543
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
1544
            plural(r.packed.objects, "object"),
1545
            r.packed.raw_bytes,
1546
            r.packed.packed_bytes,
1547
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
1548
        );
1549
    }
1550
    println!(
1551
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
1552
        plural(r.reachable, "object"),
1553
        plural(r.pruned.objects, "unreachable object"),
1554
        r.pruned.bytes,
1555
        if r.pruned.deferred > 0 {
1556
            format!(
1557
                "; {} deferred by the grace period (use --now)",
1558
                plural(r.pruned.deferred, "object")
1559
            )
1560
        } else {
1561
            String::new()
1562
        },
1563
        if r.merged_packs > 0 {
1564
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1565
        } else {
1566
            String::new()
1567
        },
1568
        plural(repo.store().pack_count(), "pack")
1569
    );
1570
    Ok(0)
1571
}
1572
1573
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
1574
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1575
    use oxy_core::repo::Health;
1576
    let repo = open()?;
1577
    let sp = ui::spinner(if offline {
1578
        "Checking…"
1579
    } else {
1580
        "Checking, and contacting remotes…"
1581
    });
1582
    let r = repo.doctor(!offline);
1583
    sp.clear();
1584
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
1585
    let word = |h: Health| match h {
1586
        Health::Ok => "ok",
1587
        Health::Warn => "warning",
1588
        Health::Fail => "fail",
1589
    };
1590
    if as_json {
1591
        let checks: Vec<String> = r
1592
            .checks
1593
            .iter()
1594
            .map(|c| {
1595
                json::obj([
1596
                    ("area", json::s(&c.area)),
1597
                    ("health", json::s(word(c.health))),
1598
                    ("message", json::s(&c.message)),
1599
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
1600
                ])
1601
            })
1602
            .collect();
1603
        println!(
1604
            "{}",
1605
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1606
        );
1607
        return Ok(code);
1608
    }
1609
    let mut last = "";
1610
    for c in &r.checks {
1611
        if c.area != last {
1612
            println!("{}", ui::section(&c.area));
1613
            last = &c.area;
1614
        }
1615
        let mark = match c.health {
1616
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
1617
            Health::Warn => ui::caution(),
1618
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1619
        };
1620
        println!("  {mark} {}", c.message);
1621
        if let Some(h) = &c.hint {
1622
            println!("    {} {}", ui::dim("→"), ui::dim(h));
1623
        }
1624
    }
1625
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
1626
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
1627
    if fails + warns == 0 {
1628
        println!("{}", ui::done("Everything looks right."));
1629
    } else {
1630
        println!(
1631
            "{} {}, {}.",
1632
            if fails > 0 {
1633
                ui::err(ui::glyph("✖", "x"))
1634
            } else {
1635
                ui::caution()
1636
            },
1637
            plural(fails, "problem"),
1638
            plural(warns, "warning")
1639
        );
1640
    }
1641
    Ok(code)
1642
}
1643
1644
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
1645
pub fn fsck(as_json: bool) -> Result<i32> {
1646
    use oxy_core::repo::Severity;
1647
    let repo = open()?;
1648
    let sp = ui::spinner("Checking every object…");
1649
    let r = repo.fsck()?;
1650
    sp.clear();
1651
    let code = if r.errors() > 0 { 1 } else { 0 };
1652
    if as_json {
1653
        let problems: Vec<String> = r
1654
            .problems
1655
            .iter()
1656
            .map(|p| {
1657
                json::obj([
1658
                    (
1659
                        "severity",
1660
                        json::s(match p.severity {
1661
                            Severity::Error => "error",
1662
                            Severity::Warning => "warning",
1663
                        }),
1664
                    ),
1665
                    (
1666
                        "object",
1667
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1668
                    ),
1669
                    ("what", json::s(&p.what)),
1670
                ])
1671
            })
1672
            .collect();
1673
        println!(
1674
            "{}",
1675
            json::obj([
1676
                ("ok", json::b(code == 0)),
1677
                ("objects", json::n(r.objects)),
1678
                ("ops", json::n(r.ops)),
1679
                ("changes", json::n(r.changes)),
1680
                ("signed", json::n(r.signed)),
1681
                ("unsigned", json::n(r.unsigned)),
1682
                ("checkpoints", json::n(r.checkpoints)),
1683
                ("attestations", json::n(r.attestations)),
1684
                ("errors", json::n(r.errors())),
1685
                ("warnings", json::n(r.warnings())),
1686
                ("problems", json::arr(problems)),
1687
            ])
1688
        );
1689
        return Ok(code);
1690
    }
1691
    println!(
1692
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
1693
        plural(r.objects, "object"),
1694
        plural(r.ops, "operation"),
1695
        plural(r.changes, "change"),
1696
        r.signed,
1697
        r.unsigned,
1698
        plural(r.checkpoints, "checkpoint"),
1699
        plural(r.attestations, "attestation"),
1700
    );
1701
    for p in &r.problems {
1702
        let obj = p
1703
            .object
1704
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
1705
            .unwrap_or_default();
1706
        match p.severity {
1707
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
1708
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1709
        }
1710
    }
1711
    if r.problems.is_empty() {
1712
        println!("{}", ui::done("No problems found."));
1713
    } else if code == 0 {
1714
        println!(
1715
            "{}",
1716
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
1717
        );
1718
    } else {
1719
        println!(
1720
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
1721
            ui::err(ui::glyph("✖", "x")),
1722
            plural(r.errors(), "error"),
1723
            plural(r.warnings(), "warning")
1724
        );
1725
    }
1726
    Ok(code)
1727
}
1728
1729
/// The head the working copy sits on, for commands that default to it. With
1730
/// several heads beneath the working copy, the most recently made one is
1731
/// chosen and announced.
1732
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
1733
    let snap = repo.snapshot_status("oxy")?;
1734
    let base = snap.base.maximal(&snap.wc.deps);
1735
    match base.as_slice() {
1736
        [] => anyhow::bail!("the working copy sits on no change yet"),
1737
        [h] => Ok(*h),
1738
        many => {
1739
            let latest = many
1740
                .iter()
1741
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
1742
                .copied()
1743
                .unwrap();
1744
            let c = repo.store().get_change(&latest)?;
1745
            println!(
1746
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
1747
                short_id(&c),
1748
                latest.short(12),
1749
                many.len()
1750
            );
1751
            Ok(latest)
1752
        }
1753
    }
1754
}
1755
1756
/// `oxy describe` without -m: the working copy's name for a build.
1757
pub fn describe_name(as_json: bool) -> Result<i32> {
1758
    let repo = open()?;
1759
    let d = repo.describe_working_copy()?;
1760
    if as_json {
1761
        println!(
1762
            "{}",
1763
            json::obj([
1764
                ("describe", json::s(&d.line())),
1765
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
1766
                ("distance", json::n(d.distance)),
1767
                ("bookmark", json::s(&d.bookmark)),
1768
                ("change", json::s(&d.change.to_hex())),
1769
                ("hash", json::s(&d.hash.to_hex())),
1770
                ("dirty", json::b(d.dirty)),
1771
            ])
1772
        );
1773
    } else {
1774
        println!("{}", d.line());
1775
    }
1776
    Ok(0)
1777
}
1778
1779
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
1780
    let repo = open()?;
1781
    let h = match change {
1782
        Some(c) => repo.resolve_change(c)?,
1783
        None => current_head(&repo)?,
1784
    };
1785
    let new = repo.describe(&h, message)?;
1786
    let c = repo.store().get_change_meta(&new)?;
1787
    println!(
1788
        "{} {} {}  {}",
1789
        ui::done("Described"),
1790
        ui::id(c.change_id.short(8)),
1791
        ui::hash(format!("#{}", new.short(12))),
1792
        ui::subject(subject_of(message))
1793
    );
1794
    Ok(0)
1795
}
1796
1797
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
1798
    let repo = open()?;
1799
    let new = match into {
1800
        Some(spec) => {
1801
            let target = repo.resolve_change(spec)?;
1802
            repo.amend_into(&target, message)?
1803
        }
1804
        None => repo.amend(message)?,
1805
    };
1806
    let c = repo.store().get_change_meta(&new)?;
1807
    println!(
1808
        "{} {} {}  {}",
1809
        ui::done("Amended"),
1810
        ui::id(c.change_id.short(8)),
1811
        ui::hash(format!("#{}", new.short(12))),
1812
        ui::subject(subject_of(&c.message))
1813
    );
1814
    where_now(&repo);
1815
    Ok(0)
1816
}
1817
1818
pub fn abandon(change: Option<&str>, revset: Option<&str>, yes: bool) -> Result<i32> {
1819
    let repo = open()?;
1820
    let Some(r) = revset else {
1821
        let h = repo.resolve_change(change.unwrap_or_default())?;
1822
        abandon_one(&repo, h)?;
1823
        where_now(&repo);
1824
        return Ok(0);
1825
    };
1826
    // A revset: say what it selects, refuse an empty set, ask above a few.
1827
    let selected = repo.revset(r)?;
1828
    let wc = repo.working_copy().ok().map(|(h, _)| h);
1829
    let hashes: Vec<ChangeHash> = selected
1830
        .hashes
1831
        .iter()
1832
        .copied()
1833
        .filter(|h| Some(*h) != wc)
1834
        .collect();
1835
    if hashes.is_empty() {
1836
        anyhow::bail!("{r:?} selects no change to abandon");
1837
    }
1838
    println!(
1839
        "{} {} selects {}:",
1840
        ui::section("abandon"),
1841
        ui::id(r),
1842
        plural(hashes.len(), "change")
1843
    );
1844
    for h in &hashes {
1845
        if let Some(m) = selected.metas.get(h) {
1846
            println!(
1847
                "  {} {}  {}",
1848
                ui::id(m.change_id.short(8)),
1849
                ui::hash(format!("#{}", h.short(12))),
1850
                subject_of(&m.message)
1851
            );
1852
        }
1853
    }
1854
    const ASK_ABOVE: usize = 5;
1855
    if hashes.len() > ASK_ABOVE && !yes {
1856
        anyhow::bail!("that is more than {ASK_ABOVE} changes; pass --yes to abandon them all");
1857
    }
1858
    // Newest first: abandoning a change rewrites what depends on it, so a
1859
    // later member is found again by its ChangeId.
1860
    let mut done = 0;
1861
    for h in &hashes {
1862
        let Some(m) = selected.metas.get(h) else {
1863
            continue;
1864
        };
1865
        let now = match repo.resolve_change(&m.change_id.to_hex()) {
1866
            Ok(h) => h,
1867
            Err(_) => continue,
1868
        };
1869
        abandon_one(&repo, now)?;
1870
        done += 1;
1871
    }
1872
    println!("{} {}", ui::done("Abandoned"), plural(done, "change"));
1873
    where_now(&repo);
1874
    Ok(0)
1875
}
1876
1877
fn abandon_one(repo: &Repo, h: ChangeHash) -> Result<()> {
1878
    let c = repo.store().get_change_meta(&h)?;
1879
    let notes = repo.abandon(&h)?;
1880
    println!(
1881
        "{} {} {}  {}",
1882
        ui::done("Abandoned"),
1883
        ui::id(c.change_id.short(8)),
1884
        ui::hash(format!("#{}", h.short(12))),
1885
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
1886
    );
1887
    for n in notes {
1888
        println!("  {} {n}", ui::note());
1889
    }
1890
    Ok(())
1891
}
1892
1893
pub fn checkpoint() -> Result<i32> {
1894
    let repo = open()?;
1895
    let sp = ui::spinner("Writing checkpoint…");
1896
    let (r, changes, bytes) = repo.checkpoint()?;
1897
    sp.done(&format!(
1898
        "{} {} of {} ({} bytes) for {}",
1899
        ui::done("Checkpoint"),
1900
        ui::hash(format!("#{}", r.short(12))),
1901
        plural(changes, "change"),
1902
        bytes,
1903
        ui::id(&repo.config.bookmark)
1904
    ));
1905
    Ok(0)
1906
}
1907
1908
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
1909
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
1910
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
1911
        return Ok(1);
1912
    };
1913
    let info = repo.quick_status()?;
1914
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
1915
        oxy_core::repo::GLYPH_PROMPT_FORMAT
1916
    } else {
1917
        format
1918
    };
1919
    let line = match color {
1920
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
1921
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
1922
        Some(_) => info.format_colored(fmt, ("", "")),
1923
        None => info.format(fmt),
1924
    };
1925
    println!("{line}");
1926
    Ok(0)
1927
}
1928
1929
pub fn sparse(paths: &[String]) -> Result<i32> {
1930
    let mut repo = open()?;
1931
    if paths.is_empty() {
1932
        if repo.config.sparse_paths.is_empty() {
1933
            println!("No sparse filter: the whole tree is materialized.");
1934
        } else {
1935
            println!("{}", ui::heading("Sparse filter"));
1936
            for p in &repo.config.sparse_paths {
1937
                println!("  {}", ui::path(p));
1938
            }
1939
        }
1940
        return Ok(0);
1941
    }
1942
    let snap = repo.snapshot("oxy sparse")?;
1943
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
1944
        anyhow::bail!(
1945
            "the working copy has changes; commit them before changing the sparse filter"
1946
        );
1947
    }
1948
    repo.config.set("filter.paths", &paths.join(","))?;
1949
    repo.save_config()?;
1950
    let heads = repo.bookmark_heads()?;
1951
    let sp = ui::spinner("Re-checking out with the new filter…");
1952
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
1953
    sp.done(&format!(
1954
        "{} {}: {} written, {} removed",
1955
        ui::done("Sparse filter set to"),
1956
        ui::path(paths.join(",")),
1957
        plural(r.written, "file"),
1958
        r.removed
1959
    ));
1960
    Ok(0)
1961
}
1962
1963
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
1964
    let repo = open()?;
1965
    repo.snapshot_status("oxy tag")?;
1966
    let heads = if changes.is_empty() {
1967
        repo.bookmark_heads()?
1968
    } else {
1969
        let mut heads = Vec::new();
1970
        for c in changes {
1971
            heads.extend(repo.resolve_heads(c)?);
1972
        }
1973
        heads
1974
    };
1975
    let t = repo.tag_create(name, &heads, message)?;
1976
    println!(
1977
        "{} {} {} {} ({}){}",
1978
        ui::done("Tagged"),
1979
        ui::bookmark(&t.name),
1980
        ui::dim(ui::glyph("→", "->")),
1981
        ui::hash(format!("#{}", t.state.short(12))),
1982
        plural(t.heads.len(), "head"),
1983
        t.signer
1984
            .map(|s| format!(", signed by {s}"))
1985
            .unwrap_or_else(|| ui::dim(", unsigned"))
1986
    );
1987
    Ok(0)
1988
}
1989
1990
pub fn tag_list(as_json: bool) -> Result<i32> {
1991
    let repo = open()?;
1992
    let tags = repo.tags()?;
1993
    if as_json {
1994
        println!(
1995
            "{}",
1996
            json::arr(tags.iter().map(|t| {
1997
                json::obj([
1998
                    ("name", json::s(&t.name)),
1999
                    ("state", json::s(&t.state.to_hex())),
2000
                    ("heads", json::hashes(&t.heads)),
2001
                    ("message", json::s(&t.message)),
2002
                    (
2003
                        "signer",
2004
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
2005
                    ),
2006
                ])
2007
            }))
2008
        );
2009
        return Ok(0);
2010
    }
2011
    if tags.is_empty() {
2012
        println!("{}", ui::dim("No tags."));
2013
    }
2014
    for t in tags {
2015
        println!(
2016
            "{} {} {}{}{}{}",
2017
            ui::ok(ui::glyph("⚑", "#")),
2018
            ui::bookmark(&t.name),
2019
            // The heads, as `oxy log` shows changes, not the state hash.
2020
            ui::hash(
2021
                t.heads
2022
                    .iter()
2023
                    .map(|h| format!("#{}", h.short(12)))
2024
                    .collect::<Vec<_>>()
2025
                    .join(" ")
2026
            ),
2027
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
2028
            if t.message.is_empty() {
2029
                String::new()
2030
            } else {
2031
                format!("  {}", ui::subject(subject_of(&t.message)))
2032
            },
2033
            t.signer
2034
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
2035
                .unwrap_or_default()
2036
        );
2037
    }
2038
    Ok(0)
2039
}
2040
2041
/// Whether `name` is a bookmark, here or only on a remote: what checkout
2042
/// and workspace add take as "be on this bookmark" (oxygen#60).
2043
fn names_bookmark(repo: &oxy_core::repo::Repo, name: &str) -> Result<bool> {
2044
    Ok(repo.view()?.bookmarks.contains_key(name)
2045
        || repo
2046
            .remote_only_bookmarks()?
2047
            .iter()
2048
            .any(|b| b.name == name || format!("{}/{}", b.remote, b.name) == name))
2049
}
2050
2051
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
2052
    let repo = open()?;
2053
    // One bookmark named: the new workspace is on it (oxygen#60), not on
2054
    // this workspace's bookmark with that one's files.
2055
    if let [name] = changes {
2056
        if names_bookmark(&repo, name)? {
2057
            let (local, _) = repo.local_bookmark_for(name)?;
2058
            let heads = repo.resolve_heads(&local)?;
2059
            let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
2060
            let ws = repo.workspace_add_on(path, Some(&heads), Some(&local))?;
2061
            sp.done(&format!(
2062
                "{} {} (workspace {}) on {}",
2063
                ui::done("Workspace created at"),
2064
                ui::path(ws.root().display()),
2065
                ui::id(ws.workspace().short(8)),
2066
                ui::bookmark(&local)
2067
            ));
2068
            return Ok(0);
2069
        }
2070
    }
2071
    let heads = if changes.is_empty() {
2072
        None
2073
    } else {
2074
        let mut heads = Vec::new();
2075
        for c in changes {
2076
            heads.extend(repo.resolve_heads(c)?);
2077
        }
2078
        Some(heads)
2079
    };
2080
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
2081
    let ws = repo.workspace_add(path, heads.as_deref())?;
2082
    sp.done(&format!(
2083
        "{} {} (workspace {})",
2084
        ui::done("Workspace created at"),
2085
        ui::path(ws.root().display()),
2086
        ui::id(ws.workspace().short(8))
2087
    ));
2088
    Ok(0)
2089
}
2090
2091
pub fn workspace_list(as_json: bool) -> Result<i32> {
2092
    let repo = open()?;
2093
    if as_json {
2094
        println!(
2095
            "{}",
2096
            json::arr(repo.workspaces()?.iter().map(|w| {
2097
                json::obj([
2098
                    ("id", json::s(&w.id.to_hex())),
2099
                    ("path", json::s(&w.path.to_string_lossy())),
2100
                    ("current", json::b(w.current)),
2101
                    (
2102
                        "working_copy",
2103
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
2104
                    ),
2105
                ])
2106
            }))
2107
        );
2108
        return Ok(0);
2109
    }
2110
    for w in repo.workspaces()? {
2111
        println!(
2112
            "{} {} {}{}",
2113
            if w.current {
2114
                ui::ok(ui::glyph("●", "*"))
2115
            } else {
2116
                ui::dim(ui::glyph("○", "o"))
2117
            },
2118
            ui::id(w.id.short(8)),
2119
            ui::path(w.path.display()),
2120
            w.working_copy
2121
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
2122
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
2123
        );
2124
    }
2125
    Ok(0)
2126
}
2127
2128
pub fn workspace_forget(spec: &str) -> Result<i32> {
2129
    let repo = open()?;
2130
    let all = repo.workspaces()?;
2131
    let target = std::fs::canonicalize(spec).ok();
2132
    let matches: Vec<_> = all
2133
        .iter()
2134
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
2135
        .collect();
2136
    let w = match matches.as_slice() {
2137
        [w] => *w,
2138
        [] => anyhow::bail!("no workspace matches {spec:?}"),
2139
        _ => anyhow::bail!("{spec:?} is ambiguous"),
2140
    };
2141
    repo.workspace_forget(&w.id)?;
2142
    println!(
2143
        "{} workspace {} at {}; its files were left in place.",
2144
        ui::done("Forgot"),
2145
        ui::id(w.id.short(8)),
2146
        ui::path(w.path.display())
2147
    );
2148
    Ok(0)
2149
}
2150
2151
pub fn lock(path: &str) -> Result<i32> {
2152
    let repo = open()?;
2153
    repo.lock_path(path)?;
2154
    println!(
2155
        "{} {} {}",
2156
        ui::done("Locked"),
2157
        ui::path(path),
2158
        ui::dim("(advisory, local)")
2159
    );
2160
    Ok(0)
2161
}
2162
2163
pub fn unlock(path: &str) -> Result<i32> {
2164
    let repo = open()?;
2165
    repo.unlock_path(path)?;
2166
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
2167
    Ok(0)
2168
}
2169
2170
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
2171
    let repo = open()?;
2172
    let h = repo.resolve_change(change)?;
2173
    let (h1, h2) = repo.split(&h, paths)?;
2174
    let c1 = repo.store().get_change_meta(&h1)?;
2175
    let c2 = repo.store().get_change_meta(&h2)?;
2176
    println!(
2177
        "{} into {} {} and {} {}",
2178
        ui::done("Split"),
2179
        ui::id(c1.change_id.short(8)),
2180
        ui::hash(format!("#{}", h1.short(12))),
2181
        ui::id(c2.change_id.short(8)),
2182
        ui::hash(format!("#{}", h2.short(12)))
2183
    );
2184
    Ok(0)
2185
}
2186
2187
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
2188
    let mut heads = Vec::new();
2189
    for c in changes {
2190
        heads.extend(repo.resolve_heads(c)?);
2191
    }
2192
    Ok(heads)
2193
}
2194
2195
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
2196
    let repo = open()?;
2197
    repo.snapshot_status("oxy bookmark create")?;
2198
    let heads = if changes.is_empty() {
2199
        None
2200
    } else {
2201
        let named = heads_from(&repo, changes)?;
2202
        let (_, wc) = repo.working_copy()?;
2203
        let gap = repo.state_gap(&wc.deps, &named)?;
2204
        if upto {
2205
            Some(gap.upto)
2206
        } else if only || gap.earlier.is_empty() {
2207
            Some(named)
2208
        } else {
2209
            anyhow::bail!(
2210
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2211
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2212
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2213
                 or --only for just {0} and what it depends on.",
2214
                changes.join(" "),
2215
                plural(gap.earlier.len(), "change"),
2216
                listed_changes(&repo, &gap.earlier)
2217
            );
2218
        }
2219
    };
2220
    let heads = repo.bookmark_create(name, heads.as_deref())?;
2221
    println!(
2222
        "{} bookmark {} {} {}",
2223
        ui::done("Created"),
2224
        ui::bookmark(name),
2225
        ui::dim(ui::glyph("→", "->")),
2226
        ui::dim(plural(heads.len(), "head"))
2227
    );
2228
    println!(
2229
        "  {} {}",
2230
        ui::note(),
2231
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2232
    );
2233
    Ok(0)
2234
}
2235
2236
/// Up to five changes, newest last, as `  #hash subject` lines.
2237
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
2238
    let shown = changes.len().min(5);
2239
    let mut lines: Vec<String> = changes[changes.len() - shown..]
2240
        .iter()
2241
        .map(|h| {
2242
            let subject = repo
2243
                .store()
2244
                .get_change(h)
2245
                .map(|c| subject_of(&c.message).to_string())
2246
                .unwrap_or_default();
2247
            format!("  #{} {subject}", h.short(12))
2248
        })
2249
        .collect();
2250
    if changes.len() > shown {
2251
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
2252
    }
2253
    lines.join("\n")
2254
}
2255
2256
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
2257
    let repo = open()?;
2258
    repo.snapshot_status("oxy bookmark set")?;
2259
    let named = heads_from(&repo, changes)?;
2260
    // What the bookmark holds now and the new heads would leave out.
2261
    let current = repo
2262
        .bookmarks()?
2263
        .into_iter()
2264
        .find(|b| b.name == name)
2265
        .map(|b| b.heads)
2266
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
2267
    let gap = repo.state_gap(&current, &named)?;
2268
    let heads = if upto {
2269
        gap.upto
2270
    } else if only || gap.earlier.is_empty() {
2271
        named
2272
    } else {
2273
        anyhow::bail!(
2274
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2275
             A state is its heads and what they depend on, not everything recorded before them.\n\
2276
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2277
             or --only for just {0} and what it depends on.",
2278
            changes.join(" "),
2279
            plural(gap.earlier.len(), "change"),
2280
            listed_changes(&repo, &gap.earlier)
2281
        );
2282
    };
2283
    let heads = repo.bookmark_set(name, &heads)?;
2284
    println!(
2285
        "{} bookmark {} {} {}",
2286
        ui::done("Moved"),
2287
        ui::bookmark(name),
2288
        ui::dim(ui::glyph("→", "->")),
2289
        ui::dim(plural(heads.len(), "head"))
2290
    );
2291
    Ok(0)
2292
}
2293
2294
pub fn bookmark_delete(name: &str) -> Result<i32> {
2295
    let repo = open()?;
2296
    repo.bookmark_delete(name)?;
2297
    println!(
2298
        "{} bookmark {} {}",
2299
        ui::done("Deleted"),
2300
        ui::bookmark(name),
2301
        ui::dim("(its changes stay until unreachable)")
2302
    );
2303
    Ok(0)
2304
}
2305
2306
pub fn bookmark_list(all: bool, as_json: bool) -> Result<i32> {
2307
    let repo = open()?;
2308
    let remote_only = repo.remote_only_bookmarks()?;
2309
    if as_json {
2310
        let mut items: Vec<String> = repo
2311
            .bookmarks()?
2312
            .into_iter()
2313
            .map(|b| {
2314
                json::obj([
2315
                    ("name", json::s(&b.name)),
2316
                    ("heads", json::hashes(&b.heads)),
2317
                    ("current", json::b(b.current)),
2318
                    ("ahead", json::opt(b.ahead, json::n)),
2319
                    ("behind", json::opt(b.behind, json::n)),
2320
                ])
2321
            })
2322
            .collect();
2323
        if all {
2324
            items.extend(remote_only.iter().map(|b| {
2325
                json::obj([
2326
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
2327
                    ("heads", json::hashes(&b.heads)),
2328
                    ("current", json::b(false)),
2329
                    ("ahead", "null".into()),
2330
                    ("behind", "null".into()),
2331
                    ("remote", json::s(&b.remote)),
2332
                ])
2333
            }));
2334
        }
2335
        println!("{}", json::arr(items));
2336
        return Ok(0);
2337
    }
2338
    for b in repo.bookmarks()? {
2339
        let mark = if b.current {
2340
            ui::ok(ui::glyph("●", "*"))
2341
        } else {
2342
            ui::dim(ui::glyph("○", "o"))
2343
        };
2344
        let mut tail = String::new();
2345
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
2346
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
2347
        }
2348
        if let Some(n) = b.behind.filter(|n| *n > 0) {
2349
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
2350
        }
2351
        let head = b
2352
            .heads
2353
            .first()
2354
            .map(|h| {
2355
                repo.store()
2356
                    .get_change(h)
2357
                    .map(|c| ui::subject(subject_of(&c.message)))
2358
                    .unwrap_or_default()
2359
            })
2360
            .unwrap_or_else(|| ui::dim("(empty)"));
2361
        println!(
2362
            "{mark} {}{}{}{tail}  {head}",
2363
            ui::bookmark(&b.name),
2364
            ui::sep(),
2365
            ui::dim(plural(b.heads.len(), "head"))
2366
        );
2367
    }
2368
    if remote_only.is_empty() {
2369
        return Ok(0);
2370
    }
2371
    if !all {
2372
        println!(
2373
            "{}",
2374
            ui::dim(format!(
2375
                "  and {} only on a remote: oxy bookmark list --all",
2376
                plural(remote_only.len(), "bookmark")
2377
            ))
2378
        );
2379
        return Ok(0);
2380
    }
2381
    for b in &remote_only {
2382
        println!(
2383
            "{} {}{}{}",
2384
            ui::dim(ui::glyph("◌", ".")),
2385
            ui::dim(format!("{}/{}", b.remote, b.name)),
2386
            ui::sep(),
2387
            ui::dim(plural(b.heads.len(), "head"))
2388
        );
2389
    }
2390
    println!(
2391
        "  {} {}",
2392
        ui::note(),
2393
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2394
    );
2395
    Ok(0)
2396
}
2397
2398
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
2399
    let mut repo = open()?;
2400
    let from = repo.config.bookmark.clone();
2401
    let (local, created_from) = repo.local_bookmark_for(name)?;
2402
    if let Some(remote) = created_from {
2403
        println!(
2404
            "{} {} from {}",
2405
            ui::done("Created"),
2406
            ui::bookmark(&local),
2407
            ui::dim(format!("{remote}/{local}"))
2408
        );
2409
    }
2410
    let name = local.as_str();
2411
    let sp = ui::spinner(&format!("Switching to {name}…"));
2412
    let (r, carried) = if carry {
2413
        repo.bookmark_switch_carry(name)?
2414
    } else {
2415
        (repo.bookmark_switch(name, discard)?, vec![])
2416
    };
2417
    sp.done(&format!(
2418
        "{} to {}: {} written, {} removed{}",
2419
        ui::done("Switched"),
2420
        ui::bookmark(name),
2421
        plural(r.written, "file"),
2422
        r.removed,
2423
        if carried.is_empty() {
2424
            String::new()
2425
        } else {
2426
            format!("; carried {}", plural(carried.len(), "changed path"))
2427
        }
2428
    ));
2429
    if r.conflicted {
2430
        println!(
2431
            "  {} {}",
2432
            ui::caution(),
2433
            ui::warn("this state has conflicts; see oxy status")
2434
        );
2435
    }
2436
    // Say when the new state leaves out work the old one had: a state is
2437
    // its heads and what they depend on, which can be far less than a Git
2438
    // user expects.
2439
    if r.lacks > 0 {
2440
        println!(
2441
            "  {} {}",
2442
            ui::note(),
2443
            ui::dim(format!(
2444
                "{name} lacks {} that {from} has",
2445
                plural(r.lacks, "change")
2446
            ))
2447
        );
2448
    }
2449
    super::sync::subrepos_behind(&repo);
2450
    where_now(&repo);
2451
    Ok(0)
2452
}
2453
2454
pub fn merge(bookmark: &str) -> Result<i32> {
2455
    let repo = open()?;
2456
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
2457
    let r = repo.merge(bookmark)?;
2458
    if !r.changed {
2459
        sp.done(&format!(
2460
            "{} {}",
2461
            ui::ok(ui::glyph("✔", "*")),
2462
            ui::dim(format!(
2463
                "{} already contains {bookmark}",
2464
                repo.config.bookmark
2465
            ))
2466
        ));
2467
        return Ok(0);
2468
    }
2469
    sp.done(&format!(
2470
        "{} {} into {}: now {}{}",
2471
        ui::done("Merged"),
2472
        ui::bookmark(bookmark),
2473
        ui::bookmark(&repo.config.bookmark),
2474
        plural(r.heads.len(), "head"),
2475
        ui::dim(if r.checked_out {
2476
            "; working copy updated"
2477
        } else {
2478
            "; run oxy checkout to update the working copy"
2479
        })
2480
    ));
2481
    let snap = repo.snapshot("oxy merge")?;
2482
    if snap.base_snapshot.is_conflicted() {
2483
        println!(
2484
            "  {} {}",
2485
            ui::caution(),
2486
            ui::warn("the result has conflicts; see oxy status")
2487
        );
2488
    }
2489
    where_now(&repo);
2490
    Ok(0)
2491
}
2492
2493
pub fn squash(change: &str, into: &str) -> Result<i32> {
2494
    let repo = open()?;
2495
    let c = repo.resolve_change(change)?;
2496
    let d = repo.resolve_change(into)?;
2497
    let sp = ui::spinner("Squashing…");
2498
    let h = repo.squash(&c, &d)?;
2499
    let new = repo.store().get_change_meta(&h)?;
2500
    sp.done(&format!(
2501
        "{} into {} {}  {}",
2502
        ui::done("Squashed"),
2503
        ui::id(new.change_id.short(8)),
2504
        ui::hash(format!("#{}", h.short(12))),
2505
        ui::subject(subject_of(&new.message))
2506
    ));
2507
    Ok(0)
2508
}
2509
2510
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
2511
    let repo = open()?;
2512
    let c = repo.resolve_change(change)?;
2513
    let mut heads = Vec::new();
2514
    for o in onto {
2515
        heads.extend(repo.resolve_heads(o)?);
2516
    }
2517
    let sp = ui::spinner("Rebasing…");
2518
    let h = match repo.rebase(&c, &heads) {
2519
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
2520
            let r = repo.rebase_into_working_copy(&c, &heads)?;
2521
            sp.done(&format!(
2522
                "{} {} into {}: now {}",
2523
                ui::done("Merged"),
2524
                onto.join(" "),
2525
                ui::bookmark(&repo.config.bookmark),
2526
                plural(r.heads.len(), "head"),
2527
            ));
2528
            if r.checked_out {
2529
                println!(
2530
                    "  {} {}",
2531
                    ui::caution(),
2532
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
2533
                );
2534
            } else {
2535
                println!(
2536
                    "  {} {}",
2537
                    ui::caution(),
2538
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
2539
                );
2540
            }
2541
            where_now(&repo);
2542
            return Ok(0);
2543
        }
2544
        other => other?,
2545
    };
2546
    let new = repo.store().get_change_meta(&h)?;
2547
    sp.done(&format!(
2548
        "{} {} {}  {}",
2549
        ui::done("Rebased"),
2550
        ui::id(new.change_id.short(8)),
2551
        ui::hash(format!("#{}", h.short(12))),
2552
        ui::dim(format!(
2553
            "now depends on {}",
2554
            plural(new.deps.len(), "change")
2555
        ))
2556
    ));
2557
    where_now(&repo);
2558
    Ok(0)
2559
}