OXYGENHUB
# 1ec3f008e96a oxygen / src / cli / workspace.rs
73.2 KiB · Rust · last changed Diff from the status cache: the working-copy change rendered against its indexed base (refs #41) 1 month 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::{
2bf22305 Andy McCall ↶ 4
    author_name, deps_line, deps_of, plural, short_id, signature_line, signature_mark, subject_of,
5
    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};
14
use std::path::PathBuf;
15
e02bf0cd Andy McCall ↶ 16
pub fn init(path: Option<PathBuf>, bare: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 17
    let path = path.unwrap_or(std::env::current_dir()?);
75167672 Andy McCall 18
    let repo = if bare {
19
        Repo::init_bare(&path)?
20
    } else {
21
        Repo::init(&path)?
22
    };
23
    println!(
24
        "{} {}oxy repository in {}",
25
        ui::done("Initialized"),
26
        if bare { "bare " } else { "" },
27
        ui::path(repo.root().display())
28
    );
29
    println!(
30
        "{}",
31
        ui::kv("bookmark", ui::bookmark(&repo.config.bookmark))
32
    );
33
    println!(
34
        "{}",
35
        ui::kv(
36
            "author",
37
            format!(
38
                "{} <{}>",
39
                ui::author(&repo.config.author_name),
40
                repo.config.author_email
41
            )
42
        )
43
    );
fce44ae9 Andy McCall ↶ 44
    Ok(0)
45
}
46
47
fn status_tag(s: ChangeStatus) -> &'static str {
48
    match s {
49
        ChangeStatus::Added => "A",
50
        ChangeStatus::Modified => "M",
51
        ChangeStatus::Removed => "D",
6e723b81 Andy McCall ↶ 52
        ChangeStatus::Renamed => "R",
fce44ae9 Andy McCall ↶ 53
        ChangeStatus::ModeChanged => "X",
54
        ChangeStatus::ConflictEdited => "C!",
6e723b81 Andy McCall ↶ 55
        ChangeStatus::Resolved => "V",
fce44ae9 Andy McCall ↶ 56
    }
57
}
58
d4dbab97 Andy McCall ↶ 59
/// Folders holding a repository of their own, which oxy leaves out (oxygen#43):
60
/// named, with how to track them.
61
fn print_untracked_nested(repo: &Repo, nested: &[String]) {
62
    if nested.is_empty() {
63
        return;
64
    }
65
    println!();
66
    println!(
67
        "{} {}",
68
        ui::section(ui::warn("Not tracked")),
69
        ui::dim("folders holding a repository of their own")
70
    );
71
    for p in nested {
72
        let kind = if repo.root().join(p).join(".git").exists() {
73
            "Git"
74
        } else {
75
            "Oxygen"
76
        };
77
        println!(
78
            "  {} {}  {}",
79
            ui::caution(),
80
            ui::path(format!("{p}/")),
81
            ui::dim(format!("a nested {kind} repository"))
82
        );
83
    }
84
    println!(
85
        "  {} {}",
86
        ui::note(),
87
        ui::dim(
88
            "to track one's files, remove its .git (or .oxy); to keep it a repository of its own, \
89
             oxy submodule add URL PATH"
90
        )
91
    );
92
}
93
36041796 Andy McCall ↶ 94
/// The working copy's changed paths, or that it is clean.
95
fn print_statuses(statuses: &[oxy_core::repo::PathStatus]) {
96
    if statuses.is_empty() {
97
        println!(
98
            "  {} {}",
99
            ui::ok(ui::glyph("✔", "*")),
100
            ui::dim("nothing to commit, working copy clean")
101
        );
102
        return;
103
    }
104
    println!();
105
    for s in statuses {
106
        println!(
107
            "  {} {}",
108
            ui::status_mark(status_tag(s.status)),
109
            ui::path(&s.path)
110
        );
111
    }
112
}
113
50a046e4 Andy McCall ↶ 114
pub fn status(json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 115
    let repo = open()?;
36041796 Andy McCall ↶ 116
    // Answered by the manifest alone, with no history to load (oxygen#35,
117
    // #41): a clean working copy, or one as the last snapshot left it.
118
    let known = if json {
119
        None
120
    } else {
121
        repo.status_by_manifest()?
122
    };
123
    if let Some(statuses) = known {
da868d5d Andy McCall ↶ 124
        let (_, wc) = repo.working_copy()?;
125
        let heads = repo.bookmark_heads()?;
126
        println!(
127
            "{} {}{}working copy {}{}{}",
128
            ui::dim("On"),
129
            ui::bookmark(&repo.config.bookmark),
130
            ui::sep(),
131
            ui::id(wc.change_id.short(8)),
132
            ui::sep(),
133
            ui::dim(plural(heads.len(), "head"))
134
        );
36041796 Andy McCall ↶ 135
        print_statuses(&statuses);
d4dbab97 Andy McCall ↶ 136
        print_untracked_nested(&repo, &repo.untracked_nested());
da868d5d Andy McCall ↶ 137
        return Ok(0);
138
    }
135212de Andy McCall ↶ 139
    let sp = ui::spinner("Snapshotting the working copy…");
cc7a0056 Andy McCall ↶ 140
    let snap = repo.snapshot_status("oxy status")?;
4cce912a Andy McCall ↶ 141
    let heads = {
142
        let _t = oxy_core::timing::phase("status: heads");
143
        repo.bookmark_heads()?
144
    };
145
    let _drop = oxy_core::timing::phase("status: print and drop");
135212de Andy McCall ↶ 146
    sp.clear();
50a046e4 Andy McCall ↶ 147
    if json {
148
        println!("{}", repo.status_json(&snap)?);
75167672 Andy McCall 149
        return Ok(if snap.base_snapshot.is_conflicted() {
150
            2
151
        } else {
152
            0
153
        });
50a046e4 Andy McCall ↶ 154
    }
135212de Andy McCall ↶ 155
    println!(
94084087 Andy McCall ↶ 156
        "{} {}{}working copy {}{}{}",
157
        ui::dim("On"),
158
        ui::bookmark(&repo.config.bookmark),
159
        ui::sep(),
135212de Andy McCall ↶ 160
        ui::id(snap.wc.change_id.short(8)),
94084087 Andy McCall ↶ 161
        ui::sep(),
162
        ui::dim(plural(heads.len(), "head"))
135212de Andy McCall ↶ 163
    );
36041796 Andy McCall ↶ 164
    print_statuses(&snap.statuses);
d4dbab97 Andy McCall ↶ 165
    print_untracked_nested(&repo, &snap.untracked_nested);
fce44ae9 Andy McCall ↶ 166
    if !snap.base_snapshot.is_conflicted() {
167
        return Ok(0);
168
    }
135212de Andy McCall ↶ 169
    println!();
75167672 Andy McCall 170
    println!(
171
        "{} {}",
172
        ui::section(ui::err("Conflicts")),
173
        ui::dim("edit the marked files, or the .oxy-conflict-N candidates, then commit")
174
    );
fce44ae9 Andy McCall ↶ 175
    for c in &snap.base_snapshot.tree.conflicts {
94084087 Andy McCall ↶ 176
        println!("  {} tree: {c:?}", ui::err(ui::glyph("✱", "!")));
fce44ae9 Andy McCall ↶ 177
    }
178
    for (p, f) in &snap.base_snapshot.files {
179
        if f.is_conflicted() {
75167672 Andy McCall 180
            let state = match snap
181
                .statuses
182
                .iter()
183
                .find(|s| s.path == *p)
184
                .map(|s| s.status)
185
            {
186
                Some(ChangeStatus::Resolved) => {
187
                    ui::ok(format!("{} resolved in working copy", ui::glyph("✔", "*")))
188
                }
189
                Some(ChangeStatus::ConflictEdited) => {
190
                    ui::warn(format!("{} markers remain", ui::glyph("‼", "!")))
191
                }
94084087 Andy McCall ↶ 192
                _ => ui::err(format!("{} unresolved", ui::glyph("✱", "!"))),
fce44ae9 Andy McCall ↶ 193
            };
135212de Andy McCall ↶ 194
            println!("  {}  {state}", ui::path(p));
fce44ae9 Andy McCall ↶ 195
        }
196
    }
197
    Ok(2)
198
}
199
75167672 Andy McCall 200
pub fn commit(
201
    message: &str,
202
    depends_on: &[String],
203
    paths: &[String],
204
    interactive: bool,
205
    hunks: &[usize],
206
) -> Result<i32> {
fce44ae9 Andy McCall ↶ 207
    let repo = open()?;
208
    let mut deps = Vec::new();
209
    for d in depends_on {
210
        deps.push(repo.resolve_change(d)?);
211
    }
c6aa5bd9 Andy McCall ↶ 212
    let selection = if !hunks.is_empty() {
213
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
214
    } else if interactive {
957fee30 Andy McCall ↶ 215
        let (_, hunks) = repo.hunks()?;
216
        if hunks.is_empty() {
217
            anyhow::bail!("nothing to commit: the working copy matches its base");
218
        }
75167672 Andy McCall 219
        let hunks: Vec<_> = hunks
220
            .into_iter()
221
            .filter(|h| {
222
                paths.is_empty()
223
                    || paths.iter().any(|p| {
224
                        h.path == *p || h.path.starts_with(&format!("{}/", p.trim_end_matches('/')))
225
                    })
226
            })
227
            .collect();
957fee30 Andy McCall ↶ 228
        let mut chosen = Vec::new();
229
        let stdin = std::io::stdin();
230
        let mut take_rest = false;
231
        for (n, h) in hunks.iter().enumerate() {
232
            if take_rest {
233
                chosen.push(h.index);
234
                continue;
235
            }
75167672 Andy McCall 236
            println!(
237
                "{} {} {}",
238
                ui::section(format!("hunk {} of {}", n + 1, hunks.len())),
239
                ui::path(&h.path),
240
                ui::dim(format!("(#{})", h.index))
241
            );
957fee30 Andy McCall ↶ 242
            for line in h.text.lines() {
75167672 Andy McCall 243
                let styled = if line.starts_with('+') {
244
                    ui::ok(line)
245
                } else if line.starts_with('-') {
246
                    ui::err(line)
247
                } else {
248
                    ui::dim(line)
249
                };
957fee30 Andy McCall ↶ 250
                println!("  {styled}");
251
            }
252
            loop {
75167672 Andy McCall 253
                print!(
254
                    "{} ",
255
                    ui::warn("Commit this hunk? [y]es [n]o [a]ll remaining [q]uit:")
256
                );
957fee30 Andy McCall ↶ 257
                use std::io::Write as _;
258
                std::io::stdout().flush()?;
259
                let mut answer = String::new();
260
                if stdin.read_line(&mut answer)? == 0 {
261
                    anyhow::bail!("aborted");
262
                }
263
                match answer.trim() {
264
                    "y" | "Y" => {
265
                        chosen.push(h.index);
266
                        break;
267
                    }
268
                    "n" | "N" | "" => break,
269
                    "a" | "A" => {
270
                        chosen.push(h.index);
271
                        take_rest = true;
272
                        break;
273
                    }
274
                    "q" | "Q" => anyhow::bail!("aborted; nothing committed"),
275
                    _ => continue,
276
                }
277
            }
278
        }
279
        if chosen.is_empty() {
280
            anyhow::bail!("no hunks chosen; nothing committed");
281
        }
282
        oxy_core::repo::Selection::Hunks(chosen)
283
    } else if paths.is_empty() {
284
        oxy_core::repo::Selection::All
285
    } else {
286
        oxy_core::repo::Selection::Paths(paths.to_vec())
287
    };
135212de Andy McCall ↶ 288
    let sp = ui::spinner("Committing…");
957fee30 Andy McCall ↶ 289
    let h = repo.commit_selection(message, &deps, &selection)?;
fce44ae9 Andy McCall ↶ 290
    let c = repo.store().get_change(&h)?;
75167672 Andy McCall 291
    sp.done(&format!(
292
        "{} {} {}  {}",
293
        ui::done("Committed"),
294
        ui::id(short_id(&c)),
295
        ui::hash(format!("#{}", h.short(12))),
296
        ui::subject(subject_of(message))
297
    ));
d4dbab97 Andy McCall ↶ 298
    print_untracked_nested(&repo, &repo.untracked_nested());
957fee30 Andy McCall ↶ 299
    if !matches!(selection, oxy_core::repo::Selection::All) {
8ab265dc Andy McCall ↶ 300
        let rest = repo.snapshot_status("oxy commit")?;
957fee30 Andy McCall ↶ 301
        if !rest.statuses.is_empty() {
75167672 Andy McCall 302
            println!(
303
                "  {} {}",
304
                ui::note(),
305
                ui::dim(format!(
306
                    "{} left uncommitted",
307
                    plural(rest.statuses.len(), "path")
308
                ))
309
            );
957fee30 Andy McCall ↶ 310
        }
311
    }
98a1620a Andy McCall ↶ 312
    where_now(&repo);
957fee30 Andy McCall ↶ 313
    Ok(0)
314
}
315
316
pub fn blame(path: &str, json: bool) -> Result<i32> {
317
    let repo = open()?;
318
    let lines = repo.blame(path)?;
319
    if json {
320
        let items = lines.iter().map(|l| {
321
            format!(
322
                "{{\"line\":{},\"change_id\":{},\"hash\":{},\"index\":{},\"author\":{},\"when_ms\":{}}}",
323
                l.line,
324
                oxy_core::repo::json_str(&l.change_id.to_hex()),
325
                oxy_core::repo::json_str(&l.hash.to_hex()),
326
                l.index,
327
                oxy_core::repo::json_str(&l.author),
328
                l.when_ms
329
            )
330
        });
331
        println!("{}", oxy_core::repo::json_array(items));
332
        return Ok(0);
333
    }
75167672 Andy McCall 334
    let width = lines
335
        .iter()
336
        .map(|l| l.author.chars().count())
337
        .max()
338
        .unwrap_or(0)
339
        .min(20);
957fee30 Andy McCall ↶ 340
    let digits = lines.len().to_string().len();
341
    for l in &lines {
342
        let author: String = l.author.chars().take(20).collect();
343
        let text = String::from_utf8_lossy(&l.text);
344
        println!(
345
            "{} {} {} {:>digits$}{} {}",
346
            ui::id(l.change_id.short(8)),
347
            ui::author(format!("{author:<width$}")),
348
            ui::dim(ui::ago(l.when_ms)),
349
            l.line,
350
            ui::dim(ui::glyph("│", "|")),
351
            text.trim_end_matches('\n')
352
        );
353
    }
354
    Ok(0)
355
}
356
357
fn bisect_report(repo: &Repo, step: &oxy_core::repo::BisectStep) -> Result<i32> {
358
    use oxy_core::repo::BisectStep::*;
359
    match step {
360
        NeedMarks { good, bad } => {
75167672 Andy McCall 361
            println!(
362
                "{} {} {}",
363
                ui::note(),
364
                ui::dim(format!("{good} good, {bad} bad;")),
365
                ui::dim(if *good == 0 {
366
                    "mark a known-good change or bookmark: oxy bisect good CHANGE"
367
                } else {
368
                    "mark a known-bad change or bookmark: oxy bisect bad CHANGE"
369
                })
370
            );
957fee30 Andy McCall ↶ 371
            Ok(0)
372
        }
75167672 Andy McCall 373
        Testing {
374
            heads,
375
            remaining,
376
            steps_left,
377
        } => {
378
            println!(
379
                "{} {} {}",
380
                ui::done("Testing"),
381
                ui::dim(format!(
382
                    "{} in the state under test;",
383
                    plural(heads.len(), "head")
384
                )),
385
                ui::dim(format!(
386
                    "{remaining} candidates left, about {steps_left} more steps"
387
                ))
388
            );
389
            println!(
390
                "  {} {}",
391
                ui::note(),
392
                ui::dim("run your test, then oxy bisect good | bad | skip")
393
            );
957fee30 Andy McCall ↶ 394
            Ok(0)
395
        }
396
        Found { culprit } => {
397
            let c = repo.store().get_change(culprit)?;
75167672 Andy McCall 398
            println!(
399
                "{} {} {}  {}",
400
                ui::done("Found"),
401
                ui::id(short_id(&c)),
402
                ui::hash(format!("#{}", culprit.short(12))),
403
                ui::subject(subject_of(&c.message))
404
            );
957fee30 Andy McCall ↶ 405
            println!("  {} {}", ui::note(), ui::dim("the first change whose inclusion makes the state bad; oxy bisect reset to return"));
406
            Ok(0)
407
        }
408
        Inconclusive { candidates } => {
75167672 Andy McCall 409
            println!(
410
                "{} {}",
411
                ui::caution(),
412
                ui::warn(format!(
413
                    "every remaining candidate was skipped ({}); oxy bisect reset to return",
414
                    plural(candidates.len(), "change")
415
                ))
416
            );
957fee30 Andy McCall ↶ 417
            Ok(1)
418
        }
419
    }
420
}
421
422
pub fn bisect_start() -> Result<i32> {
423
    let repo = open()?;
424
    repo.bisect_start()?;
75167672 Andy McCall 425
    println!(
426
        "{} bisect; {}",
427
        ui::done("Started"),
428
        ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE")
429
    );
957fee30 Andy McCall ↶ 430
    Ok(0)
431
}
432
433
pub fn bisect_mark(good: Option<bool>, changes: &[String]) -> Result<i32> {
434
    let repo = open()?;
435
    let mut heads = Vec::new();
436
    for c in changes {
437
        heads.extend(repo.resolve_heads(c)?);
438
    }
439
    let step = repo.bisect_mark(good, &heads)?;
440
    bisect_report(&repo, &step)
441
}
442
443
pub fn bisect_run(command: &[String]) -> Result<i32> {
444
    let repo = open()?;
445
    let step = repo.bisect_run(command)?;
446
    bisect_report(&repo, &step)
447
}
448
c6aa5bd9 Andy McCall ↶ 449
pub fn bisect_status(as_json: bool) -> Result<i32> {
957fee30 Andy McCall ↶ 450
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 451
    if as_json {
452
        use oxy_core::repo::BisectStep::*;
453
        let v = match repo.bisect_status()? {
454
            None => "null".to_string(),
75167672 Andy McCall 455
            Some(NeedMarks { good, bad }) => json::obj([
456
                ("state", json::s("need-marks")),
457
                ("good", json::n(good)),
458
                ("bad", json::n(bad)),
459
            ]),
460
            Some(Testing {
461
                heads,
462
                remaining,
463
                steps_left,
464
            }) => json::obj([
465
                ("state", json::s("testing")),
466
                ("heads", json::hashes(&heads)),
467
                ("remaining", json::n(remaining)),
468
                ("steps_left", json::n(steps_left)),
469
            ]),
470
            Some(Found { culprit }) => json::obj([
471
                ("state", json::s("found")),
472
                ("culprit", json::s(&culprit.to_hex())),
473
            ]),
474
            Some(Inconclusive { candidates }) => json::obj([
475
                ("state", json::s("inconclusive")),
476
                ("candidates", json::hashes(&candidates)),
477
            ]),
c6aa5bd9 Andy McCall ↶ 478
        };
479
        println!("{v}");
480
        return Ok(0);
481
    }
957fee30 Andy McCall ↶ 482
    match repo.bisect_status()? {
483
        None => {
484
            println!("{}", ui::dim("No bisect in progress."));
485
            Ok(0)
486
        }
487
        Some(step) => bisect_report(&repo, &step),
488
    }
489
}
490
491
pub fn bisect_reset() -> Result<i32> {
492
    let repo = open()?;
493
    repo.bisect_reset()?;
494
    println!("{} bisect; working copy restored", ui::done("Reset"));
fce44ae9 Andy McCall ↶ 495
    Ok(0)
496
}
497
94084087 Andy McCall ↶ 498
/// The log: one entry per change, newest first, joined by a rail. The
499
/// default view is the subject and a metadata line; `verbose` adds the full
500
/// message, dependencies, and the authenticating key.
c6aa5bd9 Andy McCall ↶ 501
fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
502
    Ok(match repo.authenticate_change(h)? {
503
        SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]),
75167672 Andy McCall 504
        SignatureStatus::Valid {
505
            key,
506
            name,
507
            email,
508
            sealed,
509
            revoked,
510
        } => json::obj([
c6aa5bd9 Andy McCall ↶ 511
            ("status", json::s(if sealed { "sealed" } else { "signed" })),
512
            ("key", json::s(&key.to_hex())),
513
            ("name", json::s(&name)),
514
            ("email", json::s(&email)),
515
            ("revoked", json::b(revoked)),
516
        ]),
75167672 Andy McCall 517
        SignatureStatus::Invalid(why) => {
518
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
519
        }
c6aa5bd9 Andy McCall ↶ 520
    })
521
}
522
523
fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result<String> {
524
    let c = &e.change;
525
    Ok(json::obj([
526
        ("hash", json::s(&e.hash.to_hex())),
527
        ("change_id", json::s(&c.change_id.to_hex())),
528
        ("author", json::s(&author_name(repo, c))),
529
        ("author_key", json::s(&c.author.to_hex())),
530
        ("when_ms", json::n(c.hlc.wall_ms)),
531
        ("message", json::s(&c.message)),
532
        ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())),
533
        ("deps", json::hashes(&c.deps)),
534
        ("head", json::b(e.is_head)),
535
        ("working_copy", json::b(e.is_working_copy)),
75167672 Andy McCall 536
        (
537
            "signature",
538
            if e.is_working_copy {
539
                "null".into()
540
            } else {
541
                signature_json(repo, &e.hash)?
542
            },
543
        ),
c6aa5bd9 Andy McCall ↶ 544
    ]))
545
}
546
83d61e80 Andy McCall ↶ 547
/// `START,END:PATH` for `oxy log -L`.
548
fn parse_line_range(spec: &str) -> Result<(usize, usize, &str)> {
549
    let bad = || anyhow::anyhow!("-L {spec}: expected START,END:PATH, as 10,24:src/lib.rs");
550
    let (range, path) = spec.split_once(':').ok_or_else(bad)?;
551
    let (a, b) = range.split_once(',').ok_or_else(bad)?;
552
    Ok((
553
        a.trim().parse().map_err(|_| bad())?,
554
        b.trim().parse().map_err(|_| bad())?,
555
        path,
556
    ))
557
}
558
559
pub fn log(
560
    limit: Option<usize>,
561
    verbose: bool,
562
    path: Option<&str>,
563
    lines: Option<&str>,
564
    as_json: bool,
565
) -> Result<i32> {
fce44ae9 Andy McCall ↶ 566
    let repo = open()?;
69816d68 Andy McCall ↶ 567
    // Whether the working copy is clean and conflicted: from the manifest
568
    // when it proves the working copy clean, else from a snapshot.
98a1620a Andy McCall ↶ 569
    let (conflicted, clean) = if repo.is_at_op() || repo.clean_by_manifest()? {
69816d68 Andy McCall ↶ 570
        (false, true)
571
    } else {
572
        let snap = repo.snapshot_status("oxy log")?;
573
        (snap.base_snapshot.is_conflicted(), snap.statuses.is_empty())
574
    };
4cce912a Andy McCall ↶ 575
    let listing = oxy_core::timing::phase("log: entries");
83d61e80 Andy McCall ↶ 576
    let entries = match (path, lines) {
577
        (_, Some(spec)) => {
578
            let (first, last, p) = parse_line_range(spec)?;
69816d68 Andy McCall ↶ 579
            let (_, wc) = repo.working_copy()?;
580
            let base = repo.load_state_history(&wc.deps)?.maximal(&wc.deps);
581
            repo.line_history(&base, p, first, last)?
83d61e80 Andy McCall ↶ 582
        }
583
        (Some(p), None) => repo.log_for_path(p)?,
584
        (None, None) => repo.log()?,
c6aa5bd9 Andy McCall ↶ 585
    };
4cce912a Andy McCall ↶ 586
    drop(listing);
587
    let _print = oxy_core::timing::phase("log: print");
c6aa5bd9 Andy McCall ↶ 588
    if as_json {
589
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
590
        let mut items = Vec::new();
591
        for e in entries.iter().take(shown) {
592
            items.push(log_entry_json(&repo, e)?);
593
        }
75167672 Andy McCall 594
        println!(
595
            "{}",
596
            json::obj([
597
                ("bookmark", json::s(&repo.config.bookmark)),
598
                ("total", json::n(entries.len())),
599
                ("changes", json::arr(items))
600
            ])
601
        );
c6aa5bd9 Andy McCall ↶ 602
        return Ok(0);
603
    }
94084087 Andy McCall ↶ 604
    let total = entries.len();
605
    let shown = limit.unwrap_or(total).min(total);
2bf22305 Andy McCall ↶ 606
    // Lay out a little past what is shown, so edges into the cut are drawn.
607
    let window: Vec<(ChangeHash, Vec<ChangeHash>)> = entries
608
        .iter()
609
        .take((shown + MAX_EDGE).min(total))
610
        .map(|e| (e.hash, e.change.deps.clone()))
611
        .collect();
612
    let rows = oxy_core::lanes::graph(&window, MAX_EDGE);
613
    // Highlight the shortest prefix that names each change: against the
614
    // whole log, which is what `resolve_change` searches.
615
    let everything;
616
    let all = if path.is_some() || lines.is_some() {
617
        everything = repo.log()?;
618
        &everything
619
    } else {
620
        &entries
621
    };
622
    let id_prefix = unique_prefixes(all.iter().map(|e| e.change.change_id.to_hex()));
623
    let labels = reference_labels(&repo)?;
624
    for (e, row) in entries.iter().take(shown).zip(&rows) {
fce44ae9 Andy McCall ↶ 625
        let c = &e.change;
75167672 Andy McCall 626
        let bullet = ui::log_bullet(
627
            e.is_working_copy,
628
            e.is_head,
629
            e.is_working_copy && conflicted,
630
        );
2bf22305 Andy McCall ↶ 631
        let id = c.change_id.to_hex();
632
        let n = id_prefix.get(&id).copied().unwrap_or(8).min(8);
633
        let mut head = vec![format!("{}{}", ui::id(&id[..n]), ui::dim(&id[n..8]))];
634
        head.push(ui::author(author_name(&repo, c)));
635
        head.push(ui::dim(ui::ago(c.hlc.wall_ms)));
636
        if let Some(names) = labels.get(&e.hash) {
637
            head.push(names.join(" "));
fce44ae9 Andy McCall ↶ 638
        }
94084087 Andy McCall ↶ 639
        if c.kind == ChangeKind::Resolution {
2bf22305 Andy McCall ↶ 640
            head.push(ui::warn("resolution"));
fce44ae9 Andy McCall ↶ 641
        }
2bf22305 Andy McCall ↶ 642
        if !e.is_working_copy {
643
            head.push(ui::hash(format!("#{}", e.hash.short(8))));
644
            head.push(signature_mark(&repo, &e.hash, Some(c))?);
645
        }
646
        println!("{}{}", node_line(row, &bullet), head.join(" "));
94084087 Andy McCall ↶ 647
        let subject = if e.is_working_copy && c.message.is_empty() {
69816d68 Andy McCall ↶ 648
            ui::dim(if clean {
2bf22305 Andy McCall ↶ 649
                "(working copy, clean)"
75167672 Andy McCall 650
            } else {
2bf22305 Andy McCall ↶ 651
                "(working copy, uncommitted changes)"
75167672 Andy McCall 652
            })
2bf22305 Andy McCall ↶ 653
        } else if c.message.trim().is_empty() {
654
            ui::dim("(no description)")
94084087 Andy McCall ↶ 655
        } else {
2bf22305 Andy McCall ↶ 656
            subject_of(&c.message).to_string()
94084087 Andy McCall ↶ 657
        };
2bf22305 Andy McCall ↶ 658
        println!("{}{subject}", below_line(row));
94084087 Andy McCall ↶ 659
        if verbose {
2bf22305 Andy McCall ↶ 660
            let rail = continuation(row);
94084087 Andy McCall ↶ 661
            if !e.is_working_copy {
75167672 Andy McCall 662
                println!(
2bf22305 Andy McCall ↶ 663
                    "{rail}{}",
75167672 Andy McCall 664
                    ui::dim(format!(
665
                        "{} {}",
666
                        when(c.hlc.wall_ms),
667
                        signature_line(&repo, &e.hash)?
668
                    ))
669
                );
94084087 Andy McCall ↶ 670
            }
671
            if !c.deps.is_empty() {
75167672 Andy McCall 672
                println!(
2bf22305 Andy McCall ↶ 673
                    "{rail}{} {}",
75167672 Andy McCall 674
                    ui::dim(ui::glyph("↳", "->")),
675
                    ui::dim(deps_of(&c.deps))
676
                );
94084087 Andy McCall ↶ 677
            }
75167672 Andy McCall 678
            let body: Vec<&str> = c
679
                .message
680
                .lines()
681
                .skip(1)
682
                .skip_while(|l| l.trim().is_empty())
683
                .collect();
2bf22305 Andy McCall ↶ 684
            for line in body {
685
                println!("{rail}  {line}");
94084087 Andy McCall ↶ 686
            }
fce44ae9 Andy McCall ↶ 687
        }
688
    }
94084087 Andy McCall ↶ 689
    if shown < total {
2bf22305 Andy McCall ↶ 690
        if let Some(last) = rows.get(shown.saturating_sub(1)) {
691
            let cut: String = last
692
                .below
693
                .iter()
694
                .map(|c| match c {
695
                    Cell::Blank | Cell::Elided | Cell::JoinRight => "  ",
696
                    _ => "~ ",
697
                })
698
                .collect();
699
            if cut.trim().is_empty() {
700
                println!("{}", ui::dim("~"));
701
            } else {
702
                println!("{}", ui::dim(cut.trim_end()));
703
            }
704
        }
75167672 Andy McCall 705
        println!(
706
            "{}",
707
            ui::dim(format!(
708
                "{} {} more; pass -n to see them",
709
                ui::glyph("…", "..."),
710
                total - shown
711
            ))
712
        );
94084087 Andy McCall ↶ 713
    }
fce44ae9 Andy McCall ↶ 714
    Ok(0)
2bf22305 Andy McCall ↶ 715
}
716
717
/// Rows a drawn edge may span in `oxy log`; a longer one is elided (`~`).
718
const MAX_EDGE: usize = 12;
719
720
use oxy_core::hash::ChangeHash;
721
use oxy_core::lanes::{Cell, GraphRow};
722
723
/// A graph cell, two columns wide.
724
fn cell(c: Cell) -> &'static str {
725
    match c {
726
        Cell::Blank => "  ",
727
        Cell::Line => ui::glyph("│ ", "| "),
728
        Cell::Elided => "~ ",
729
        Cell::JoinLeft => ui::glyph("├─", "|-"),
730
        Cell::JoinPass => ui::glyph("──", "--"),
731
        Cell::JoinCross => ui::glyph("┼─", "+-"),
732
        Cell::JoinRight => ui::glyph("╯ ", "' "),
733
    }
734
}
735
736
/// The graph part of a change's own line, its bullet in its column.
737
fn node_line(row: &GraphRow, bullet: &str) -> String {
738
    let width = row
739
        .passing
740
        .iter()
741
        .copied()
742
        .max()
743
        .unwrap_or(0)
744
        .max(row.column)
745
        + 1;
746
    let mut out = String::new();
747
    for c in 0..width {
748
        if c == row.column {
749
            out.push_str(bullet);
750
            out.push(' ');
751
        } else if row.passing.contains(&c) {
752
            out.push_str(&ui::dim(cell(Cell::Line)));
753
        } else {
754
            out.push_str("  ");
755
        }
756
    }
757
    out.push(' ');
758
    out
759
}
760
761
/// The graph part of the line under a change: lanes carrying on, a join,
762
/// or `~` for an elided edge.
763
fn below_line(row: &GraphRow) -> String {
764
    let g: String = row.below.iter().map(|c| cell(*c)).collect();
765
    format!("{} ", ui::dim(g))
766
}
767
768
/// The graph part of any further line of a change (`-v`).
769
fn continuation(row: &GraphRow) -> String {
770
    let g: String = row
771
        .below
772
        .iter()
773
        .map(|c| match c {
774
            Cell::Line | Cell::JoinLeft | Cell::JoinCross => cell(Cell::Line),
775
            _ => "  ",
776
        })
777
        .collect();
778
    format!("{} ", ui::dim(g))
779
}
780
781
/// For each hex ID, the length of its shortest prefix no other ID shares.
782
fn unique_prefixes(ids: impl Iterator<Item = String>) -> std::collections::HashMap<String, usize> {
783
    let mut v: Vec<String> = ids.collect();
784
    v.sort();
785
    v.dedup();
786
    let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
787
    let mut out = std::collections::HashMap::with_capacity(v.len());
788
    for i in 0..v.len() {
789
        let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 };
790
        let after = if i + 1 < v.len() {
791
            common(&v[i], &v[i + 1])
792
        } else {
793
            0
794
        };
795
        out.insert(v[i].clone(), before.max(after) + 1);
796
    }
797
    out
798
}
799
800
/// Bookmark, remote bookmark and tag names to show beside the changes they
801
/// point at. A name is shown on each head of its state; one with more than
802
/// three heads names too much of the log to help, so it is left out (oxy
803
/// bookmark list shows it). A remote bookmark at the same state as the
804
/// local one of that name is not repeated.
805
fn reference_labels(repo: &Repo) -> Result<std::collections::HashMap<ChangeHash, Vec<String>>> {
806
    const MAX_HEADS: usize = 3;
807
    let view = repo.view()?;
808
    let mut out: std::collections::HashMap<ChangeHash, Vec<String>> = Default::default();
809
    let mut add = |heads: Vec<ChangeHash>, label: String| {
810
        if heads.len() <= MAX_HEADS {
811
            for h in heads {
812
                out.entry(h).or_default().push(label.clone());
813
            }
814
        }
815
    };
816
    for (name, st) in &view.bookmarks {
817
        add(repo.store().get_state(st)?.heads, ui::bookmark(name));
818
    }
819
    for (remote, bookmarks) in &view.remotes {
820
        for (name, st) in bookmarks {
821
            if view.bookmarks.get(name) == Some(st) {
822
                continue;
823
            }
824
            add(
825
                repo.store().get_state(st)?.heads,
826
                ui::dim(format!("{remote}/{name}")),
827
            );
828
        }
829
    }
830
    for t in repo.tags()? {
831
        add(t.heads.clone(), ui::warn(&t.name));
832
    }
833
    Ok(out)
fce44ae9 Andy McCall ↶ 834
}
835
c6aa5bd9 Andy McCall ↶ 836
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
837
    let repo = open()?;
838
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
839
    if as_json {
840
        let files = repo.diff_files(hash.as_ref())?;
841
        let items = files.iter().map(|f| {
842
            json::obj([
843
                ("path", json::s(&f.path)),
844
                ("kind", json::s(&f.kind)),
845
                ("from", json::opt(f.from.as_deref(), json::s)),
846
                (
847
                    "hunks",
848
                    json::arr(f.hunks.iter().map(|h| {
849
                        json::obj([
850
                            ("base_line", json::n(h.base_line)),
75167672 Andy McCall 851
                            (
852
                                "added",
853
                                json::arr(
854
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
855
                                ),
856
                            ),
857
                            (
858
                                "removed",
859
                                json::arr(h.removed.iter().map(|(n, l)| {
860
                                    json::obj([
861
                                        ("line", json::n(*n)),
862
                                        ("text", json::s(&String::from_utf8_lossy(l))),
863
                                    ])
864
                                })),
865
                            ),
c6aa5bd9 Andy McCall ↶ 866
                        ])
867
                    })),
868
                ),
869
            ])
870
        });
75167672 Andy McCall 871
        println!(
872
            "{}",
873
            json::obj([
874
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
875
                ("files", json::arr(items))
876
            ])
877
        );
c6aa5bd9 Andy McCall ↶ 878
        return Ok(0);
879
    }
880
    match hash {
881
        Some(h) => {
882
            let c = repo.store().get_change(&h)?;
8ab265dc Andy McCall ↶ 883
            let (base, snapshot) = repo.change_base(&c)?;
c6aa5bd9 Andy McCall ↶ 884
            print!("{}", render_change(&c, &base, &snapshot));
885
        }
886
        None => {
77445673 Andy McCall ↶ 887
            let (wc, base, snapshot) = repo.working_copy_with_base()?;
888
            print!("{}", render_change(&wc, &base, &snapshot));
c6aa5bd9 Andy McCall ↶ 889
        }
890
    }
891
    Ok(0)
892
}
893
894
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
895
    let repo = open()?;
896
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
897
    let bytes = repo.file_at(path, heads.as_deref())?;
898
    use std::io::Write as _;
899
    std::io::stdout().write_all(&bytes)?;
900
    Ok(0)
901
}
902
903
pub fn root(as_json: bool) -> Result<i32> {
904
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
905
        if as_json {
906
            println!("null");
907
        }
908
        return Ok(1);
909
    };
910
    if as_json {
75167672 Andy McCall 911
        println!(
912
            "{}",
913
            json::obj([
914
                ("root", json::s(&repo.root().to_string_lossy())),
915
                ("workspace", json::s(&repo.workspace().to_hex())),
916
                ("bookmark", json::s(&repo.config.bookmark))
917
            ])
918
        );
c6aa5bd9 Andy McCall ↶ 919
    } else {
920
        println!("{}", repo.root().display());
921
    }
922
    Ok(0)
923
}
924
925
pub fn version(as_json: bool) -> Result<i32> {
926
    if as_json {
75167672 Andy McCall 927
        println!(
928
            "{}",
929
            json::obj([
930
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
931
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
932
                ("format", json::n(2))
933
            ])
934
        );
c6aa5bd9 Andy McCall ↶ 935
    } else {
75167672 Andy McCall 936
        println!(
937
            "oxy {} (repository format 2, protocol {})",
938
            env!("CARGO_PKG_VERSION"),
939
            oxy_core::protocol::PROTOCOL_VERSION
940
        );
c6aa5bd9 Andy McCall ↶ 941
    }
942
    Ok(0)
943
}
944
945
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
946
    let repo = open()?;
947
    if paths.is_empty() && hunks.is_empty() {
948
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
949
    }
950
    let mut n = 0;
951
    if !hunks.is_empty() {
952
        n += repo.discard_hunks(hunks)?;
953
    }
954
    if !paths.is_empty() {
955
        n += repo.discard(paths)?;
956
    }
75167672 Andy McCall 957
    println!(
958
        "{} {} restored to the working copy's base",
959
        ui::done("Discarded"),
960
        plural(n, "path")
961
    );
c6aa5bd9 Andy McCall ↶ 962
    Ok(0)
963
}
964
965
pub fn hunks(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 966
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 967
    let (_, hunks) = repo.hunks()?;
968
    if as_json {
75167672 Andy McCall 969
        println!(
970
            "{}",
971
            json::arr(hunks.iter().map(|h| json::obj([
972
                ("index", json::n(h.index)),
973
                ("path", json::s(&h.path)),
974
                ("text", json::s(&h.text))
975
            ])))
976
        );
c6aa5bd9 Andy McCall ↶ 977
        return Ok(0);
978
    }
979
    if hunks.is_empty() {
75167672 Andy McCall 980
        println!(
981
            "{}",
982
            ui::dim("No hunks: the working copy matches its base.")
983
        );
c6aa5bd9 Andy McCall ↶ 984
    }
985
    for h in &hunks {
75167672 Andy McCall 986
        println!(
987
            "{} {}",
988
            ui::section(format!("hunk {}", h.index)),
989
            ui::path(&h.path)
990
        );
c6aa5bd9 Andy McCall ↶ 991
        for line in h.text.lines() {
75167672 Andy McCall 992
            let styled = if line.starts_with('+') {
993
                ui::ok(line)
994
            } else if line.starts_with('-') {
995
                ui::err(line)
996
            } else {
997
                ui::dim(line)
998
            };
c6aa5bd9 Andy McCall ↶ 999
            println!("  {styled}");
1000
        }
1001
    }
fce44ae9 Andy McCall ↶ 1002
    Ok(0)
1003
}
1004
c6aa5bd9 Andy McCall ↶ 1005
pub fn show(change: &str, as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 1006
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1007
    repo.snapshot_status("oxy show")?;
fce44ae9 Andy McCall ↶ 1008
    let h = repo.resolve_change(change)?;
1009
    let c = repo.store().get_change(&h)?;
c6aa5bd9 Andy McCall ↶ 1010
    if as_json {
1011
        let files = repo.diff_files(Some(&h))?;
1012
        let heads = repo.bookmark_heads()?;
75167672 Andy McCall 1013
        let entry = oxy_core::repo::LogEntry {
1014
            hash: h,
1015
            change: oxy_core::state::ChangeMeta::of(&c),
1016
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
1017
            is_head: heads.contains(&h),
1018
        };
c6aa5bd9 Andy McCall ↶ 1019
        let mut body = log_entry_json(&repo, &entry)?;
1020
        body.pop();
75167672 Andy McCall 1021
        body.push_str(&format!(
1022
            ",{}:{}}}",
1023
            json::s("files"),
1024
            json::arr(files.iter().map(|f| json::obj([
1025
                ("path", json::s(&f.path)),
1026
                ("kind", json::s(&f.kind)),
1027
                ("from", json::opt(f.from.as_deref(), json::s))
1028
            ])))
1029
        ));
c6aa5bd9 Andy McCall ↶ 1030
        println!("{body}");
1031
        return Ok(0);
1032
    }
75167672 Andy McCall 1033
    println!(
1034
        "{} {} {}",
1035
        ui::section("change"),
1036
        ui::id(short_id(&c)),
1037
        ui::hash(format!("#{h}"))
1038
    );
94084087 Andy McCall ↶ 1039
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
75167672 Andy McCall 1040
    println!(
1041
        "{}",
1042
        ui::kv(
1043
            "author",
1044
            ui::author(author_name(&repo, &oxy_core::state::ChangeMeta::of(&c)))
1045
        )
1046
    );
1047
    println!(
1048
        "{}",
1049
        ui::kv(
1050
            "date",
1051
            format!(
1052
                "{} {}",
1053
                when(c.hlc.wall_ms),
1054
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1055
            )
1056
        )
1057
    );
94084087 Andy McCall ↶ 1058
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
1059
    println!("{}", ui::kv("sig", signature_line(&repo, &h)?));
1060
    println!();
75167672 Andy McCall 1061
    for line in (if c.message.is_empty() {
1062
        "(no description)"
1063
    } else {
1064
        &c.message
1065
    })
1066
    .lines()
1067
    {
94084087 Andy McCall ↶ 1068
        println!("    {line}");
1069
    }
1070
    println!();
fce44ae9 Andy McCall ↶ 1071
    print!("{}", repo.describe_change(&h)?);
1072
    Ok(0)
1073
}
1074
1c2bd9ab Andy McCall ↶ 1075
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 1076
    let repo = open()?;
1077
    let heads = if changes.is_empty() {
1078
        repo.bookmark_heads()?
1079
    } else {
132b884b Andy McCall ↶ 1080
        let mut heads = Vec::new();
1081
        for c in changes {
1082
            heads.extend(repo.resolve_heads(c)?);
1083
        }
1084
        heads
fce44ae9 Andy McCall ↶ 1085
    };
75167672 Andy McCall 1086
    let spec = if changes.is_empty() {
1087
        repo.config.bookmark.clone()
1088
    } else {
1089
        changes.join(" ")
1090
    };
135212de Andy McCall ↶ 1091
    let sp = ui::spinner(&format!("Checking out {spec}…"));
1c2bd9ab Andy McCall ↶ 1092
    let command = format!("oxy checkout {spec}");
1093
    let (r, carried) = if carry {
1094
        repo.checkout_carry(&heads, &spec, &command)?
1095
    } else {
1096
        (repo.checkout(&heads, discard, &command)?, vec![])
1097
    };
75167672 Andy McCall 1098
    sp.done(&format!(
1c2bd9ab Andy McCall ↶ 1099
        "{} on {}: {} written, {} removed{}",
75167672 Andy McCall 1100
        ui::done("Working copy"),
1101
        ui::bookmark(&spec),
1102
        plural(r.written, "file"),
1c2bd9ab Andy McCall ↶ 1103
        r.removed,
1104
        if carried.is_empty() {
1105
            String::new()
1106
        } else {
1107
            format!("; carried {}", plural(carried.len(), "changed path"))
1108
        }
75167672 Andy McCall 1109
    ));
4dee277c Andy McCall ↶ 1110
    for n in &r.notes {
1111
        println!("  {} {n}", ui::note());
1112
    }
fce44ae9 Andy McCall ↶ 1113
    if r.conflicted {
75167672 Andy McCall 1114
        println!(
1115
            "  {} {}",
1116
            ui::caution(),
1117
            ui::warn("this state has conflicts; see oxy status")
1118
        );
fce44ae9 Andy McCall ↶ 1119
    }
98a1620a Andy McCall ↶ 1120
    where_now(&repo);
fce44ae9 Andy McCall ↶ 1121
    Ok(0)
1122
}
1123
c6aa5bd9 Andy McCall ↶ 1124
pub fn resolve(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 1125
    let repo = open()?;
1126
    let snap = repo.snapshot("oxy resolve")?;
c6aa5bd9 Andy McCall ↶ 1127
    if as_json {
1128
        println!("{}", repo.status_json(&snap)?);
75167672 Andy McCall 1129
        return Ok(if snap.base_snapshot.is_conflicted() {
1130
            2
1131
        } else {
1132
            0
1133
        });
c6aa5bd9 Andy McCall ↶ 1134
    }
fce44ae9 Andy McCall ↶ 1135
    if !snap.base_snapshot.is_conflicted() {
1136
        println!("The working copy's base has no conflicts.");
1137
        return Ok(0);
1138
    }
1139
    let mut remaining = 0;
1140
    for (p, f) in &snap.base_snapshot.files {
1141
        if !f.is_conflicted() {
1142
            continue;
1143
        }
75167672 Andy McCall 1144
        match snap
1145
            .statuses
1146
            .iter()
1147
            .find(|s| s.path == *p)
1148
            .map(|s| s.status)
1149
        {
fce44ae9 Andy McCall ↶ 1150
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
1151
            Some(ChangeStatus::ConflictEdited) => {
1152
                remaining += 1;
1153
                println!("markers    {p}");
1154
            }
1155
            _ => {
1156
                remaining += 1;
1157
                println!("unresolved {p}");
1158
            }
1159
        }
1160
    }
1161
    for c in &snap.base_snapshot.tree.conflicts {
1162
        remaining += 1;
1163
        println!("tree       {c:?}");
1164
    }
1165
    if remaining == 0 {
1166
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
1167
        Ok(0)
1168
    } else {
1169
        Ok(2)
1170
    }
1171
}
1172
1173
pub fn undo() -> Result<i32> {
1174
    let repo = open()?;
1175
    let op = repo.undo()?;
94084087 Andy McCall ↶ 1176
    println!("{} now at: {}", ui::done("Undone;"), ui::dim(&op.command));
98a1620a Andy McCall ↶ 1177
    where_now(&repo);
fce44ae9 Andy McCall ↶ 1178
    Ok(0)
1179
}
1180
98a1620a Andy McCall ↶ 1181
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 1182
    let repo = open()?;
98a1620a Andy McCall ↶ 1183
    let ops = repo.op_log()?;
1184
    // What each operation changed, against the one before it.
1185
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
1186
        match ops.get(i + 1) {
1187
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
1188
            None => Ok(vec![]),
1189
        }
1190
    };
c6aa5bd9 Andy McCall ↶ 1191
    if as_json {
98a1620a Andy McCall ↶ 1192
        let mut items = Vec::new();
1193
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
1194
            let summary: Vec<String> = changes_of(i)?
1195
                .iter()
1196
                .map(|c| change_words(&repo, c))
1197
                .collect();
1198
            items.push(json::obj([
1199
                ("id", json::s(&r.to_hex())),
1200
                ("when_ms", json::n(op.hlc.wall_ms)),
1201
                ("command", json::s(&op.command)),
1202
                ("snapshot", json::b(op.is_snapshot())),
1203
                ("current", json::b(i == 0)),
1204
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1205
            ]));
1206
        }
1207
        println!("{}", json::arr(items));
c6aa5bd9 Andy McCall ↶ 1208
        return Ok(0);
1209
    }
98a1620a Andy McCall ↶ 1210
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
1211
    let id = |r: &oxy_core::hash::ObjectRef| {
1212
        let hex = r.to_hex();
1213
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
1214
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
1215
    };
1216
    let rail = ui::dim(ui::glyph("│", "|"));
1217
    let (mut i, mut shown) = (0, 0);
1218
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
1219
        let (r, op) = &ops[i];
75167672 Andy McCall 1220
        let bullet = if i == 0 {
98a1620a Andy McCall ↶ 1221
            ui::ok(ui::glyph("@", "@"))
75167672 Andy McCall 1222
        } else {
1223
            ui::dim(ui::glyph("○", "o"))
1224
        };
98a1620a Andy McCall ↶ 1225
        // A run of snapshots folds into one entry.
1226
        let mut run = 1;
1227
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
1228
            run += 1;
1229
        }
1230
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
1231
        if op.is_snapshot() {
1232
            let span = if run > 1 {
1233
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1234
            } else {
1235
                String::new()
1236
            };
1237
            println!(
1238
                "{bullet}  {}{} {when}",
1239
                id(r),
1240
                if span.is_empty() {
1241
                    String::new()
1242
                } else {
1243
                    format!(" {span}")
1244
                }
1245
            );
1246
            println!(
1247
                "{rail}  {}",
1248
                ui::dim(if run == 1 {
1249
                    "working-copy snapshot".to_string()
1250
                } else {
1251
                    format!("{run} working-copy snapshots")
1252
                })
1253
            );
1254
        } else {
1255
            println!("{bullet}  {} {when}", id(r));
1256
            let words: Vec<String> = changes_of(i)?
1257
                .iter()
1258
                .map(|c| change_words(&repo, c))
1259
                .collect();
1260
            let summary = if words.is_empty() {
1261
                if i + 1 == ops.len() {
1262
                    "created the repository".to_string()
1263
                } else {
1264
                    "no bookmark or working-copy change".to_string()
1265
                }
1266
            } else {
1267
                words.join("; ")
1268
            };
1269
            println!(
1270
                "{rail}  {}",
1271
                if i == 0 {
1272
                    ui::subject(&summary)
1273
                } else {
1274
                    summary
1275
                }
1276
            );
1277
            let cmd = op.command.lines().next().unwrap_or("");
1278
            let cmd: String = cmd.chars().take(100).collect();
1279
            println!("{rail}  {}", ui::dim(cmd));
1280
        }
1281
        i += run;
1282
        shown += 1;
1283
    }
1284
    if i < ops.len() {
75167672 Andy McCall 1285
        println!(
98a1620a Andy McCall ↶ 1286
            "{}",
1287
            ui::dim(format!(
1288
                "{} {} older; pass -n to see more",
1289
                ui::glyph("…", "..."),
1290
                plural(ops.len() - i, "operation")
1291
            ))
1292
        );
1293
    }
1294
    Ok(0)
1295
}
1296
1297
/// One change an operation made, in words.
1298
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1299
    use oxy_core::repo::ViewChange::*;
1300
    match c {
1301
        BookmarkCreated { name, heads } => {
1302
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1303
        }
1304
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
1305
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
1306
        BookmarkMoved { name, from, to } => format!(
1307
            "{name}: {from} {} {}",
1308
            ui::glyph("→", "->"),
1309
            plural(*to, "head")
1310
        ),
1311
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
1312
        TagCreated { name } => format!("tagged {name}"),
1313
        TagDeleted { name } => format!("removed tag {name}"),
1314
        Policy => "trust policy changed".to_string(),
1315
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
1316
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
1317
            Err(_) => "working copy moved".to_string(),
1318
        },
1319
    }
1320
}
1321
1322
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
1323
    let repo = open()?;
1324
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
1325
    let r = repo.op_restore(op, discard)?;
1326
    sp.done(&format!(
1327
        "{} to operation {} {}",
1328
        ui::done("Restored"),
1329
        ui::hash(r.op.short(12)),
1330
        ui::dim(r.command.lines().next().unwrap_or(""))
1331
    ));
1332
    println!(
1333
        "  {} {}",
1334
        ui::note(),
1335
        ui::dim(format!(
1336
            "{} written, {} removed; oxy undo goes back again",
1337
            plural(r.checkout.written, "file"),
1338
            r.checkout.removed
1339
        ))
1340
    );
1341
    where_now(&repo);
1342
    Ok(0)
1343
}
1344
1345
pub fn op_revert(op: &str) -> Result<i32> {
1346
    let repo = open()?;
1347
    let r = repo.op_revert(op)?;
1348
    let view = repo.view()?;
1349
    let names: Vec<String> = r
1350
        .reverted
1351
        .iter()
1352
        .map(|n| {
1353
            if view.bookmarks.contains_key(n) {
1354
                ui::bookmark(n)
75167672 Andy McCall 1355
            } else {
98a1620a Andy McCall ↶ 1356
                format!("{} (removed)", ui::bookmark(n))
75167672 Andy McCall 1357
            }
98a1620a Andy McCall ↶ 1358
        })
1359
        .collect();
1360
    println!(
1361
        "{} operation {} {}",
1362
        ui::done("Reverted"),
1363
        ui::hash(r.op.short(12)),
1364
        ui::dim(r.command.lines().next().unwrap_or(""))
1365
    );
1366
    println!(
1367
        "  {} {}",
1368
        ui::note(),
1369
        ui::dim(format!("as before it: {}", names.join(", ")))
1370
    );
1371
    if !r.kept.is_empty() {
1372
        println!(
1373
            "  {} {}",
1374
            ui::caution(),
1375
            ui::warn(format!(
1376
                "left as they are, having moved again since: {}",
1377
                r.kept.join(", ")
1378
            ))
75167672 Andy McCall 1379
        );
fce44ae9 Andy McCall ↶ 1380
    }
98a1620a Andy McCall ↶ 1381
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
1382
        println!(
1383
            "  {} {}",
1384
            ui::note(),
1385
            ui::dim("the working copy has work of its own: oxy checkout to move it")
1386
        );
1387
    }
1388
    where_now(&repo);
fce44ae9 Andy McCall ↶ 1389
    Ok(0)
98a1620a Andy McCall ↶ 1390
}
1391
1392
/// Where the working copy and bookmark are now, after a command moved
1393
/// them (as jj says "Working copy now at").
1394
pub fn where_now(repo: &Repo) {
1395
    let Ok((_, wc)) = repo.working_copy() else {
1396
        return;
1397
    };
1398
    let heads = repo.bookmark_heads().unwrap_or_default();
1399
    let newest = heads
1400
        .iter()
1401
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
1402
        .max_by_key(|(m, _)| m.hlc);
1403
    println!(
1404
        "  {} {}",
1405
        ui::dim(format!("{:<13}", "Working copy")),
1406
        ui::id(wc.change_id.short(8))
1407
    );
1408
    let tail = match newest {
1409
        Some((m, _)) => format!(
1410
            ", newest {} {}",
1411
            ui::id(m.change_id.short(8)),
1412
            subject_of(&m.message)
1413
        ),
1414
        None => String::new(),
1415
    };
1416
    println!(
1417
        "  {} {}: {}{tail}",
1418
        ui::dim(format!("{:<13}", "Bookmark")),
1419
        ui::bookmark(&repo.config.bookmark),
1420
        plural(heads.len(), "head")
1421
    );
fce44ae9 Andy McCall ↶ 1422
}
d02e545d Andy McCall ↶ 1423
ba160f60 Andy McCall ↶ 1424
pub fn gc(now: bool) -> Result<i32> {
d02e545d Andy McCall ↶ 1425
    let repo = open()?;
135212de Andy McCall ↶ 1426
    let sp = ui::spinner("Packing and pruning…");
ba160f60 Andy McCall ↶ 1427
    let r = repo.gc(now)?;
135212de Andy McCall ↶ 1428
    sp.clear();
ba160f60 Andy McCall ↶ 1429
    if r.packed.objects > 0 {
d02e545d Andy McCall ↶ 1430
        println!(
da652d63 Andy McCall ↶ 1431
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
1432
            plural(r.packed.objects, "object"),
ba160f60 Andy McCall ↶ 1433
            r.packed.raw_bytes,
1434
            r.packed.packed_bytes,
1435
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
d02e545d Andy McCall ↶ 1436
        );
1437
    }
75167672 Andy McCall 1438
    println!(
1439
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
ba160f60 Andy McCall ↶ 1440
        plural(r.reachable, "object"),
1441
        plural(r.pruned.objects, "unreachable object"),
1442
        r.pruned.bytes,
75167672 Andy McCall 1443
        if r.pruned.deferred > 0 {
1444
            format!(
1445
                "; {} deferred by the grace period (use --now)",
1446
                plural(r.pruned.deferred, "object")
1447
            )
1448
        } else {
1449
            String::new()
1450
        },
1451
        if r.merged_packs > 0 {
1452
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1453
        } else {
1454
            String::new()
1455
        },
ba160f60 Andy McCall ↶ 1456
        plural(repo.store().pack_count(), "pack")
1457
    );
d02e545d Andy McCall ↶ 1458
    Ok(0)
1459
}
614541c3 Andy McCall ↶ 1460
3e5772cc Andy McCall ↶ 1461
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
1462
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1463
    use oxy_core::repo::Health;
1464
    let repo = open()?;
1465
    let sp = ui::spinner(if offline {
1466
        "Checking…"
1467
    } else {
1468
        "Checking, and contacting remotes…"
1469
    });
1470
    let r = repo.doctor(!offline);
1471
    sp.clear();
1472
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
1473
    let word = |h: Health| match h {
1474
        Health::Ok => "ok",
1475
        Health::Warn => "warning",
1476
        Health::Fail => "fail",
1477
    };
1478
    if as_json {
1479
        let checks: Vec<String> = r
1480
            .checks
1481
            .iter()
1482
            .map(|c| {
1483
                json::obj([
1484
                    ("area", json::s(&c.area)),
1485
                    ("health", json::s(word(c.health))),
1486
                    ("message", json::s(&c.message)),
1487
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
1488
                ])
1489
            })
1490
            .collect();
1491
        println!(
1492
            "{}",
1493
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1494
        );
1495
        return Ok(code);
1496
    }
1497
    let mut last = "";
1498
    for c in &r.checks {
1499
        if c.area != last {
1500
            println!("{}", ui::section(&c.area));
1501
            last = &c.area;
1502
        }
1503
        let mark = match c.health {
1504
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
1505
            Health::Warn => ui::caution(),
1506
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1507
        };
1508
        println!("  {mark} {}", c.message);
1509
        if let Some(h) = &c.hint {
1510
            println!("    {} {}", ui::dim("→"), ui::dim(h));
1511
        }
1512
    }
1513
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
1514
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
1515
    if fails + warns == 0 {
1516
        println!("{}", ui::done("Everything looks right."));
1517
    } else {
1518
        println!(
1519
            "{} {}, {}.",
1520
            if fails > 0 {
1521
                ui::err(ui::glyph("✖", "x"))
1522
            } else {
1523
                ui::caution()
1524
            },
1525
            plural(fails, "problem"),
1526
            plural(warns, "warning")
1527
        );
1528
    }
1529
    Ok(code)
1530
}
1531
387335ff Andy McCall ↶ 1532
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
1533
pub fn fsck(as_json: bool) -> Result<i32> {
1534
    use oxy_core::repo::Severity;
1535
    let repo = open()?;
1536
    let sp = ui::spinner("Checking every object…");
1537
    let r = repo.fsck()?;
1538
    sp.clear();
1539
    let code = if r.errors() > 0 { 1 } else { 0 };
1540
    if as_json {
1541
        let problems: Vec<String> = r
1542
            .problems
1543
            .iter()
1544
            .map(|p| {
1545
                json::obj([
1546
                    (
1547
                        "severity",
1548
                        json::s(match p.severity {
1549
                            Severity::Error => "error",
1550
                            Severity::Warning => "warning",
1551
                        }),
1552
                    ),
1553
                    (
1554
                        "object",
1555
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1556
                    ),
1557
                    ("what", json::s(&p.what)),
1558
                ])
1559
            })
1560
            .collect();
1561
        println!(
1562
            "{}",
1563
            json::obj([
1564
                ("ok", json::b(code == 0)),
1565
                ("objects", json::n(r.objects)),
1566
                ("ops", json::n(r.ops)),
1567
                ("changes", json::n(r.changes)),
1568
                ("signed", json::n(r.signed)),
1569
                ("unsigned", json::n(r.unsigned)),
1570
                ("checkpoints", json::n(r.checkpoints)),
1571
                ("attestations", json::n(r.attestations)),
1572
                ("errors", json::n(r.errors())),
1573
                ("warnings", json::n(r.warnings())),
1574
                ("problems", json::arr(problems)),
1575
            ])
1576
        );
1577
        return Ok(code);
1578
    }
1579
    println!(
1580
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
1581
        plural(r.objects, "object"),
1582
        plural(r.ops, "operation"),
1583
        plural(r.changes, "change"),
1584
        r.signed,
1585
        r.unsigned,
1586
        plural(r.checkpoints, "checkpoint"),
1587
        plural(r.attestations, "attestation"),
1588
    );
1589
    for p in &r.problems {
1590
        let obj = p
1591
            .object
1592
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
1593
            .unwrap_or_default();
1594
        match p.severity {
1595
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
1596
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1597
        }
1598
    }
1599
    if r.problems.is_empty() {
1600
        println!("{}", ui::done("No problems found."));
1601
    } else if code == 0 {
1602
        println!(
1603
            "{}",
1604
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
1605
        );
1606
    } else {
1607
        println!(
1608
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
1609
            ui::err(ui::glyph("✖", "x")),
1610
            plural(r.errors(), "error"),
1611
            plural(r.warnings(), "warning")
1612
        );
1613
    }
1614
    Ok(code)
1615
}
1616
79d03f82 Andy McCall ↶ 1617
/// The head the working copy sits on, for commands that default to it. With
1618
/// several heads beneath the working copy, the most recently made one is
1619
/// chosen and announced.
614541c3 Andy McCall ↶ 1620
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
cc7a0056 Andy McCall ↶ 1621
    let snap = repo.snapshot_status("oxy")?;
614541c3 Andy McCall ↶ 1622
    let base = snap.base.maximal(&snap.wc.deps);
1623
    match base.as_slice() {
79d03f82 Andy McCall ↶ 1624
        [] => anyhow::bail!("the working copy sits on no change yet"),
614541c3 Andy McCall ↶ 1625
        [h] => Ok(*h),
79d03f82 Andy McCall ↶ 1626
        many => {
1627
            let latest = many
1628
                .iter()
1629
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
1630
                .copied()
1631
                .unwrap();
1632
            let c = repo.store().get_change(&latest)?;
75167672 Andy McCall 1633
            println!(
1634
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
1635
                short_id(&c),
1636
                latest.short(12),
1637
                many.len()
1638
            );
79d03f82 Andy McCall ↶ 1639
            Ok(latest)
1640
        }
614541c3 Andy McCall ↶ 1641
    }
1642
}
1643
6a81dbab Andy McCall ↶ 1644
/// `oxy describe` without -m: the working copy's name for a build.
1645
pub fn describe_name(as_json: bool) -> Result<i32> {
1646
    let repo = open()?;
1647
    let d = repo.describe_working_copy()?;
1648
    if as_json {
1649
        println!(
1650
            "{}",
1651
            json::obj([
1652
                ("describe", json::s(&d.line())),
1653
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
1654
                ("distance", json::n(d.distance)),
1655
                ("bookmark", json::s(&d.bookmark)),
1656
                ("change", json::s(&d.change.to_hex())),
1657
                ("hash", json::s(&d.hash.to_hex())),
1658
                ("dirty", json::b(d.dirty)),
1659
            ])
1660
        );
1661
    } else {
1662
        println!("{}", d.line());
1663
    }
1664
    Ok(0)
1665
}
1666
614541c3 Andy McCall ↶ 1667
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
1668
    let repo = open()?;
1669
    let h = match change {
1670
        Some(c) => repo.resolve_change(c)?,
1671
        None => current_head(&repo)?,
1672
    };
1673
    let new = repo.describe(&h, message)?;
1674
    let c = repo.store().get_change(&new)?;
75167672 Andy McCall 1675
    println!(
1676
        "{} {} {}  {}",
1677
        ui::done("Described"),
1678
        ui::id(short_id(&c)),
1679
        ui::hash(format!("#{}", new.short(12))),
1680
        ui::subject(subject_of(message))
1681
    );
614541c3 Andy McCall ↶ 1682
    Ok(0)
1683
}
1684
23b217d7 Andy McCall ↶ 1685
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
614541c3 Andy McCall ↶ 1686
    let repo = open()?;
23b217d7 Andy McCall ↶ 1687
    let new = match into {
1688
        Some(spec) => {
1689
            let target = repo.resolve_change(spec)?;
1690
            repo.amend_into(&target, message)?
1691
        }
1692
        None => repo.amend(message)?,
1693
    };
614541c3 Andy McCall ↶ 1694
    let c = repo.store().get_change(&new)?;
75167672 Andy McCall 1695
    println!(
1696
        "{} {} {}  {}",
1697
        ui::done("Amended"),
1698
        ui::id(short_id(&c)),
1699
        ui::hash(format!("#{}", new.short(12))),
1700
        ui::subject(subject_of(&c.message))
1701
    );
98a1620a Andy McCall ↶ 1702
    where_now(&repo);
614541c3 Andy McCall ↶ 1703
    Ok(0)
1704
}
1705
1706
pub fn abandon(change: &str) -> Result<i32> {
1707
    let repo = open()?;
1708
    let h = repo.resolve_change(change)?;
1709
    let c = repo.store().get_change(&h)?;
6706bdcf Andy McCall ↶ 1710
    let notes = repo.abandon(&h)?;
75167672 Andy McCall 1711
    println!(
1712
        "{} {} {}  {}",
1713
        ui::done("Abandoned"),
1714
        ui::id(short_id(&c)),
1715
        ui::hash(format!("#{}", h.short(12))),
1716
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
1717
    );
6706bdcf Andy McCall ↶ 1718
    for n in notes {
94084087 Andy McCall ↶ 1719
        println!("  {} {n}", ui::note());
6706bdcf Andy McCall ↶ 1720
    }
98a1620a Andy McCall ↶ 1721
    where_now(&repo);
614541c3 Andy McCall ↶ 1722
    Ok(0)
1723
}
252e8cb2 Andy McCall ↶ 1724
1725
pub fn checkpoint() -> Result<i32> {
1726
    let repo = open()?;
135212de Andy McCall ↶ 1727
    let sp = ui::spinner("Writing checkpoint…");
252e8cb2 Andy McCall ↶ 1728
    let (r, changes, bytes) = repo.checkpoint()?;
75167672 Andy McCall 1729
    sp.done(&format!(
1730
        "{} {} of {} ({} bytes) for {}",
1731
        ui::done("Checkpoint"),
1732
        ui::hash(format!("#{}", r.short(12))),
1733
        plural(changes, "change"),
1734
        bytes,
1735
        ui::id(&repo.config.bookmark)
1736
    ));
135212de Andy McCall ↶ 1737
    Ok(0)
1738
}
1739
1740
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
694805cc Andy McCall ↶ 1741
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
75167672 Andy McCall 1742
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
1743
        return Ok(1);
1744
    };
135212de Andy McCall ↶ 1745
    let info = repo.quick_status()?;
75167672 Andy McCall 1746
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
1747
        oxy_core::repo::GLYPH_PROMPT_FORMAT
1748
    } else {
1749
        format
1750
    };
694805cc Andy McCall ↶ 1751
    let line = match color {
1752
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
1753
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
1754
        Some(_) => info.format_colored(fmt, ("", "")),
1755
        None => info.format(fmt),
1756
    };
1757
    println!("{line}");
252e8cb2 Andy McCall ↶ 1758
    Ok(0)
1759
}
7421309f Andy McCall ↶ 1760
1761
pub fn sparse(paths: &[String]) -> Result<i32> {
1762
    let mut repo = open()?;
1763
    if paths.is_empty() {
1764
        if repo.config.sparse_paths.is_empty() {
1765
            println!("No sparse filter: the whole tree is materialized.");
1766
        } else {
1767
            println!("{}", ui::heading("Sparse filter"));
1768
            for p in &repo.config.sparse_paths {
1769
                println!("  {}", ui::path(p));
1770
            }
1771
        }
1772
        return Ok(0);
1773
    }
1774
    let snap = repo.snapshot("oxy sparse")?;
1775
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
75167672 Andy McCall 1776
        anyhow::bail!(
1777
            "the working copy has changes; commit them before changing the sparse filter"
1778
        );
7421309f Andy McCall ↶ 1779
    }
1780
    repo.config.set("filter.paths", &paths.join(","))?;
1781
    repo.save_config()?;
1782
    let heads = repo.bookmark_heads()?;
1783
    let sp = ui::spinner("Re-checking out with the new filter…");
1784
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
75167672 Andy McCall 1785
    sp.done(&format!(
1786
        "{} {}: {} written, {} removed",
c07406bc Andy McCall ↶ 1787
        ui::done("Sparse filter set to"),
75167672 Andy McCall 1788
        ui::path(paths.join(",")),
1789
        plural(r.written, "file"),
1790
        r.removed
1791
    ));
7421309f Andy McCall ↶ 1792
    Ok(0)
1793
}
132b884b Andy McCall ↶ 1794
1795
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
1796
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1797
    repo.snapshot_status("oxy tag")?;
132b884b Andy McCall ↶ 1798
    let heads = if changes.is_empty() {
1799
        repo.bookmark_heads()?
1800
    } else {
1801
        let mut heads = Vec::new();
1802
        for c in changes {
1803
            heads.extend(repo.resolve_heads(c)?);
1804
        }
1805
        heads
1806
    };
1807
    let t = repo.tag_create(name, &heads, message)?;
1808
    println!(
94084087 Andy McCall ↶ 1809
        "{} {} {} {} ({}){}",
1810
        ui::done("Tagged"),
1811
        ui::bookmark(&t.name),
1812
        ui::dim(ui::glyph("→", "->")),
132b884b Andy McCall ↶ 1813
        ui::hash(format!("#{}", t.state.short(12))),
1814
        plural(t.heads.len(), "head"),
75167672 Andy McCall 1815
        t.signer
1816
            .map(|s| format!(", signed by {s}"))
1817
            .unwrap_or_else(|| ui::dim(", unsigned"))
132b884b Andy McCall ↶ 1818
    );
1819
    Ok(0)
1820
}
1821
1196b29b Andy McCall ↶ 1822
pub fn tag_list(as_json: bool) -> Result<i32> {
132b884b Andy McCall ↶ 1823
    let repo = open()?;
1824
    let tags = repo.tags()?;
1196b29b Andy McCall ↶ 1825
    if as_json {
1826
        println!(
1827
            "{}",
1828
            json::arr(tags.iter().map(|t| {
1829
                json::obj([
1830
                    ("name", json::s(&t.name)),
1831
                    ("state", json::s(&t.state.to_hex())),
1832
                    ("heads", json::hashes(&t.heads)),
1833
                    ("message", json::s(&t.message)),
75167672 Andy McCall 1834
                    (
1835
                        "signer",
1836
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
1837
                    ),
1196b29b Andy McCall ↶ 1838
                ])
1839
            }))
1840
        );
1841
        return Ok(0);
1842
    }
132b884b Andy McCall ↶ 1843
    if tags.is_empty() {
1844
        println!("{}", ui::dim("No tags."));
1845
    }
1846
    for t in tags {
1847
        println!(
94084087 Andy McCall ↶ 1848
            "{} {} {}{}{}{}",
1849
            ui::ok(ui::glyph("⚑", "#")),
1850
            ui::bookmark(&t.name),
6a81dbab Andy McCall ↶ 1851
            // The heads, as `oxy log` shows changes, not the state hash.
1852
            ui::hash(
1853
                t.heads
1854
                    .iter()
1855
                    .map(|h| format!("#{}", h.short(12)))
1856
                    .collect::<Vec<_>>()
1857
                    .join(" ")
1858
            ),
94084087 Andy McCall ↶ 1859
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
75167672 Andy McCall 1860
            if t.message.is_empty() {
1861
                String::new()
1862
            } else {
1863
                format!("  {}", ui::subject(subject_of(&t.message)))
1864
            },
1865
            t.signer
1866
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
1867
                .unwrap_or_default()
132b884b Andy McCall ↶ 1868
        );
1869
    }
1870
    Ok(0)
1871
}
4e88e774 Andy McCall ↶ 1872
1873
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
1874
    let repo = open()?;
1875
    let heads = if changes.is_empty() {
1876
        None
1877
    } else {
1878
        let mut heads = Vec::new();
1879
        for c in changes {
1880
            heads.extend(repo.resolve_heads(c)?);
1881
        }
1882
        Some(heads)
1883
    };
1884
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
1885
    let ws = repo.workspace_add(path, heads.as_deref())?;
75167672 Andy McCall 1886
    sp.done(&format!(
1887
        "{} {} (workspace {})",
1888
        ui::done("Workspace created at"),
1889
        ui::path(ws.root().display()),
1890
        ui::id(ws.workspace().short(8))
1891
    ));
4e88e774 Andy McCall ↶ 1892
    Ok(0)
1893
}
1894
1196b29b Andy McCall ↶ 1895
pub fn workspace_list(as_json: bool) -> Result<i32> {
4e88e774 Andy McCall ↶ 1896
    let repo = open()?;
1196b29b Andy McCall ↶ 1897
    if as_json {
1898
        println!(
1899
            "{}",
1900
            json::arr(repo.workspaces()?.iter().map(|w| {
1901
                json::obj([
1902
                    ("id", json::s(&w.id.to_hex())),
1903
                    ("path", json::s(&w.path.to_string_lossy())),
1904
                    ("current", json::b(w.current)),
75167672 Andy McCall 1905
                    (
1906
                        "working_copy",
1907
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
1908
                    ),
1196b29b Andy McCall ↶ 1909
                ])
1910
            }))
1911
        );
1912
        return Ok(0);
1913
    }
4e88e774 Andy McCall ↶ 1914
    for w in repo.workspaces()? {
1915
        println!(
1916
            "{} {} {}{}",
75167672 Andy McCall 1917
            if w.current {
1918
                ui::ok(ui::glyph("●", "*"))
1919
            } else {
1920
                ui::dim(ui::glyph("○", "o"))
1921
            },
4e88e774 Andy McCall ↶ 1922
            ui::id(w.id.short(8)),
1923
            ui::path(w.path.display()),
75167672 Andy McCall 1924
            w.working_copy
1925
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
1926
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
4e88e774 Andy McCall ↶ 1927
        );
1928
    }
1929
    Ok(0)
1930
}
1931
1932
pub fn workspace_forget(spec: &str) -> Result<i32> {
1933
    let repo = open()?;
1934
    let all = repo.workspaces()?;
1935
    let target = std::fs::canonicalize(spec).ok();
75167672 Andy McCall 1936
    let matches: Vec<_> = all
1937
        .iter()
1938
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
1939
        .collect();
4e88e774 Andy McCall ↶ 1940
    let w = match matches.as_slice() {
1941
        [w] => *w,
1942
        [] => anyhow::bail!("no workspace matches {spec:?}"),
1943
        _ => anyhow::bail!("{spec:?} is ambiguous"),
1944
    };
1945
    repo.workspace_forget(&w.id)?;
75167672 Andy McCall 1946
    println!(
1947
        "{} workspace {} at {}; its files were left in place.",
1948
        ui::done("Forgot"),
1949
        ui::id(w.id.short(8)),
1950
        ui::path(w.path.display())
1951
    );
4e88e774 Andy McCall ↶ 1952
    Ok(0)
1953
}
cdb5beba Andy McCall ↶ 1954
1955
pub fn lock(path: &str) -> Result<i32> {
1956
    let repo = open()?;
1957
    repo.lock_path(path)?;
75167672 Andy McCall 1958
    println!(
1959
        "{} {} {}",
1960
        ui::done("Locked"),
1961
        ui::path(path),
1962
        ui::dim("(advisory, local)")
1963
    );
cdb5beba Andy McCall ↶ 1964
    Ok(0)
1965
}
1966
1967
pub fn unlock(path: &str) -> Result<i32> {
1968
    let repo = open()?;
1969
    repo.unlock_path(path)?;
94084087 Andy McCall ↶ 1970
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
cdb5beba Andy McCall ↶ 1971
    Ok(0)
1972
}
23b217d7 Andy McCall ↶ 1973
1974
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
1975
    let repo = open()?;
1976
    let h = repo.resolve_change(change)?;
1977
    let (h1, h2) = repo.split(&h, paths)?;
1978
    let c1 = repo.store().get_change(&h1)?;
1979
    let c2 = repo.store().get_change(&h2)?;
75167672 Andy McCall 1980
    println!(
1981
        "{} into {} {} and {} {}",
1982
        ui::done("Split"),
1983
        ui::id(short_id(&c1)),
1984
        ui::hash(format!("#{}", h1.short(12))),
1985
        ui::id(short_id(&c2)),
1986
        ui::hash(format!("#{}", h2.short(12)))
1987
    );
23b217d7 Andy McCall ↶ 1988
    Ok(0)
1989
}
7b9809e6 Andy McCall ↶ 1990
1991
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
1992
    let mut heads = Vec::new();
1993
    for c in changes {
1994
        heads.extend(repo.resolve_heads(c)?);
1995
    }
1996
    Ok(heads)
1997
}
1998
4fe7d604 Andy McCall ↶ 1999
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 2000
    let repo = open()?;
cc7a0056 Andy McCall ↶ 2001
    repo.snapshot_status("oxy bookmark create")?;
75167672 Andy McCall 2002
    let heads = if changes.is_empty() {
2003
        None
2004
    } else {
4fe7d604 Andy McCall ↶ 2005
        let named = heads_from(&repo, changes)?;
2006
        let (_, wc) = repo.working_copy()?;
2007
        let gap = repo.state_gap(&wc.deps, &named)?;
2008
        if upto {
2009
            Some(gap.upto)
2010
        } else if only || gap.earlier.is_empty() {
2011
            Some(named)
2012
        } else {
2013
            anyhow::bail!(
2014
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2015
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2016
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2017
                 or --only for just {0} and what it depends on.",
2018
                changes.join(" "),
2019
                plural(gap.earlier.len(), "change"),
2020
                listed_changes(&repo, &gap.earlier)
2021
            );
2022
        }
75167672 Andy McCall 2023
    };
7b9809e6 Andy McCall ↶ 2024
    let heads = repo.bookmark_create(name, heads.as_deref())?;
75167672 Andy McCall 2025
    println!(
2026
        "{} bookmark {} {} {}",
2027
        ui::done("Created"),
2028
        ui::bookmark(name),
2029
        ui::dim(ui::glyph("→", "->")),
2030
        ui::dim(plural(heads.len(), "head"))
2031
    );
2032
    println!(
2033
        "  {} {}",
2034
        ui::note(),
2035
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2036
    );
7b9809e6 Andy McCall ↶ 2037
    Ok(0)
2038
}
2039
4fe7d604 Andy McCall ↶ 2040
/// Up to five changes, newest last, as `  #hash subject` lines.
2041
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
2042
    let shown = changes.len().min(5);
2043
    let mut lines: Vec<String> = changes[changes.len() - shown..]
2044
        .iter()
2045
        .map(|h| {
2046
            let subject = repo
2047
                .store()
2048
                .get_change(h)
2049
                .map(|c| subject_of(&c.message).to_string())
2050
                .unwrap_or_default();
2051
            format!("  #{} {subject}", h.short(12))
2052
        })
2053
        .collect();
2054
    if changes.len() > shown {
2055
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
2056
    }
2057
    lines.join("\n")
2058
}
2059
06d16dc2 Andy McCall ↶ 2060
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 2061
    let repo = open()?;
cc7a0056 Andy McCall ↶ 2062
    repo.snapshot_status("oxy bookmark set")?;
06d16dc2 Andy McCall ↶ 2063
    let named = heads_from(&repo, changes)?;
2064
    // What the bookmark holds now and the new heads would leave out.
2065
    let current = repo
2066
        .bookmarks()?
2067
        .into_iter()
2068
        .find(|b| b.name == name)
2069
        .map(|b| b.heads)
2070
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
2071
    let gap = repo.state_gap(&current, &named)?;
2072
    let heads = if upto {
2073
        gap.upto
2074
    } else if only || gap.earlier.is_empty() {
2075
        named
2076
    } else {
2077
        anyhow::bail!(
2078
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2079
             A state is its heads and what they depend on, not everything recorded before them.\n\
2080
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2081
             or --only for just {0} and what it depends on.",
2082
            changes.join(" "),
2083
            plural(gap.earlier.len(), "change"),
2084
            listed_changes(&repo, &gap.earlier)
2085
        );
2086
    };
7b9809e6 Andy McCall ↶ 2087
    let heads = repo.bookmark_set(name, &heads)?;
75167672 Andy McCall 2088
    println!(
2089
        "{} bookmark {} {} {}",
2090
        ui::done("Moved"),
2091
        ui::bookmark(name),
2092
        ui::dim(ui::glyph("→", "->")),
2093
        ui::dim(plural(heads.len(), "head"))
2094
    );
7b9809e6 Andy McCall ↶ 2095
    Ok(0)
2096
}
2097
2098
pub fn bookmark_delete(name: &str) -> Result<i32> {
2099
    let repo = open()?;
2100
    repo.bookmark_delete(name)?;
75167672 Andy McCall 2101
    println!(
2102
        "{} bookmark {} {}",
2103
        ui::done("Deleted"),
2104
        ui::bookmark(name),
2105
        ui::dim("(its changes stay until unreachable)")
2106
    );
7b9809e6 Andy McCall ↶ 2107
    Ok(0)
2108
}
2109
14edbaaf Andy McCall ↶ 2110
pub fn bookmark_list(all: bool, as_json: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 2111
    let repo = open()?;
14edbaaf Andy McCall ↶ 2112
    let remote_only = repo.remote_only_bookmarks()?;
c6aa5bd9 Andy McCall ↶ 2113
    if as_json {
14edbaaf Andy McCall ↶ 2114
        let mut items: Vec<String> = repo
2115
            .bookmarks()?
2116
            .into_iter()
2117
            .map(|b| {
2118
                json::obj([
2119
                    ("name", json::s(&b.name)),
2120
                    ("heads", json::hashes(&b.heads)),
2121
                    ("current", json::b(b.current)),
2122
                    ("ahead", json::opt(b.ahead, json::n)),
2123
                    ("behind", json::opt(b.behind, json::n)),
2124
                ])
2125
            })
2126
            .collect();
2127
        if all {
2128
            items.extend(remote_only.iter().map(|b| {
2129
                json::obj([
2130
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
2131
                    ("heads", json::hashes(&b.heads)),
2132
                    ("current", json::b(false)),
2133
                    ("ahead", "null".into()),
2134
                    ("behind", "null".into()),
2135
                    ("remote", json::s(&b.remote)),
2136
                ])
2137
            }));
2138
        }
c6aa5bd9 Andy McCall ↶ 2139
        println!("{}", json::arr(items));
2140
        return Ok(0);
2141
    }
7b9809e6 Andy McCall ↶ 2142
    for b in repo.bookmarks()? {
75167672 Andy McCall 2143
        let mark = if b.current {
2144
            ui::ok(ui::glyph("●", "*"))
2145
        } else {
2146
            ui::dim(ui::glyph("○", "o"))
2147
        };
7b9809e6 Andy McCall ↶ 2148
        let mut tail = String::new();
2149
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
2150
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
2151
        }
2152
        if let Some(n) = b.behind.filter(|n| *n > 0) {
2153
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
2154
        }
75167672 Andy McCall 2155
        let head = b
2156
            .heads
2157
            .first()
2158
            .map(|h| {
2159
                repo.store()
2160
                    .get_change(h)
2161
                    .map(|c| ui::subject(subject_of(&c.message)))
2162
                    .unwrap_or_default()
2163
            })
2164
            .unwrap_or_else(|| ui::dim("(empty)"));
2165
        println!(
2166
            "{mark} {}{}{}{tail}  {head}",
2167
            ui::bookmark(&b.name),
14edbaaf Andy McCall ↶ 2168
            ui::sep(),
2169
            ui::dim(plural(b.heads.len(), "head"))
2170
        );
2171
    }
2172
    if remote_only.is_empty() {
2173
        return Ok(0);
2174
    }
2175
    if !all {
2176
        println!(
2177
            "{}",
2178
            ui::dim(format!(
2179
                "  and {} only on a remote: oxy bookmark list --all",
2180
                plural(remote_only.len(), "bookmark")
2181
            ))
2182
        );
2183
        return Ok(0);
2184
    }
2185
    for b in &remote_only {
2186
        println!(
2187
            "{} {}{}{}",
2188
            ui::dim(ui::glyph("◌", ".")),
2189
            ui::dim(format!("{}/{}", b.remote, b.name)),
75167672 Andy McCall 2190
            ui::sep(),
2191
            ui::dim(plural(b.heads.len(), "head"))
2192
        );
7b9809e6 Andy McCall ↶ 2193
    }
14edbaaf Andy McCall ↶ 2194
    println!(
2195
        "  {} {}",
2196
        ui::note(),
2197
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2198
    );
7b9809e6 Andy McCall ↶ 2199
    Ok(0)
2200
}
2201
61e3bce7 Andy McCall ↶ 2202
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 2203
    let mut repo = open()?;
4fe7d604 Andy McCall ↶ 2204
    let from = repo.config.bookmark.clone();
14edbaaf Andy McCall ↶ 2205
    let (local, created_from) = repo.local_bookmark_for(name)?;
2206
    if let Some(remote) = created_from {
2207
        println!(
2208
            "{} {} from {}",
2209
            ui::done("Created"),
2210
            ui::bookmark(&local),
2211
            ui::dim(format!("{remote}/{local}"))
2212
        );
2213
    }
2214
    let name = local.as_str();
7b9809e6 Andy McCall ↶ 2215
    let sp = ui::spinner(&format!("Switching to {name}…"));
61e3bce7 Andy McCall ↶ 2216
    let (r, carried) = if carry {
2217
        repo.bookmark_switch_carry(name)?
2218
    } else {
2219
        (repo.bookmark_switch(name, discard)?, vec![])
2220
    };
75167672 Andy McCall 2221
    sp.done(&format!(
61e3bce7 Andy McCall ↶ 2222
        "{} to {}: {} written, {} removed{}",
75167672 Andy McCall 2223
        ui::done("Switched"),
2224
        ui::bookmark(name),
2225
        plural(r.written, "file"),
61e3bce7 Andy McCall ↶ 2226
        r.removed,
2227
        if carried.is_empty() {
2228
            String::new()
2229
        } else {
2230
            format!("; carried {}", plural(carried.len(), "changed path"))
2231
        }
75167672 Andy McCall 2232
    ));
7b9809e6 Andy McCall ↶ 2233
    if r.conflicted {
75167672 Andy McCall 2234
        println!(
2235
            "  {} {}",
2236
            ui::caution(),
2237
            ui::warn("this state has conflicts; see oxy status")
2238
        );
4fe7d604 Andy McCall ↶ 2239
    }
2240
    // Say when the new state leaves out work the old one had: a state is
2241
    // its heads and what they depend on, which can be far less than a Git
2242
    // user expects.
d3cd7ef9 Andy McCall ↶ 2243
    if r.lacks > 0 {
2244
        println!(
2245
            "  {} {}",
2246
            ui::note(),
2247
            ui::dim(format!(
2248
                "{name} lacks {} that {from} has",
2249
                plural(r.lacks, "change")
2250
            ))
2251
        );
7b9809e6 Andy McCall ↶ 2252
    }
14edbaaf Andy McCall ↶ 2253
    super::sync::subrepos_behind(&repo);
98a1620a Andy McCall ↶ 2254
    where_now(&repo);
7b9809e6 Andy McCall ↶ 2255
    Ok(0)
2256
}
2257
2258
pub fn merge(bookmark: &str) -> Result<i32> {
2259
    let repo = open()?;
2260
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
2261
    let r = repo.merge(bookmark)?;
2262
    if !r.changed {
75167672 Andy McCall 2263
        sp.done(&format!(
2264
            "{} {}",
2265
            ui::ok(ui::glyph("✔", "*")),
2266
            ui::dim(format!(
2267
                "{} already contains {bookmark}",
2268
                repo.config.bookmark
2269
            ))
2270
        ));
7b9809e6 Andy McCall ↶ 2271
        return Ok(0);
2272
    }
2273
    sp.done(&format!(
2274
        "{} {} into {}: now {}{}",
2275
        ui::done("Merged"),
2276
        ui::bookmark(bookmark),
2277
        ui::bookmark(&repo.config.bookmark),
2278
        plural(r.heads.len(), "head"),
75167672 Andy McCall 2279
        ui::dim(if r.checked_out {
2280
            "; working copy updated"
2281
        } else {
2282
            "; run oxy checkout to update the working copy"
2283
        })
7b9809e6 Andy McCall ↶ 2284
    ));
2285
    let snap = repo.snapshot("oxy merge")?;
2286
    if snap.base_snapshot.is_conflicted() {
75167672 Andy McCall 2287
        println!(
2288
            "  {} {}",
2289
            ui::caution(),
2290
            ui::warn("the result has conflicts; see oxy status")
2291
        );
7b9809e6 Andy McCall ↶ 2292
    }
98a1620a Andy McCall ↶ 2293
    where_now(&repo);
7b9809e6 Andy McCall ↶ 2294
    Ok(0)
2295
}
2296
728da0f9 Andy McCall ↶ 2297
pub fn squash(change: &str, into: &str) -> Result<i32> {
2298
    let repo = open()?;
2299
    let c = repo.resolve_change(change)?;
2300
    let d = repo.resolve_change(into)?;
2301
    let sp = ui::spinner("Squashing…");
2302
    let h = repo.squash(&c, &d)?;
2303
    let new = repo.store().get_change(&h)?;
75167672 Andy McCall 2304
    sp.done(&format!(
2305
        "{} into {} {}  {}",
2306
        ui::done("Squashed"),
2307
        ui::id(short_id(&new)),
2308
        ui::hash(format!("#{}", h.short(12))),
2309
        ui::subject(subject_of(&new.message))
2310
    ));
728da0f9 Andy McCall ↶ 2311
    Ok(0)
2312
}
2313
e266b7d4 Andy McCall ↶ 2314
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
728da0f9 Andy McCall ↶ 2315
    let repo = open()?;
2316
    let c = repo.resolve_change(change)?;
2317
    let mut heads = Vec::new();
2318
    for o in onto {
2319
        heads.extend(repo.resolve_heads(o)?);
2320
    }
2321
    let sp = ui::spinner("Rebasing…");
e266b7d4 Andy McCall ↶ 2322
    let h = match repo.rebase(&c, &heads) {
2323
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
2324
            let r = repo.rebase_into_working_copy(&c, &heads)?;
2325
            sp.done(&format!(
2326
                "{} {} into {}: now {}",
2327
                ui::done("Merged"),
2328
                onto.join(" "),
2329
                ui::bookmark(&repo.config.bookmark),
2330
                plural(r.heads.len(), "head"),
2331
            ));
2332
            if r.checked_out {
2333
                println!(
2334
                    "  {} {}",
2335
                    ui::caution(),
2336
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
2337
                );
2338
            } else {
2339
                println!(
2340
                    "  {} {}",
2341
                    ui::caution(),
2342
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
2343
                );
2344
            }
98a1620a Andy McCall ↶ 2345
            where_now(&repo);
e266b7d4 Andy McCall ↶ 2346
            return Ok(0);
2347
        }
2348
        other => other?,
2349
    };
728da0f9 Andy McCall ↶ 2350
    let new = repo.store().get_change(&h)?;
75167672 Andy McCall 2351
    sp.done(&format!(
2352
        "{} {} {}  {}",
2353
        ui::done("Rebased"),
2354
        ui::id(short_id(&new)),
2355
        ui::hash(format!("#{}", h.short(12))),
2356
        ui::dim(format!(
2357
            "now depends on {}",
2358
            plural(new.deps.len(), "change")
2359
        ))
2360
    ));
98a1620a Andy McCall ↶ 2361
    where_now(&repo);
728da0f9 Andy McCall ↶ 2362
    Ok(0)
2363
}