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