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