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