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