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