OXYGENHUB
# f53cbe7a204e oxygen / src / cli / workspace.rs
75.0 KiB · Rust · last changed Fetch reports how each bookmark stands against the remote's copy 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"))),
e293c90d Andy McCall ↶ 960
                // What was built: a release's or install's `oxy describe`,
961
                // a Flow build's heads, or "local build".
962
                ("build", json::s(env!("OXY_BUILD_ID"))),
75167672 Andy McCall 963
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
964
                ("format", json::n(2))
965
            ])
966
        );
c6aa5bd9 Andy McCall ↶ 967
    } else {
75167672 Andy McCall 968
        println!(
969
            "oxy {} (repository format 2, protocol {})",
e293c90d Andy McCall ↶ 970
            env!("OXY_VERSION_LONG"),
75167672 Andy McCall 971
            oxy_core::protocol::PROTOCOL_VERSION
972
        );
c6aa5bd9 Andy McCall ↶ 973
    }
974
    Ok(0)
975
}
976
977
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
978
    let repo = open()?;
979
    if paths.is_empty() && hunks.is_empty() {
980
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
981
    }
982
    let mut n = 0;
983
    if !hunks.is_empty() {
984
        n += repo.discard_hunks(hunks)?;
985
    }
986
    if !paths.is_empty() {
987
        n += repo.discard(paths)?;
988
    }
75167672 Andy McCall 989
    println!(
990
        "{} {} restored to the working copy's base",
991
        ui::done("Discarded"),
992
        plural(n, "path")
993
    );
c6aa5bd9 Andy McCall ↶ 994
    Ok(0)
995
}
996
997
pub fn hunks(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 998
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 999
    let (_, hunks) = repo.hunks()?;
1000
    if as_json {
75167672 Andy McCall 1001
        println!(
1002
            "{}",
1003
            json::arr(hunks.iter().map(|h| json::obj([
1004
                ("index", json::n(h.index)),
1005
                ("path", json::s(&h.path)),
1006
                ("text", json::s(&h.text))
1007
            ])))
1008
        );
c6aa5bd9 Andy McCall ↶ 1009
        return Ok(0);
1010
    }
1011
    if hunks.is_empty() {
75167672 Andy McCall 1012
        println!(
1013
            "{}",
1014
            ui::dim("No hunks: the working copy matches its base.")
1015
        );
c6aa5bd9 Andy McCall ↶ 1016
    }
1017
    for h in &hunks {
75167672 Andy McCall 1018
        println!(
1019
            "{} {}",
1020
            ui::section(format!("hunk {}", h.index)),
1021
            ui::path(&h.path)
1022
        );
c6aa5bd9 Andy McCall ↶ 1023
        for line in h.text.lines() {
75167672 Andy McCall 1024
            let styled = if line.starts_with('+') {
1025
                ui::ok(line)
1026
            } else if line.starts_with('-') {
1027
                ui::err(line)
1028
            } else {
1029
                ui::dim(line)
1030
            };
c6aa5bd9 Andy McCall ↶ 1031
            println!("  {styled}");
1032
        }
1033
    }
fce44ae9 Andy McCall ↶ 1034
    Ok(0)
1035
}
1036
c6aa5bd9 Andy McCall ↶ 1037
pub fn show(change: &str, as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 1038
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1039
    repo.snapshot_status("oxy show")?;
fce44ae9 Andy McCall ↶ 1040
    let h = repo.resolve_change(change)?;
1041
    let c = repo.store().get_change(&h)?;
c6aa5bd9 Andy McCall ↶ 1042
    if as_json {
1043
        let files = repo.diff_files(Some(&h))?;
1044
        let heads = repo.bookmark_heads()?;
75167672 Andy McCall 1045
        let entry = oxy_core::repo::LogEntry {
1046
            hash: h,
1047
            change: oxy_core::state::ChangeMeta::of(&c),
1048
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
1049
            is_head: heads.contains(&h),
1050
        };
c6aa5bd9 Andy McCall ↶ 1051
        let mut body = log_entry_json(&repo, &entry)?;
1052
        body.pop();
75167672 Andy McCall 1053
        body.push_str(&format!(
1054
            ",{}:{}}}",
1055
            json::s("files"),
1056
            json::arr(files.iter().map(|f| json::obj([
1057
                ("path", json::s(&f.path)),
1058
                ("kind", json::s(&f.kind)),
1059
                ("from", json::opt(f.from.as_deref(), json::s))
1060
            ])))
1061
        ));
c6aa5bd9 Andy McCall ↶ 1062
        println!("{body}");
1063
        return Ok(0);
1064
    }
75167672 Andy McCall 1065
    println!(
1066
        "{} {} {}",
1067
        ui::section("change"),
1068
        ui::id(short_id(&c)),
1069
        ui::hash(format!("#{h}"))
1070
    );
94084087 Andy McCall ↶ 1071
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
b35df36b Andy McCall ↶ 1072
    // Fetched but not pulled (oxygen#56): say where it is.
1073
    if let Some(at) = repo.remote_only_location(&h)? {
1074
        println!(
1075
            "{}",
1076
            ui::kv(
1077
                "only in",
1078
                ui::warn(format!(
1079
                    "{at}: fetched, not yet in a local bookmark (oxy pull)"
1080
                ))
1081
            )
1082
        );
1083
    }
75167672 Andy McCall 1084
    println!(
1085
        "{}",
1086
        ui::kv(
1087
            "author",
1088
            ui::author(author_name(&repo, &oxy_core::state::ChangeMeta::of(&c)))
1089
        )
1090
    );
1091
    println!(
1092
        "{}",
1093
        ui::kv(
1094
            "date",
1095
            format!(
1096
                "{} {}",
1097
                when(c.hlc.wall_ms),
1098
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1099
            )
1100
        )
1101
    );
94084087 Andy McCall ↶ 1102
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
1103
    println!("{}", ui::kv("sig", signature_line(&repo, &h)?));
1104
    println!();
75167672 Andy McCall 1105
    for line in (if c.message.is_empty() {
1106
        "(no description)"
1107
    } else {
1108
        &c.message
1109
    })
1110
    .lines()
1111
    {
94084087 Andy McCall ↶ 1112
        println!("    {line}");
1113
    }
1114
    println!();
fce44ae9 Andy McCall ↶ 1115
    print!("{}", repo.describe_change(&h)?);
1116
    Ok(0)
1117
}
1118
1c2bd9ab Andy McCall ↶ 1119
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 1120
    let repo = open()?;
1121
    let heads = if changes.is_empty() {
1122
        repo.bookmark_heads()?
1123
    } else {
132b884b Andy McCall ↶ 1124
        let mut heads = Vec::new();
1125
        for c in changes {
1126
            heads.extend(repo.resolve_heads(c)?);
1127
        }
1128
        heads
fce44ae9 Andy McCall ↶ 1129
    };
75167672 Andy McCall 1130
    let spec = if changes.is_empty() {
1131
        repo.config.bookmark.clone()
1132
    } else {
1133
        changes.join(" ")
1134
    };
135212de Andy McCall ↶ 1135
    let sp = ui::spinner(&format!("Checking out {spec}…"));
1c2bd9ab Andy McCall ↶ 1136
    let command = format!("oxy checkout {spec}");
1137
    let (r, carried) = if carry {
1138
        repo.checkout_carry(&heads, &spec, &command)?
1139
    } else {
1140
        (repo.checkout(&heads, discard, &command)?, vec![])
1141
    };
75167672 Andy McCall 1142
    sp.done(&format!(
1c2bd9ab Andy McCall ↶ 1143
        "{} on {}: {} written, {} removed{}",
75167672 Andy McCall 1144
        ui::done("Working copy"),
1145
        ui::bookmark(&spec),
1146
        plural(r.written, "file"),
1c2bd9ab Andy McCall ↶ 1147
        r.removed,
1148
        if carried.is_empty() {
1149
            String::new()
1150
        } else {
1151
            format!("; carried {}", plural(carried.len(), "changed path"))
1152
        }
75167672 Andy McCall 1153
    ));
4dee277c Andy McCall ↶ 1154
    for n in &r.notes {
1155
        println!("  {} {n}", ui::note());
1156
    }
fce44ae9 Andy McCall ↶ 1157
    if r.conflicted {
75167672 Andy McCall 1158
        println!(
1159
            "  {} {}",
1160
            ui::caution(),
1161
            ui::warn("this state has conflicts; see oxy status")
1162
        );
fce44ae9 Andy McCall ↶ 1163
    }
98a1620a Andy McCall ↶ 1164
    where_now(&repo);
fce44ae9 Andy McCall ↶ 1165
    Ok(0)
1166
}
1167
c6aa5bd9 Andy McCall ↶ 1168
pub fn resolve(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 1169
    let repo = open()?;
1170
    let snap = repo.snapshot("oxy resolve")?;
c6aa5bd9 Andy McCall ↶ 1171
    if as_json {
1172
        println!("{}", repo.status_json(&snap)?);
75167672 Andy McCall 1173
        return Ok(if snap.base_snapshot.is_conflicted() {
1174
            2
1175
        } else {
1176
            0
1177
        });
c6aa5bd9 Andy McCall ↶ 1178
    }
fce44ae9 Andy McCall ↶ 1179
    if !snap.base_snapshot.is_conflicted() {
1180
        println!("The working copy's base has no conflicts.");
1181
        return Ok(0);
1182
    }
1183
    let mut remaining = 0;
1184
    for (p, f) in &snap.base_snapshot.files {
1185
        if !f.is_conflicted() {
1186
            continue;
1187
        }
75167672 Andy McCall 1188
        match snap
1189
            .statuses
1190
            .iter()
1191
            .find(|s| s.path == *p)
1192
            .map(|s| s.status)
1193
        {
fce44ae9 Andy McCall ↶ 1194
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
1195
            Some(ChangeStatus::ConflictEdited) => {
1196
                remaining += 1;
1197
                println!("markers    {p}");
1198
            }
1199
            _ => {
1200
                remaining += 1;
1201
                println!("unresolved {p}");
1202
            }
1203
        }
1204
    }
1205
    for c in &snap.base_snapshot.tree.conflicts {
1206
        remaining += 1;
1207
        println!("tree       {c:?}");
1208
    }
1209
    if remaining == 0 {
1210
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
1211
        Ok(0)
1212
    } else {
1213
        Ok(2)
1214
    }
1215
}
1216
1217
pub fn undo() -> Result<i32> {
1218
    let repo = open()?;
1219
    let op = repo.undo()?;
94084087 Andy McCall ↶ 1220
    println!("{} now at: {}", ui::done("Undone;"), ui::dim(&op.command));
98a1620a Andy McCall ↶ 1221
    where_now(&repo);
fce44ae9 Andy McCall ↶ 1222
    Ok(0)
1223
}
1224
98a1620a Andy McCall ↶ 1225
pub fn op_log(limit: Option<usize>, as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 1226
    let repo = open()?;
98a1620a Andy McCall ↶ 1227
    let ops = repo.op_log()?;
1228
    // What each operation changed, against the one before it.
1229
    let changes_of = |i: usize| -> Result<Vec<oxy_core::repo::ViewChange>> {
1230
        match ops.get(i + 1) {
1231
            Some((_, before)) => Ok(repo.view_changes(&before.view, &ops[i].1.view)?),
1232
            None => Ok(vec![]),
1233
        }
1234
    };
c6aa5bd9 Andy McCall ↶ 1235
    if as_json {
98a1620a Andy McCall ↶ 1236
        let mut items = Vec::new();
1237
        for (i, (r, op)) in ops.iter().enumerate().take(limit.unwrap_or(usize::MAX)) {
1238
            let summary: Vec<String> = changes_of(i)?
1239
                .iter()
1240
                .map(|c| change_words(&repo, c))
1241
                .collect();
1242
            items.push(json::obj([
1243
                ("id", json::s(&r.to_hex())),
1244
                ("when_ms", json::n(op.hlc.wall_ms)),
1245
                ("command", json::s(&op.command)),
1246
                ("snapshot", json::b(op.is_snapshot())),
1247
                ("current", json::b(i == 0)),
1248
                ("changes", json::arr(summary.iter().map(|x| json::s(x)))),
1249
            ]));
1250
        }
1251
        println!("{}", json::arr(items));
c6aa5bd9 Andy McCall ↶ 1252
        return Ok(0);
1253
    }
98a1620a Andy McCall ↶ 1254
    let id_prefix = unique_prefixes(ops.iter().map(|(r, _)| r.to_hex()));
1255
    let id = |r: &oxy_core::hash::ObjectRef| {
1256
        let hex = r.to_hex();
1257
        let n = id_prefix.get(&hex).copied().unwrap_or(12).min(12);
1258
        format!("{}{}", ui::id(&hex[..n]), ui::dim(&hex[n..12]))
1259
    };
1260
    let rail = ui::dim(ui::glyph("│", "|"));
1261
    let (mut i, mut shown) = (0, 0);
1262
    while i < ops.len() && shown < limit.unwrap_or(usize::MAX) {
1263
        let (r, op) = &ops[i];
75167672 Andy McCall 1264
        let bullet = if i == 0 {
98a1620a Andy McCall ↶ 1265
            ui::ok(ui::glyph("@", "@"))
75167672 Andy McCall 1266
        } else {
1267
            ui::dim(ui::glyph("○", "o"))
1268
        };
98a1620a Andy McCall ↶ 1269
        // A run of snapshots folds into one entry.
1270
        let mut run = 1;
1271
        while op.is_snapshot() && i + run < ops.len() && ops[i + run].1.is_snapshot() {
1272
            run += 1;
1273
        }
1274
        let when = ui::dim(ui::ago(op.hlc.wall_ms));
1275
        if op.is_snapshot() {
1276
            let span = if run > 1 {
1277
                format!("{} {}", ui::dim("…"), id(&ops[i + run - 1].0))
1278
            } else {
1279
                String::new()
1280
            };
1281
            println!(
1282
                "{bullet}  {}{} {when}",
1283
                id(r),
1284
                if span.is_empty() {
1285
                    String::new()
1286
                } else {
1287
                    format!(" {span}")
1288
                }
1289
            );
1290
            println!(
1291
                "{rail}  {}",
1292
                ui::dim(if run == 1 {
1293
                    "working-copy snapshot".to_string()
1294
                } else {
1295
                    format!("{run} working-copy snapshots")
1296
                })
1297
            );
1298
        } else {
1299
            println!("{bullet}  {} {when}", id(r));
1300
            let words: Vec<String> = changes_of(i)?
1301
                .iter()
1302
                .map(|c| change_words(&repo, c))
1303
                .collect();
1304
            let summary = if words.is_empty() {
1305
                if i + 1 == ops.len() {
1306
                    "created the repository".to_string()
1307
                } else {
1308
                    "no bookmark or working-copy change".to_string()
1309
                }
1310
            } else {
1311
                words.join("; ")
1312
            };
1313
            println!(
1314
                "{rail}  {}",
1315
                if i == 0 {
1316
                    ui::subject(&summary)
1317
                } else {
1318
                    summary
1319
                }
1320
            );
1321
            let cmd = op.command.lines().next().unwrap_or("");
1322
            let cmd: String = cmd.chars().take(100).collect();
1323
            println!("{rail}  {}", ui::dim(cmd));
1324
        }
1325
        i += run;
1326
        shown += 1;
1327
    }
1328
    if i < ops.len() {
75167672 Andy McCall 1329
        println!(
98a1620a Andy McCall ↶ 1330
            "{}",
1331
            ui::dim(format!(
1332
                "{} {} older; pass -n to see more",
1333
                ui::glyph("…", "..."),
1334
                plural(ops.len() - i, "operation")
1335
            ))
1336
        );
1337
    }
1338
    Ok(0)
1339
}
1340
1341
/// One change an operation made, in words.
1342
fn change_words(repo: &Repo, c: &oxy_core::repo::ViewChange) -> String {
1343
    use oxy_core::repo::ViewChange::*;
1344
    match c {
1345
        BookmarkCreated { name, heads } => {
1346
            format!("created bookmark {name} ({})", plural(*heads, "head"))
1347
        }
1348
        BookmarkDeleted { name } => format!("deleted bookmark {name}"),
1349
        BookmarkMoved { name, from, to } if from == to => format!("moved {name}"),
1350
        BookmarkMoved { name, from, to } => format!(
1351
            "{name}: {from} {} {}",
1352
            ui::glyph("→", "->"),
1353
            plural(*to, "head")
1354
        ),
1355
        RemoteMoved { remote, name } => format!("{remote}/{name} updated"),
1356
        TagCreated { name } => format!("tagged {name}"),
1357
        TagDeleted { name } => format!("removed tag {name}"),
1358
        Policy => "trust policy changed".to_string(),
1359
        WorkingCopy { change } => match repo.store().get_change_meta(change) {
1360
            Ok(m) => format!("working copy now {}", m.change_id.short(8)),
1361
            Err(_) => "working copy moved".to_string(),
1362
        },
1363
    }
1364
}
1365
1366
pub fn op_restore(op: &str, discard: bool) -> Result<i32> {
1367
    let repo = open()?;
1368
    let sp = ui::spinner(&format!("Restoring to operation {op}…"));
1369
    let r = repo.op_restore(op, discard)?;
1370
    sp.done(&format!(
1371
        "{} to operation {} {}",
1372
        ui::done("Restored"),
1373
        ui::hash(r.op.short(12)),
1374
        ui::dim(r.command.lines().next().unwrap_or(""))
1375
    ));
1376
    println!(
1377
        "  {} {}",
1378
        ui::note(),
1379
        ui::dim(format!(
1380
            "{} written, {} removed; oxy undo goes back again",
1381
            plural(r.checkout.written, "file"),
1382
            r.checkout.removed
1383
        ))
1384
    );
1385
    where_now(&repo);
1386
    Ok(0)
1387
}
1388
1389
pub fn op_revert(op: &str) -> Result<i32> {
1390
    let repo = open()?;
1391
    let r = repo.op_revert(op)?;
1392
    let view = repo.view()?;
1393
    let names: Vec<String> = r
1394
        .reverted
1395
        .iter()
1396
        .map(|n| {
1397
            if view.bookmarks.contains_key(n) {
1398
                ui::bookmark(n)
75167672 Andy McCall 1399
            } else {
98a1620a Andy McCall ↶ 1400
                format!("{} (removed)", ui::bookmark(n))
75167672 Andy McCall 1401
            }
98a1620a Andy McCall ↶ 1402
        })
1403
        .collect();
1404
    println!(
1405
        "{} operation {} {}",
1406
        ui::done("Reverted"),
1407
        ui::hash(r.op.short(12)),
1408
        ui::dim(r.command.lines().next().unwrap_or(""))
1409
    );
1410
    println!(
1411
        "  {} {}",
1412
        ui::note(),
1413
        ui::dim(format!("as before it: {}", names.join(", ")))
1414
    );
1415
    if !r.kept.is_empty() {
1416
        println!(
1417
            "  {} {}",
1418
            ui::caution(),
1419
            ui::warn(format!(
1420
                "left as they are, having moved again since: {}",
1421
                r.kept.join(", ")
1422
            ))
75167672 Andy McCall 1423
        );
fce44ae9 Andy McCall ↶ 1424
    }
98a1620a Andy McCall ↶ 1425
    if !r.checked_out && r.reverted.contains(&repo.config.bookmark) {
1426
        println!(
1427
            "  {} {}",
1428
            ui::note(),
1429
            ui::dim("the working copy has work of its own: oxy checkout to move it")
1430
        );
1431
    }
1432
    where_now(&repo);
fce44ae9 Andy McCall ↶ 1433
    Ok(0)
98a1620a Andy McCall ↶ 1434
}
1435
1436
/// Where the working copy and bookmark are now, after a command moved
1437
/// them (as jj says "Working copy now at").
1438
pub fn where_now(repo: &Repo) {
1439
    let Ok((_, wc)) = repo.working_copy() else {
1440
        return;
1441
    };
1442
    let heads = repo.bookmark_heads().unwrap_or_default();
1443
    let newest = heads
1444
        .iter()
1445
        .filter_map(|h| repo.store().get_change_meta(h).ok().map(|m| (m, *h)))
1446
        .max_by_key(|(m, _)| m.hlc);
1447
    println!(
1448
        "  {} {}",
1449
        ui::dim(format!("{:<13}", "Working copy")),
1450
        ui::id(wc.change_id.short(8))
1451
    );
1452
    let tail = match newest {
1453
        Some((m, _)) => format!(
1454
            ", newest {} {}",
1455
            ui::id(m.change_id.short(8)),
1456
            subject_of(&m.message)
1457
        ),
1458
        None => String::new(),
1459
    };
1460
    println!(
1461
        "  {} {}: {}{tail}",
1462
        ui::dim(format!("{:<13}", "Bookmark")),
1463
        ui::bookmark(&repo.config.bookmark),
1464
        plural(heads.len(), "head")
1465
    );
fce44ae9 Andy McCall ↶ 1466
}
d02e545d Andy McCall ↶ 1467
ba160f60 Andy McCall ↶ 1468
pub fn gc(now: bool) -> Result<i32> {
d02e545d Andy McCall ↶ 1469
    let repo = open()?;
135212de Andy McCall ↶ 1470
    let sp = ui::spinner("Packing and pruning…");
ba160f60 Andy McCall ↶ 1471
    let r = repo.gc(now)?;
135212de Andy McCall ↶ 1472
    sp.clear();
ba160f60 Andy McCall ↶ 1473
    if r.packed.objects > 0 {
d02e545d Andy McCall ↶ 1474
        println!(
da652d63 Andy McCall ↶ 1475
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
1476
            plural(r.packed.objects, "object"),
ba160f60 Andy McCall ↶ 1477
            r.packed.raw_bytes,
1478
            r.packed.packed_bytes,
1479
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
d02e545d Andy McCall ↶ 1480
        );
1481
    }
75167672 Andy McCall 1482
    println!(
1483
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
ba160f60 Andy McCall ↶ 1484
        plural(r.reachable, "object"),
1485
        plural(r.pruned.objects, "unreachable object"),
1486
        r.pruned.bytes,
75167672 Andy McCall 1487
        if r.pruned.deferred > 0 {
1488
            format!(
1489
                "; {} deferred by the grace period (use --now)",
1490
                plural(r.pruned.deferred, "object")
1491
            )
1492
        } else {
1493
            String::new()
1494
        },
1495
        if r.merged_packs > 0 {
1496
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1497
        } else {
1498
            String::new()
1499
        },
ba160f60 Andy McCall ↶ 1500
        plural(repo.store().pack_count(), "pack")
1501
    );
d02e545d Andy McCall ↶ 1502
    Ok(0)
1503
}
614541c3 Andy McCall ↶ 1504
3e5772cc Andy McCall ↶ 1505
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
1506
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1507
    use oxy_core::repo::Health;
1508
    let repo = open()?;
1509
    let sp = ui::spinner(if offline {
1510
        "Checking…"
1511
    } else {
1512
        "Checking, and contacting remotes…"
1513
    });
1514
    let r = repo.doctor(!offline);
1515
    sp.clear();
1516
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
1517
    let word = |h: Health| match h {
1518
        Health::Ok => "ok",
1519
        Health::Warn => "warning",
1520
        Health::Fail => "fail",
1521
    };
1522
    if as_json {
1523
        let checks: Vec<String> = r
1524
            .checks
1525
            .iter()
1526
            .map(|c| {
1527
                json::obj([
1528
                    ("area", json::s(&c.area)),
1529
                    ("health", json::s(word(c.health))),
1530
                    ("message", json::s(&c.message)),
1531
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
1532
                ])
1533
            })
1534
            .collect();
1535
        println!(
1536
            "{}",
1537
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1538
        );
1539
        return Ok(code);
1540
    }
1541
    let mut last = "";
1542
    for c in &r.checks {
1543
        if c.area != last {
1544
            println!("{}", ui::section(&c.area));
1545
            last = &c.area;
1546
        }
1547
        let mark = match c.health {
1548
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
1549
            Health::Warn => ui::caution(),
1550
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1551
        };
1552
        println!("  {mark} {}", c.message);
1553
        if let Some(h) = &c.hint {
1554
            println!("    {} {}", ui::dim("→"), ui::dim(h));
1555
        }
1556
    }
1557
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
1558
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
1559
    if fails + warns == 0 {
1560
        println!("{}", ui::done("Everything looks right."));
1561
    } else {
1562
        println!(
1563
            "{} {}, {}.",
1564
            if fails > 0 {
1565
                ui::err(ui::glyph("✖", "x"))
1566
            } else {
1567
                ui::caution()
1568
            },
1569
            plural(fails, "problem"),
1570
            plural(warns, "warning")
1571
        );
1572
    }
1573
    Ok(code)
1574
}
1575
387335ff Andy McCall ↶ 1576
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
1577
pub fn fsck(as_json: bool) -> Result<i32> {
1578
    use oxy_core::repo::Severity;
1579
    let repo = open()?;
1580
    let sp = ui::spinner("Checking every object…");
1581
    let r = repo.fsck()?;
1582
    sp.clear();
1583
    let code = if r.errors() > 0 { 1 } else { 0 };
1584
    if as_json {
1585
        let problems: Vec<String> = r
1586
            .problems
1587
            .iter()
1588
            .map(|p| {
1589
                json::obj([
1590
                    (
1591
                        "severity",
1592
                        json::s(match p.severity {
1593
                            Severity::Error => "error",
1594
                            Severity::Warning => "warning",
1595
                        }),
1596
                    ),
1597
                    (
1598
                        "object",
1599
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1600
                    ),
1601
                    ("what", json::s(&p.what)),
1602
                ])
1603
            })
1604
            .collect();
1605
        println!(
1606
            "{}",
1607
            json::obj([
1608
                ("ok", json::b(code == 0)),
1609
                ("objects", json::n(r.objects)),
1610
                ("ops", json::n(r.ops)),
1611
                ("changes", json::n(r.changes)),
1612
                ("signed", json::n(r.signed)),
1613
                ("unsigned", json::n(r.unsigned)),
1614
                ("checkpoints", json::n(r.checkpoints)),
1615
                ("attestations", json::n(r.attestations)),
1616
                ("errors", json::n(r.errors())),
1617
                ("warnings", json::n(r.warnings())),
1618
                ("problems", json::arr(problems)),
1619
            ])
1620
        );
1621
        return Ok(code);
1622
    }
1623
    println!(
1624
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
1625
        plural(r.objects, "object"),
1626
        plural(r.ops, "operation"),
1627
        plural(r.changes, "change"),
1628
        r.signed,
1629
        r.unsigned,
1630
        plural(r.checkpoints, "checkpoint"),
1631
        plural(r.attestations, "attestation"),
1632
    );
1633
    for p in &r.problems {
1634
        let obj = p
1635
            .object
1636
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
1637
            .unwrap_or_default();
1638
        match p.severity {
1639
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
1640
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1641
        }
1642
    }
1643
    if r.problems.is_empty() {
1644
        println!("{}", ui::done("No problems found."));
1645
    } else if code == 0 {
1646
        println!(
1647
            "{}",
1648
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
1649
        );
1650
    } else {
1651
        println!(
1652
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
1653
            ui::err(ui::glyph("✖", "x")),
1654
            plural(r.errors(), "error"),
1655
            plural(r.warnings(), "warning")
1656
        );
1657
    }
1658
    Ok(code)
1659
}
1660
79d03f82 Andy McCall ↶ 1661
/// The head the working copy sits on, for commands that default to it. With
1662
/// several heads beneath the working copy, the most recently made one is
1663
/// chosen and announced.
614541c3 Andy McCall ↶ 1664
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
cc7a0056 Andy McCall ↶ 1665
    let snap = repo.snapshot_status("oxy")?;
614541c3 Andy McCall ↶ 1666
    let base = snap.base.maximal(&snap.wc.deps);
1667
    match base.as_slice() {
79d03f82 Andy McCall ↶ 1668
        [] => anyhow::bail!("the working copy sits on no change yet"),
614541c3 Andy McCall ↶ 1669
        [h] => Ok(*h),
79d03f82 Andy McCall ↶ 1670
        many => {
1671
            let latest = many
1672
                .iter()
1673
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
1674
                .copied()
1675
                .unwrap();
1676
            let c = repo.store().get_change(&latest)?;
75167672 Andy McCall 1677
            println!(
1678
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
1679
                short_id(&c),
1680
                latest.short(12),
1681
                many.len()
1682
            );
79d03f82 Andy McCall ↶ 1683
            Ok(latest)
1684
        }
614541c3 Andy McCall ↶ 1685
    }
1686
}
1687
6a81dbab Andy McCall ↶ 1688
/// `oxy describe` without -m: the working copy's name for a build.
1689
pub fn describe_name(as_json: bool) -> Result<i32> {
1690
    let repo = open()?;
1691
    let d = repo.describe_working_copy()?;
1692
    if as_json {
1693
        println!(
1694
            "{}",
1695
            json::obj([
1696
                ("describe", json::s(&d.line())),
1697
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
1698
                ("distance", json::n(d.distance)),
1699
                ("bookmark", json::s(&d.bookmark)),
1700
                ("change", json::s(&d.change.to_hex())),
1701
                ("hash", json::s(&d.hash.to_hex())),
1702
                ("dirty", json::b(d.dirty)),
1703
            ])
1704
        );
1705
    } else {
1706
        println!("{}", d.line());
1707
    }
1708
    Ok(0)
1709
}
1710
614541c3 Andy McCall ↶ 1711
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
1712
    let repo = open()?;
1713
    let h = match change {
1714
        Some(c) => repo.resolve_change(c)?,
1715
        None => current_head(&repo)?,
1716
    };
1717
    let new = repo.describe(&h, message)?;
1718
    let c = repo.store().get_change(&new)?;
75167672 Andy McCall 1719
    println!(
1720
        "{} {} {}  {}",
1721
        ui::done("Described"),
1722
        ui::id(short_id(&c)),
1723
        ui::hash(format!("#{}", new.short(12))),
1724
        ui::subject(subject_of(message))
1725
    );
614541c3 Andy McCall ↶ 1726
    Ok(0)
1727
}
1728
23b217d7 Andy McCall ↶ 1729
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
614541c3 Andy McCall ↶ 1730
    let repo = open()?;
23b217d7 Andy McCall ↶ 1731
    let new = match into {
1732
        Some(spec) => {
1733
            let target = repo.resolve_change(spec)?;
1734
            repo.amend_into(&target, message)?
1735
        }
1736
        None => repo.amend(message)?,
1737
    };
614541c3 Andy McCall ↶ 1738
    let c = repo.store().get_change(&new)?;
75167672 Andy McCall 1739
    println!(
1740
        "{} {} {}  {}",
1741
        ui::done("Amended"),
1742
        ui::id(short_id(&c)),
1743
        ui::hash(format!("#{}", new.short(12))),
1744
        ui::subject(subject_of(&c.message))
1745
    );
98a1620a Andy McCall ↶ 1746
    where_now(&repo);
614541c3 Andy McCall ↶ 1747
    Ok(0)
1748
}
1749
1750
pub fn abandon(change: &str) -> Result<i32> {
1751
    let repo = open()?;
1752
    let h = repo.resolve_change(change)?;
1753
    let c = repo.store().get_change(&h)?;
6706bdcf Andy McCall ↶ 1754
    let notes = repo.abandon(&h)?;
75167672 Andy McCall 1755
    println!(
1756
        "{} {} {}  {}",
1757
        ui::done("Abandoned"),
1758
        ui::id(short_id(&c)),
1759
        ui::hash(format!("#{}", h.short(12))),
1760
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
1761
    );
6706bdcf Andy McCall ↶ 1762
    for n in notes {
94084087 Andy McCall ↶ 1763
        println!("  {} {n}", ui::note());
6706bdcf Andy McCall ↶ 1764
    }
98a1620a Andy McCall ↶ 1765
    where_now(&repo);
614541c3 Andy McCall ↶ 1766
    Ok(0)
1767
}
252e8cb2 Andy McCall ↶ 1768
1769
pub fn checkpoint() -> Result<i32> {
1770
    let repo = open()?;
135212de Andy McCall ↶ 1771
    let sp = ui::spinner("Writing checkpoint…");
252e8cb2 Andy McCall ↶ 1772
    let (r, changes, bytes) = repo.checkpoint()?;
75167672 Andy McCall 1773
    sp.done(&format!(
1774
        "{} {} of {} ({} bytes) for {}",
1775
        ui::done("Checkpoint"),
1776
        ui::hash(format!("#{}", r.short(12))),
1777
        plural(changes, "change"),
1778
        bytes,
1779
        ui::id(&repo.config.bookmark)
1780
    ));
135212de Andy McCall ↶ 1781
    Ok(0)
1782
}
1783
1784
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
694805cc Andy McCall ↶ 1785
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
75167672 Andy McCall 1786
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
1787
        return Ok(1);
1788
    };
135212de Andy McCall ↶ 1789
    let info = repo.quick_status()?;
75167672 Andy McCall 1790
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
1791
        oxy_core::repo::GLYPH_PROMPT_FORMAT
1792
    } else {
1793
        format
1794
    };
694805cc Andy McCall ↶ 1795
    let line = match color {
1796
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
1797
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
1798
        Some(_) => info.format_colored(fmt, ("", "")),
1799
        None => info.format(fmt),
1800
    };
1801
    println!("{line}");
252e8cb2 Andy McCall ↶ 1802
    Ok(0)
1803
}
7421309f Andy McCall ↶ 1804
1805
pub fn sparse(paths: &[String]) -> Result<i32> {
1806
    let mut repo = open()?;
1807
    if paths.is_empty() {
1808
        if repo.config.sparse_paths.is_empty() {
1809
            println!("No sparse filter: the whole tree is materialized.");
1810
        } else {
1811
            println!("{}", ui::heading("Sparse filter"));
1812
            for p in &repo.config.sparse_paths {
1813
                println!("  {}", ui::path(p));
1814
            }
1815
        }
1816
        return Ok(0);
1817
    }
1818
    let snap = repo.snapshot("oxy sparse")?;
1819
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
75167672 Andy McCall 1820
        anyhow::bail!(
1821
            "the working copy has changes; commit them before changing the sparse filter"
1822
        );
7421309f Andy McCall ↶ 1823
    }
1824
    repo.config.set("filter.paths", &paths.join(","))?;
1825
    repo.save_config()?;
1826
    let heads = repo.bookmark_heads()?;
1827
    let sp = ui::spinner("Re-checking out with the new filter…");
1828
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
75167672 Andy McCall 1829
    sp.done(&format!(
1830
        "{} {}: {} written, {} removed",
c07406bc Andy McCall ↶ 1831
        ui::done("Sparse filter set to"),
75167672 Andy McCall 1832
        ui::path(paths.join(",")),
1833
        plural(r.written, "file"),
1834
        r.removed
1835
    ));
7421309f Andy McCall ↶ 1836
    Ok(0)
1837
}
132b884b Andy McCall ↶ 1838
1839
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
1840
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1841
    repo.snapshot_status("oxy tag")?;
132b884b Andy McCall ↶ 1842
    let heads = if changes.is_empty() {
1843
        repo.bookmark_heads()?
1844
    } else {
1845
        let mut heads = Vec::new();
1846
        for c in changes {
1847
            heads.extend(repo.resolve_heads(c)?);
1848
        }
1849
        heads
1850
    };
1851
    let t = repo.tag_create(name, &heads, message)?;
1852
    println!(
94084087 Andy McCall ↶ 1853
        "{} {} {} {} ({}){}",
1854
        ui::done("Tagged"),
1855
        ui::bookmark(&t.name),
1856
        ui::dim(ui::glyph("→", "->")),
132b884b Andy McCall ↶ 1857
        ui::hash(format!("#{}", t.state.short(12))),
1858
        plural(t.heads.len(), "head"),
75167672 Andy McCall 1859
        t.signer
1860
            .map(|s| format!(", signed by {s}"))
1861
            .unwrap_or_else(|| ui::dim(", unsigned"))
132b884b Andy McCall ↶ 1862
    );
1863
    Ok(0)
1864
}
1865
1196b29b Andy McCall ↶ 1866
pub fn tag_list(as_json: bool) -> Result<i32> {
132b884b Andy McCall ↶ 1867
    let repo = open()?;
1868
    let tags = repo.tags()?;
1196b29b Andy McCall ↶ 1869
    if as_json {
1870
        println!(
1871
            "{}",
1872
            json::arr(tags.iter().map(|t| {
1873
                json::obj([
1874
                    ("name", json::s(&t.name)),
1875
                    ("state", json::s(&t.state.to_hex())),
1876
                    ("heads", json::hashes(&t.heads)),
1877
                    ("message", json::s(&t.message)),
75167672 Andy McCall 1878
                    (
1879
                        "signer",
1880
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
1881
                    ),
1196b29b Andy McCall ↶ 1882
                ])
1883
            }))
1884
        );
1885
        return Ok(0);
1886
    }
132b884b Andy McCall ↶ 1887
    if tags.is_empty() {
1888
        println!("{}", ui::dim("No tags."));
1889
    }
1890
    for t in tags {
1891
        println!(
94084087 Andy McCall ↶ 1892
            "{} {} {}{}{}{}",
1893
            ui::ok(ui::glyph("⚑", "#")),
1894
            ui::bookmark(&t.name),
6a81dbab Andy McCall ↶ 1895
            // The heads, as `oxy log` shows changes, not the state hash.
1896
            ui::hash(
1897
                t.heads
1898
                    .iter()
1899
                    .map(|h| format!("#{}", h.short(12)))
1900
                    .collect::<Vec<_>>()
1901
                    .join(" ")
1902
            ),
94084087 Andy McCall ↶ 1903
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
75167672 Andy McCall 1904
            if t.message.is_empty() {
1905
                String::new()
1906
            } else {
1907
                format!("  {}", ui::subject(subject_of(&t.message)))
1908
            },
1909
            t.signer
1910
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
1911
                .unwrap_or_default()
132b884b Andy McCall ↶ 1912
        );
1913
    }
1914
    Ok(0)
1915
}
4e88e774 Andy McCall ↶ 1916
1917
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
1918
    let repo = open()?;
1919
    let heads = if changes.is_empty() {
1920
        None
1921
    } else {
1922
        let mut heads = Vec::new();
1923
        for c in changes {
1924
            heads.extend(repo.resolve_heads(c)?);
1925
        }
1926
        Some(heads)
1927
    };
1928
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
1929
    let ws = repo.workspace_add(path, heads.as_deref())?;
75167672 Andy McCall 1930
    sp.done(&format!(
1931
        "{} {} (workspace {})",
1932
        ui::done("Workspace created at"),
1933
        ui::path(ws.root().display()),
1934
        ui::id(ws.workspace().short(8))
1935
    ));
4e88e774 Andy McCall ↶ 1936
    Ok(0)
1937
}
1938
1196b29b Andy McCall ↶ 1939
pub fn workspace_list(as_json: bool) -> Result<i32> {
4e88e774 Andy McCall ↶ 1940
    let repo = open()?;
1196b29b Andy McCall ↶ 1941
    if as_json {
1942
        println!(
1943
            "{}",
1944
            json::arr(repo.workspaces()?.iter().map(|w| {
1945
                json::obj([
1946
                    ("id", json::s(&w.id.to_hex())),
1947
                    ("path", json::s(&w.path.to_string_lossy())),
1948
                    ("current", json::b(w.current)),
75167672 Andy McCall 1949
                    (
1950
                        "working_copy",
1951
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
1952
                    ),
1196b29b Andy McCall ↶ 1953
                ])
1954
            }))
1955
        );
1956
        return Ok(0);
1957
    }
4e88e774 Andy McCall ↶ 1958
    for w in repo.workspaces()? {
1959
        println!(
1960
            "{} {} {}{}",
75167672 Andy McCall 1961
            if w.current {
1962
                ui::ok(ui::glyph("●", "*"))
1963
            } else {
1964
                ui::dim(ui::glyph("○", "o"))
1965
            },
4e88e774 Andy McCall ↶ 1966
            ui::id(w.id.short(8)),
1967
            ui::path(w.path.display()),
75167672 Andy McCall 1968
            w.working_copy
1969
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
1970
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
4e88e774 Andy McCall ↶ 1971
        );
1972
    }
1973
    Ok(0)
1974
}
1975
1976
pub fn workspace_forget(spec: &str) -> Result<i32> {
1977
    let repo = open()?;
1978
    let all = repo.workspaces()?;
1979
    let target = std::fs::canonicalize(spec).ok();
75167672 Andy McCall 1980
    let matches: Vec<_> = all
1981
        .iter()
1982
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
1983
        .collect();
4e88e774 Andy McCall ↶ 1984
    let w = match matches.as_slice() {
1985
        [w] => *w,
1986
        [] => anyhow::bail!("no workspace matches {spec:?}"),
1987
        _ => anyhow::bail!("{spec:?} is ambiguous"),
1988
    };
1989
    repo.workspace_forget(&w.id)?;
75167672 Andy McCall 1990
    println!(
1991
        "{} workspace {} at {}; its files were left in place.",
1992
        ui::done("Forgot"),
1993
        ui::id(w.id.short(8)),
1994
        ui::path(w.path.display())
1995
    );
4e88e774 Andy McCall ↶ 1996
    Ok(0)
1997
}
cdb5beba Andy McCall ↶ 1998
1999
pub fn lock(path: &str) -> Result<i32> {
2000
    let repo = open()?;
2001
    repo.lock_path(path)?;
75167672 Andy McCall 2002
    println!(
2003
        "{} {} {}",
2004
        ui::done("Locked"),
2005
        ui::path(path),
2006
        ui::dim("(advisory, local)")
2007
    );
cdb5beba Andy McCall ↶ 2008
    Ok(0)
2009
}
2010
2011
pub fn unlock(path: &str) -> Result<i32> {
2012
    let repo = open()?;
2013
    repo.unlock_path(path)?;
94084087 Andy McCall ↶ 2014
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
cdb5beba Andy McCall ↶ 2015
    Ok(0)
2016
}
23b217d7 Andy McCall ↶ 2017
2018
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
2019
    let repo = open()?;
2020
    let h = repo.resolve_change(change)?;
2021
    let (h1, h2) = repo.split(&h, paths)?;
2022
    let c1 = repo.store().get_change(&h1)?;
2023
    let c2 = repo.store().get_change(&h2)?;
75167672 Andy McCall 2024
    println!(
2025
        "{} into {} {} and {} {}",
2026
        ui::done("Split"),
2027
        ui::id(short_id(&c1)),
2028
        ui::hash(format!("#{}", h1.short(12))),
2029
        ui::id(short_id(&c2)),
2030
        ui::hash(format!("#{}", h2.short(12)))
2031
    );
23b217d7 Andy McCall ↶ 2032
    Ok(0)
2033
}
7b9809e6 Andy McCall ↶ 2034
2035
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
2036
    let mut heads = Vec::new();
2037
    for c in changes {
2038
        heads.extend(repo.resolve_heads(c)?);
2039
    }
2040
    Ok(heads)
2041
}
2042
4fe7d604 Andy McCall ↶ 2043
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 2044
    let repo = open()?;
cc7a0056 Andy McCall ↶ 2045
    repo.snapshot_status("oxy bookmark create")?;
75167672 Andy McCall 2046
    let heads = if changes.is_empty() {
2047
        None
2048
    } else {
4fe7d604 Andy McCall ↶ 2049
        let named = heads_from(&repo, changes)?;
2050
        let (_, wc) = repo.working_copy()?;
2051
        let gap = repo.state_gap(&wc.deps, &named)?;
2052
        if upto {
2053
            Some(gap.upto)
2054
        } else if only || gap.earlier.is_empty() {
2055
            Some(named)
2056
        } else {
2057
            anyhow::bail!(
2058
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
2059
                 A state is its heads and what they depend on, not everything recorded before them.\n\
2060
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
2061
                 or --only for just {0} and what it depends on.",
2062
                changes.join(" "),
2063
                plural(gap.earlier.len(), "change"),
2064
                listed_changes(&repo, &gap.earlier)
2065
            );
2066
        }
75167672 Andy McCall 2067
    };
7b9809e6 Andy McCall ↶ 2068
    let heads = repo.bookmark_create(name, heads.as_deref())?;
75167672 Andy McCall 2069
    println!(
2070
        "{} bookmark {} {} {}",
2071
        ui::done("Created"),
2072
        ui::bookmark(name),
2073
        ui::dim(ui::glyph("→", "->")),
2074
        ui::dim(plural(heads.len(), "head"))
2075
    );
2076
    println!(
2077
        "  {} {}",
2078
        ui::note(),
2079
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
2080
    );
7b9809e6 Andy McCall ↶ 2081
    Ok(0)
2082
}
2083
4fe7d604 Andy McCall ↶ 2084
/// Up to five changes, newest last, as `  #hash subject` lines.
2085
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
2086
    let shown = changes.len().min(5);
2087
    let mut lines: Vec<String> = changes[changes.len() - shown..]
2088
        .iter()
2089
        .map(|h| {
2090
            let subject = repo
2091
                .store()
2092
                .get_change(h)
2093
                .map(|c| subject_of(&c.message).to_string())
2094
                .unwrap_or_default();
2095
            format!("  #{} {subject}", h.short(12))
2096
        })
2097
        .collect();
2098
    if changes.len() > shown {
2099
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
2100
    }
2101
    lines.join("\n")
2102
}
2103
06d16dc2 Andy McCall ↶ 2104
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 2105
    let repo = open()?;
cc7a0056 Andy McCall ↶ 2106
    repo.snapshot_status("oxy bookmark set")?;
06d16dc2 Andy McCall ↶ 2107
    let named = heads_from(&repo, changes)?;
2108
    // What the bookmark holds now and the new heads would leave out.
2109
    let current = repo
2110
        .bookmarks()?
2111
        .into_iter()
2112
        .find(|b| b.name == name)
2113
        .map(|b| b.heads)
2114
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
2115
    let gap = repo.state_gap(&current, &named)?;
2116
    let heads = if upto {
2117
        gap.upto
2118
    } else if only || gap.earlier.is_empty() {
2119
        named
2120
    } else {
2121
        anyhow::bail!(
2122
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
2123
             A state is its heads and what they depend on, not everything recorded before them.\n\
2124
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
2125
             or --only for just {0} and what it depends on.",
2126
            changes.join(" "),
2127
            plural(gap.earlier.len(), "change"),
2128
            listed_changes(&repo, &gap.earlier)
2129
        );
2130
    };
7b9809e6 Andy McCall ↶ 2131
    let heads = repo.bookmark_set(name, &heads)?;
75167672 Andy McCall 2132
    println!(
2133
        "{} bookmark {} {} {}",
2134
        ui::done("Moved"),
2135
        ui::bookmark(name),
2136
        ui::dim(ui::glyph("→", "->")),
2137
        ui::dim(plural(heads.len(), "head"))
2138
    );
7b9809e6 Andy McCall ↶ 2139
    Ok(0)
2140
}
2141
2142
pub fn bookmark_delete(name: &str) -> Result<i32> {
2143
    let repo = open()?;
2144
    repo.bookmark_delete(name)?;
75167672 Andy McCall 2145
    println!(
2146
        "{} bookmark {} {}",
2147
        ui::done("Deleted"),
2148
        ui::bookmark(name),
2149
        ui::dim("(its changes stay until unreachable)")
2150
    );
7b9809e6 Andy McCall ↶ 2151
    Ok(0)
2152
}
2153
14edbaaf Andy McCall ↶ 2154
pub fn bookmark_list(all: bool, as_json: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 2155
    let repo = open()?;
14edbaaf Andy McCall ↶ 2156
    let remote_only = repo.remote_only_bookmarks()?;
c6aa5bd9 Andy McCall ↶ 2157
    if as_json {
14edbaaf Andy McCall ↶ 2158
        let mut items: Vec<String> = repo
2159
            .bookmarks()?
2160
            .into_iter()
2161
            .map(|b| {
2162
                json::obj([
2163
                    ("name", json::s(&b.name)),
2164
                    ("heads", json::hashes(&b.heads)),
2165
                    ("current", json::b(b.current)),
2166
                    ("ahead", json::opt(b.ahead, json::n)),
2167
                    ("behind", json::opt(b.behind, json::n)),
2168
                ])
2169
            })
2170
            .collect();
2171
        if all {
2172
            items.extend(remote_only.iter().map(|b| {
2173
                json::obj([
2174
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
2175
                    ("heads", json::hashes(&b.heads)),
2176
                    ("current", json::b(false)),
2177
                    ("ahead", "null".into()),
2178
                    ("behind", "null".into()),
2179
                    ("remote", json::s(&b.remote)),
2180
                ])
2181
            }));
2182
        }
c6aa5bd9 Andy McCall ↶ 2183
        println!("{}", json::arr(items));
2184
        return Ok(0);
2185
    }
7b9809e6 Andy McCall ↶ 2186
    for b in repo.bookmarks()? {
75167672 Andy McCall 2187
        let mark = if b.current {
2188
            ui::ok(ui::glyph("●", "*"))
2189
        } else {
2190
            ui::dim(ui::glyph("○", "o"))
2191
        };
7b9809e6 Andy McCall ↶ 2192
        let mut tail = String::new();
2193
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
2194
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
2195
        }
2196
        if let Some(n) = b.behind.filter(|n| *n > 0) {
2197
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
2198
        }
75167672 Andy McCall 2199
        let head = b
2200
            .heads
2201
            .first()
2202
            .map(|h| {
2203
                repo.store()
2204
                    .get_change(h)
2205
                    .map(|c| ui::subject(subject_of(&c.message)))
2206
                    .unwrap_or_default()
2207
            })
2208
            .unwrap_or_else(|| ui::dim("(empty)"));
2209
        println!(
2210
            "{mark} {}{}{}{tail}  {head}",
2211
            ui::bookmark(&b.name),
14edbaaf Andy McCall ↶ 2212
            ui::sep(),
2213
            ui::dim(plural(b.heads.len(), "head"))
2214
        );
2215
    }
2216
    if remote_only.is_empty() {
2217
        return Ok(0);
2218
    }
2219
    if !all {
2220
        println!(
2221
            "{}",
2222
            ui::dim(format!(
2223
                "  and {} only on a remote: oxy bookmark list --all",
2224
                plural(remote_only.len(), "bookmark")
2225
            ))
2226
        );
2227
        return Ok(0);
2228
    }
2229
    for b in &remote_only {
2230
        println!(
2231
            "{} {}{}{}",
2232
            ui::dim(ui::glyph("◌", ".")),
2233
            ui::dim(format!("{}/{}", b.remote, b.name)),
75167672 Andy McCall 2234
            ui::sep(),
2235
            ui::dim(plural(b.heads.len(), "head"))
2236
        );
7b9809e6 Andy McCall ↶ 2237
    }
14edbaaf Andy McCall ↶ 2238
    println!(
2239
        "  {} {}",
2240
        ui::note(),
2241
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
2242
    );
7b9809e6 Andy McCall ↶ 2243
    Ok(0)
2244
}
2245
61e3bce7 Andy McCall ↶ 2246
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 2247
    let mut repo = open()?;
4fe7d604 Andy McCall ↶ 2248
    let from = repo.config.bookmark.clone();
14edbaaf Andy McCall ↶ 2249
    let (local, created_from) = repo.local_bookmark_for(name)?;
2250
    if let Some(remote) = created_from {
2251
        println!(
2252
            "{} {} from {}",
2253
            ui::done("Created"),
2254
            ui::bookmark(&local),
2255
            ui::dim(format!("{remote}/{local}"))
2256
        );
2257
    }
2258
    let name = local.as_str();
7b9809e6 Andy McCall ↶ 2259
    let sp = ui::spinner(&format!("Switching to {name}…"));
61e3bce7 Andy McCall ↶ 2260
    let (r, carried) = if carry {
2261
        repo.bookmark_switch_carry(name)?
2262
    } else {
2263
        (repo.bookmark_switch(name, discard)?, vec![])
2264
    };
75167672 Andy McCall 2265
    sp.done(&format!(
61e3bce7 Andy McCall ↶ 2266
        "{} to {}: {} written, {} removed{}",
75167672 Andy McCall 2267
        ui::done("Switched"),
2268
        ui::bookmark(name),
2269
        plural(r.written, "file"),
61e3bce7 Andy McCall ↶ 2270
        r.removed,
2271
        if carried.is_empty() {
2272
            String::new()
2273
        } else {
2274
            format!("; carried {}", plural(carried.len(), "changed path"))
2275
        }
75167672 Andy McCall 2276
    ));
7b9809e6 Andy McCall ↶ 2277
    if r.conflicted {
75167672 Andy McCall 2278
        println!(
2279
            "  {} {}",
2280
            ui::caution(),
2281
            ui::warn("this state has conflicts; see oxy status")
2282
        );
4fe7d604 Andy McCall ↶ 2283
    }
2284
    // Say when the new state leaves out work the old one had: a state is
2285
    // its heads and what they depend on, which can be far less than a Git
2286
    // user expects.
d3cd7ef9 Andy McCall ↶ 2287
    if r.lacks > 0 {
2288
        println!(
2289
            "  {} {}",
2290
            ui::note(),
2291
            ui::dim(format!(
2292
                "{name} lacks {} that {from} has",
2293
                plural(r.lacks, "change")
2294
            ))
2295
        );
7b9809e6 Andy McCall ↶ 2296
    }
14edbaaf Andy McCall ↶ 2297
    super::sync::subrepos_behind(&repo);
98a1620a Andy McCall ↶ 2298
    where_now(&repo);
7b9809e6 Andy McCall ↶ 2299
    Ok(0)
2300
}
2301
2302
pub fn merge(bookmark: &str) -> Result<i32> {
2303
    let repo = open()?;
2304
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
2305
    let r = repo.merge(bookmark)?;
2306
    if !r.changed {
75167672 Andy McCall 2307
        sp.done(&format!(
2308
            "{} {}",
2309
            ui::ok(ui::glyph("✔", "*")),
2310
            ui::dim(format!(
2311
                "{} already contains {bookmark}",
2312
                repo.config.bookmark
2313
            ))
2314
        ));
7b9809e6 Andy McCall ↶ 2315
        return Ok(0);
2316
    }
2317
    sp.done(&format!(
2318
        "{} {} into {}: now {}{}",
2319
        ui::done("Merged"),
2320
        ui::bookmark(bookmark),
2321
        ui::bookmark(&repo.config.bookmark),
2322
        plural(r.heads.len(), "head"),
75167672 Andy McCall 2323
        ui::dim(if r.checked_out {
2324
            "; working copy updated"
2325
        } else {
2326
            "; run oxy checkout to update the working copy"
2327
        })
7b9809e6 Andy McCall ↶ 2328
    ));
2329
    let snap = repo.snapshot("oxy merge")?;
2330
    if snap.base_snapshot.is_conflicted() {
75167672 Andy McCall 2331
        println!(
2332
            "  {} {}",
2333
            ui::caution(),
2334
            ui::warn("the result has conflicts; see oxy status")
2335
        );
7b9809e6 Andy McCall ↶ 2336
    }
98a1620a Andy McCall ↶ 2337
    where_now(&repo);
7b9809e6 Andy McCall ↶ 2338
    Ok(0)
2339
}
2340
728da0f9 Andy McCall ↶ 2341
pub fn squash(change: &str, into: &str) -> Result<i32> {
2342
    let repo = open()?;
2343
    let c = repo.resolve_change(change)?;
2344
    let d = repo.resolve_change(into)?;
2345
    let sp = ui::spinner("Squashing…");
2346
    let h = repo.squash(&c, &d)?;
2347
    let new = repo.store().get_change(&h)?;
75167672 Andy McCall 2348
    sp.done(&format!(
2349
        "{} into {} {}  {}",
2350
        ui::done("Squashed"),
2351
        ui::id(short_id(&new)),
2352
        ui::hash(format!("#{}", h.short(12))),
2353
        ui::subject(subject_of(&new.message))
2354
    ));
728da0f9 Andy McCall ↶ 2355
    Ok(0)
2356
}
2357
e266b7d4 Andy McCall ↶ 2358
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
728da0f9 Andy McCall ↶ 2359
    let repo = open()?;
2360
    let c = repo.resolve_change(change)?;
2361
    let mut heads = Vec::new();
2362
    for o in onto {
2363
        heads.extend(repo.resolve_heads(o)?);
2364
    }
2365
    let sp = ui::spinner("Rebasing…");
e266b7d4 Andy McCall ↶ 2366
    let h = match repo.rebase(&c, &heads) {
2367
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
2368
            let r = repo.rebase_into_working_copy(&c, &heads)?;
2369
            sp.done(&format!(
2370
                "{} {} into {}: now {}",
2371
                ui::done("Merged"),
2372
                onto.join(" "),
2373
                ui::bookmark(&repo.config.bookmark),
2374
                plural(r.heads.len(), "head"),
2375
            ));
2376
            if r.checked_out {
2377
                println!(
2378
                    "  {} {}",
2379
                    ui::caution(),
2380
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
2381
                );
2382
            } else {
2383
                println!(
2384
                    "  {} {}",
2385
                    ui::caution(),
2386
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
2387
                );
2388
            }
98a1620a Andy McCall ↶ 2389
            where_now(&repo);
e266b7d4 Andy McCall ↶ 2390
            return Ok(0);
2391
        }
2392
        other => other?,
2393
    };
728da0f9 Andy McCall ↶ 2394
    let new = repo.store().get_change(&h)?;
75167672 Andy McCall 2395
    sp.done(&format!(
2396
        "{} {} {}  {}",
2397
        ui::done("Rebased"),
2398
        ui::id(short_id(&new)),
2399
        ui::hash(format!("#{}", h.short(12))),
2400
        ui::dim(format!(
2401
            "now depends on {}",
2402
            plural(new.deps.len(), "change")
2403
        ))
2404
    ));
98a1620a Andy McCall ↶ 2405
    where_now(&repo);
728da0f9 Andy McCall ↶ 2406
    Ok(0)
2407
}