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