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