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