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