OXYGENHUB
# b582948f1912 oxygen / src / cli / workspace.rs
57.3 KiB · Rust · last changed Log from the state index, signature marks without reading changes (refs #41) 1 month ago source blame history raw
fce44ae9 Andy McCall ↶ 1
//! Commands that act on the local repository and working copy.
2
75167672 Andy McCall 3
use super::format::{
4
    author_name, deps_line, deps_of, plural, short_id, short_meta_id, signature_line,
5
    signature_mark, subject_of, when,
6
};
c6aa5bd9 Andy McCall ↶ 7
use super::json;
fce44ae9 Andy McCall ↶ 8
use super::open;
135212de Andy McCall ↶ 9
use super::ui;
fce44ae9 Andy McCall ↶ 10
use anyhow::Result;
94084087 Andy McCall ↶ 11
use oxy_core::objects::ChangeKind;
75167672 Andy McCall 12
use oxy_core::repo::SignatureStatus;
fce44ae9 Andy McCall ↶ 13
use oxy_core::repo::{render_change, ChangeStatus, Repo};
14
use std::path::PathBuf;
15
e02bf0cd Andy McCall ↶ 16
pub fn init(path: Option<PathBuf>, bare: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 17
    let path = path.unwrap_or(std::env::current_dir()?);
75167672 Andy McCall 18
    let repo = if bare {
19
        Repo::init_bare(&path)?
20
    } else {
21
        Repo::init(&path)?
22
    };
23
    println!(
24
        "{} {}oxy repository in {}",
25
        ui::done("Initialized"),
26
        if bare { "bare " } else { "" },
27
        ui::path(repo.root().display())
28
    );
29
    println!(
30
        "{}",
31
        ui::kv("bookmark", ui::bookmark(&repo.config.bookmark))
32
    );
33
    println!(
34
        "{}",
35
        ui::kv(
36
            "author",
37
            format!(
38
                "{} <{}>",
39
                ui::author(&repo.config.author_name),
40
                repo.config.author_email
41
            )
42
        )
43
    );
fce44ae9 Andy McCall ↶ 44
    Ok(0)
45
}
46
47
fn status_tag(s: ChangeStatus) -> &'static str {
48
    match s {
49
        ChangeStatus::Added => "A",
50
        ChangeStatus::Modified => "M",
51
        ChangeStatus::Removed => "D",
6e723b81 Andy McCall ↶ 52
        ChangeStatus::Renamed => "R",
fce44ae9 Andy McCall ↶ 53
        ChangeStatus::ModeChanged => "X",
54
        ChangeStatus::ConflictEdited => "C!",
6e723b81 Andy McCall ↶ 55
        ChangeStatus::Resolved => "V",
fce44ae9 Andy McCall ↶ 56
    }
57
}
58
50a046e4 Andy McCall ↶ 59
pub fn status(json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 60
    let repo = open()?;
da868d5d Andy McCall ↶ 61
    // Clean by the manifest alone: no history to load (oxygen#35).
62
    if !json && repo.clean_by_manifest()? {
63
        let (_, wc) = repo.working_copy()?;
64
        let heads = repo.bookmark_heads()?;
65
        println!(
66
            "{} {}{}working copy {}{}{}",
67
            ui::dim("On"),
68
            ui::bookmark(&repo.config.bookmark),
69
            ui::sep(),
70
            ui::id(wc.change_id.short(8)),
71
            ui::sep(),
72
            ui::dim(plural(heads.len(), "head"))
73
        );
74
        println!(
75
            "  {} {}",
76
            ui::ok(ui::glyph("✔", "*")),
77
            ui::dim("nothing to commit, working copy clean")
78
        );
79
        return Ok(0);
80
    }
135212de Andy McCall ↶ 81
    let sp = ui::spinner("Snapshotting the working copy…");
cc7a0056 Andy McCall ↶ 82
    let snap = repo.snapshot_status("oxy status")?;
4cce912a Andy McCall ↶ 83
    let heads = {
84
        let _t = oxy_core::timing::phase("status: heads");
85
        repo.bookmark_heads()?
86
    };
87
    let _drop = oxy_core::timing::phase("status: print and drop");
135212de Andy McCall ↶ 88
    sp.clear();
50a046e4 Andy McCall ↶ 89
    if json {
90
        println!("{}", repo.status_json(&snap)?);
75167672 Andy McCall 91
        return Ok(if snap.base_snapshot.is_conflicted() {
92
            2
93
        } else {
94
            0
95
        });
50a046e4 Andy McCall ↶ 96
    }
135212de Andy McCall ↶ 97
    println!(
94084087 Andy McCall ↶ 98
        "{} {}{}working copy {}{}{}",
99
        ui::dim("On"),
100
        ui::bookmark(&repo.config.bookmark),
101
        ui::sep(),
135212de Andy McCall ↶ 102
        ui::id(snap.wc.change_id.short(8)),
94084087 Andy McCall ↶ 103
        ui::sep(),
104
        ui::dim(plural(heads.len(), "head"))
135212de Andy McCall ↶ 105
    );
fce44ae9 Andy McCall ↶ 106
    if snap.statuses.is_empty() {
75167672 Andy McCall 107
        println!(
108
            "  {} {}",
109
            ui::ok(ui::glyph("✔", "*")),
110
            ui::dim("nothing to commit, working copy clean")
111
        );
94084087 Andy McCall ↶ 112
    } else {
113
        println!();
114
        for s in &snap.statuses {
75167672 Andy McCall 115
            println!(
116
                "  {} {}",
117
                ui::status_mark(status_tag(s.status)),
118
                ui::path(&s.path)
119
            );
94084087 Andy McCall ↶ 120
        }
fce44ae9 Andy McCall ↶ 121
    }
122
    if !snap.base_snapshot.is_conflicted() {
123
        return Ok(0);
124
    }
135212de Andy McCall ↶ 125
    println!();
75167672 Andy McCall 126
    println!(
127
        "{} {}",
128
        ui::section(ui::err("Conflicts")),
129
        ui::dim("edit the marked files, or the .oxy-conflict-N candidates, then commit")
130
    );
fce44ae9 Andy McCall ↶ 131
    for c in &snap.base_snapshot.tree.conflicts {
94084087 Andy McCall ↶ 132
        println!("  {} tree: {c:?}", ui::err(ui::glyph("✱", "!")));
fce44ae9 Andy McCall ↶ 133
    }
134
    for (p, f) in &snap.base_snapshot.files {
135
        if f.is_conflicted() {
75167672 Andy McCall 136
            let state = match snap
137
                .statuses
138
                .iter()
139
                .find(|s| s.path == *p)
140
                .map(|s| s.status)
141
            {
142
                Some(ChangeStatus::Resolved) => {
143
                    ui::ok(format!("{} resolved in working copy", ui::glyph("✔", "*")))
144
                }
145
                Some(ChangeStatus::ConflictEdited) => {
146
                    ui::warn(format!("{} markers remain", ui::glyph("‼", "!")))
147
                }
94084087 Andy McCall ↶ 148
                _ => ui::err(format!("{} unresolved", ui::glyph("✱", "!"))),
fce44ae9 Andy McCall ↶ 149
            };
135212de Andy McCall ↶ 150
            println!("  {}  {state}", ui::path(p));
fce44ae9 Andy McCall ↶ 151
        }
152
    }
153
    Ok(2)
154
}
155
75167672 Andy McCall 156
pub fn commit(
157
    message: &str,
158
    depends_on: &[String],
159
    paths: &[String],
160
    interactive: bool,
161
    hunks: &[usize],
162
) -> Result<i32> {
fce44ae9 Andy McCall ↶ 163
    let repo = open()?;
164
    let mut deps = Vec::new();
165
    for d in depends_on {
166
        deps.push(repo.resolve_change(d)?);
167
    }
c6aa5bd9 Andy McCall ↶ 168
    let selection = if !hunks.is_empty() {
169
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
170
    } else if interactive {
957fee30 Andy McCall ↶ 171
        let (_, hunks) = repo.hunks()?;
172
        if hunks.is_empty() {
173
            anyhow::bail!("nothing to commit: the working copy matches its base");
174
        }
75167672 Andy McCall 175
        let hunks: Vec<_> = hunks
176
            .into_iter()
177
            .filter(|h| {
178
                paths.is_empty()
179
                    || paths.iter().any(|p| {
180
                        h.path == *p || h.path.starts_with(&format!("{}/", p.trim_end_matches('/')))
181
                    })
182
            })
183
            .collect();
957fee30 Andy McCall ↶ 184
        let mut chosen = Vec::new();
185
        let stdin = std::io::stdin();
186
        let mut take_rest = false;
187
        for (n, h) in hunks.iter().enumerate() {
188
            if take_rest {
189
                chosen.push(h.index);
190
                continue;
191
            }
75167672 Andy McCall 192
            println!(
193
                "{} {} {}",
194
                ui::section(format!("hunk {} of {}", n + 1, hunks.len())),
195
                ui::path(&h.path),
196
                ui::dim(format!("(#{})", h.index))
197
            );
957fee30 Andy McCall ↶ 198
            for line in h.text.lines() {
75167672 Andy McCall 199
                let styled = if line.starts_with('+') {
200
                    ui::ok(line)
201
                } else if line.starts_with('-') {
202
                    ui::err(line)
203
                } else {
204
                    ui::dim(line)
205
                };
957fee30 Andy McCall ↶ 206
                println!("  {styled}");
207
            }
208
            loop {
75167672 Andy McCall 209
                print!(
210
                    "{} ",
211
                    ui::warn("Commit this hunk? [y]es [n]o [a]ll remaining [q]uit:")
212
                );
957fee30 Andy McCall ↶ 213
                use std::io::Write as _;
214
                std::io::stdout().flush()?;
215
                let mut answer = String::new();
216
                if stdin.read_line(&mut answer)? == 0 {
217
                    anyhow::bail!("aborted");
218
                }
219
                match answer.trim() {
220
                    "y" | "Y" => {
221
                        chosen.push(h.index);
222
                        break;
223
                    }
224
                    "n" | "N" | "" => break,
225
                    "a" | "A" => {
226
                        chosen.push(h.index);
227
                        take_rest = true;
228
                        break;
229
                    }
230
                    "q" | "Q" => anyhow::bail!("aborted; nothing committed"),
231
                    _ => continue,
232
                }
233
            }
234
        }
235
        if chosen.is_empty() {
236
            anyhow::bail!("no hunks chosen; nothing committed");
237
        }
238
        oxy_core::repo::Selection::Hunks(chosen)
239
    } else if paths.is_empty() {
240
        oxy_core::repo::Selection::All
241
    } else {
242
        oxy_core::repo::Selection::Paths(paths.to_vec())
243
    };
135212de Andy McCall ↶ 244
    let sp = ui::spinner("Committing…");
957fee30 Andy McCall ↶ 245
    let h = repo.commit_selection(message, &deps, &selection)?;
fce44ae9 Andy McCall ↶ 246
    let c = repo.store().get_change(&h)?;
75167672 Andy McCall 247
    sp.done(&format!(
248
        "{} {} {}  {}",
249
        ui::done("Committed"),
250
        ui::id(short_id(&c)),
251
        ui::hash(format!("#{}", h.short(12))),
252
        ui::subject(subject_of(message))
253
    ));
957fee30 Andy McCall ↶ 254
    if !matches!(selection, oxy_core::repo::Selection::All) {
8ab265dc Andy McCall ↶ 255
        let rest = repo.snapshot_status("oxy commit")?;
957fee30 Andy McCall ↶ 256
        if !rest.statuses.is_empty() {
75167672 Andy McCall 257
            println!(
258
                "  {} {}",
259
                ui::note(),
260
                ui::dim(format!(
261
                    "{} left uncommitted",
262
                    plural(rest.statuses.len(), "path")
263
                ))
264
            );
957fee30 Andy McCall ↶ 265
        }
266
    }
267
    Ok(0)
268
}
269
270
pub fn blame(path: &str, json: bool) -> Result<i32> {
271
    let repo = open()?;
272
    let lines = repo.blame(path)?;
273
    if json {
274
        let items = lines.iter().map(|l| {
275
            format!(
276
                "{{\"line\":{},\"change_id\":{},\"hash\":{},\"index\":{},\"author\":{},\"when_ms\":{}}}",
277
                l.line,
278
                oxy_core::repo::json_str(&l.change_id.to_hex()),
279
                oxy_core::repo::json_str(&l.hash.to_hex()),
280
                l.index,
281
                oxy_core::repo::json_str(&l.author),
282
                l.when_ms
283
            )
284
        });
285
        println!("{}", oxy_core::repo::json_array(items));
286
        return Ok(0);
287
    }
75167672 Andy McCall 288
    let width = lines
289
        .iter()
290
        .map(|l| l.author.chars().count())
291
        .max()
292
        .unwrap_or(0)
293
        .min(20);
957fee30 Andy McCall ↶ 294
    let digits = lines.len().to_string().len();
295
    for l in &lines {
296
        let author: String = l.author.chars().take(20).collect();
297
        let text = String::from_utf8_lossy(&l.text);
298
        println!(
299
            "{} {} {} {:>digits$}{} {}",
300
            ui::id(l.change_id.short(8)),
301
            ui::author(format!("{author:<width$}")),
302
            ui::dim(ui::ago(l.when_ms)),
303
            l.line,
304
            ui::dim(ui::glyph("│", "|")),
305
            text.trim_end_matches('\n')
306
        );
307
    }
308
    Ok(0)
309
}
310
311
fn bisect_report(repo: &Repo, step: &oxy_core::repo::BisectStep) -> Result<i32> {
312
    use oxy_core::repo::BisectStep::*;
313
    match step {
314
        NeedMarks { good, bad } => {
75167672 Andy McCall 315
            println!(
316
                "{} {} {}",
317
                ui::note(),
318
                ui::dim(format!("{good} good, {bad} bad;")),
319
                ui::dim(if *good == 0 {
320
                    "mark a known-good change or bookmark: oxy bisect good CHANGE"
321
                } else {
322
                    "mark a known-bad change or bookmark: oxy bisect bad CHANGE"
323
                })
324
            );
957fee30 Andy McCall ↶ 325
            Ok(0)
326
        }
75167672 Andy McCall 327
        Testing {
328
            heads,
329
            remaining,
330
            steps_left,
331
        } => {
332
            println!(
333
                "{} {} {}",
334
                ui::done("Testing"),
335
                ui::dim(format!(
336
                    "{} in the state under test;",
337
                    plural(heads.len(), "head")
338
                )),
339
                ui::dim(format!(
340
                    "{remaining} candidates left, about {steps_left} more steps"
341
                ))
342
            );
343
            println!(
344
                "  {} {}",
345
                ui::note(),
346
                ui::dim("run your test, then oxy bisect good | bad | skip")
347
            );
957fee30 Andy McCall ↶ 348
            Ok(0)
349
        }
350
        Found { culprit } => {
351
            let c = repo.store().get_change(culprit)?;
75167672 Andy McCall 352
            println!(
353
                "{} {} {}  {}",
354
                ui::done("Found"),
355
                ui::id(short_id(&c)),
356
                ui::hash(format!("#{}", culprit.short(12))),
357
                ui::subject(subject_of(&c.message))
358
            );
957fee30 Andy McCall ↶ 359
            println!("  {} {}", ui::note(), ui::dim("the first change whose inclusion makes the state bad; oxy bisect reset to return"));
360
            Ok(0)
361
        }
362
        Inconclusive { candidates } => {
75167672 Andy McCall 363
            println!(
364
                "{} {}",
365
                ui::caution(),
366
                ui::warn(format!(
367
                    "every remaining candidate was skipped ({}); oxy bisect reset to return",
368
                    plural(candidates.len(), "change")
369
                ))
370
            );
957fee30 Andy McCall ↶ 371
            Ok(1)
372
        }
373
    }
374
}
375
376
pub fn bisect_start() -> Result<i32> {
377
    let repo = open()?;
378
    repo.bisect_start()?;
75167672 Andy McCall 379
    println!(
380
        "{} bisect; {}",
381
        ui::done("Started"),
382
        ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE")
383
    );
957fee30 Andy McCall ↶ 384
    Ok(0)
385
}
386
387
pub fn bisect_mark(good: Option<bool>, changes: &[String]) -> Result<i32> {
388
    let repo = open()?;
389
    let mut heads = Vec::new();
390
    for c in changes {
391
        heads.extend(repo.resolve_heads(c)?);
392
    }
393
    let step = repo.bisect_mark(good, &heads)?;
394
    bisect_report(&repo, &step)
395
}
396
397
pub fn bisect_run(command: &[String]) -> Result<i32> {
398
    let repo = open()?;
399
    let step = repo.bisect_run(command)?;
400
    bisect_report(&repo, &step)
401
}
402
c6aa5bd9 Andy McCall ↶ 403
pub fn bisect_status(as_json: bool) -> Result<i32> {
957fee30 Andy McCall ↶ 404
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 405
    if as_json {
406
        use oxy_core::repo::BisectStep::*;
407
        let v = match repo.bisect_status()? {
408
            None => "null".to_string(),
75167672 Andy McCall 409
            Some(NeedMarks { good, bad }) => json::obj([
410
                ("state", json::s("need-marks")),
411
                ("good", json::n(good)),
412
                ("bad", json::n(bad)),
413
            ]),
414
            Some(Testing {
415
                heads,
416
                remaining,
417
                steps_left,
418
            }) => json::obj([
419
                ("state", json::s("testing")),
420
                ("heads", json::hashes(&heads)),
421
                ("remaining", json::n(remaining)),
422
                ("steps_left", json::n(steps_left)),
423
            ]),
424
            Some(Found { culprit }) => json::obj([
425
                ("state", json::s("found")),
426
                ("culprit", json::s(&culprit.to_hex())),
427
            ]),
428
            Some(Inconclusive { candidates }) => json::obj([
429
                ("state", json::s("inconclusive")),
430
                ("candidates", json::hashes(&candidates)),
431
            ]),
c6aa5bd9 Andy McCall ↶ 432
        };
433
        println!("{v}");
434
        return Ok(0);
435
    }
957fee30 Andy McCall ↶ 436
    match repo.bisect_status()? {
437
        None => {
438
            println!("{}", ui::dim("No bisect in progress."));
439
            Ok(0)
440
        }
441
        Some(step) => bisect_report(&repo, &step),
442
    }
443
}
444
445
pub fn bisect_reset() -> Result<i32> {
446
    let repo = open()?;
447
    repo.bisect_reset()?;
448
    println!("{} bisect; working copy restored", ui::done("Reset"));
fce44ae9 Andy McCall ↶ 449
    Ok(0)
450
}
451
94084087 Andy McCall ↶ 452
/// The log: one entry per change, newest first, joined by a rail. The
453
/// default view is the subject and a metadata line; `verbose` adds the full
454
/// message, dependencies, and the authenticating key.
c6aa5bd9 Andy McCall ↶ 455
fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
456
    Ok(match repo.authenticate_change(h)? {
457
        SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]),
75167672 Andy McCall 458
        SignatureStatus::Valid {
459
            key,
460
            name,
461
            email,
462
            sealed,
463
            revoked,
464
        } => json::obj([
c6aa5bd9 Andy McCall ↶ 465
            ("status", json::s(if sealed { "sealed" } else { "signed" })),
466
            ("key", json::s(&key.to_hex())),
467
            ("name", json::s(&name)),
468
            ("email", json::s(&email)),
469
            ("revoked", json::b(revoked)),
470
        ]),
75167672 Andy McCall 471
        SignatureStatus::Invalid(why) => {
472
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
473
        }
c6aa5bd9 Andy McCall ↶ 474
    })
475
}
476
477
fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result<String> {
478
    let c = &e.change;
479
    Ok(json::obj([
480
        ("hash", json::s(&e.hash.to_hex())),
481
        ("change_id", json::s(&c.change_id.to_hex())),
482
        ("author", json::s(&author_name(repo, c))),
483
        ("author_key", json::s(&c.author.to_hex())),
484
        ("when_ms", json::n(c.hlc.wall_ms)),
485
        ("message", json::s(&c.message)),
486
        ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())),
487
        ("deps", json::hashes(&c.deps)),
488
        ("head", json::b(e.is_head)),
489
        ("working_copy", json::b(e.is_working_copy)),
75167672 Andy McCall 490
        (
491
            "signature",
492
            if e.is_working_copy {
493
                "null".into()
494
            } else {
495
                signature_json(repo, &e.hash)?
496
            },
497
        ),
c6aa5bd9 Andy McCall ↶ 498
    ]))
499
}
500
83d61e80 Andy McCall ↶ 501
/// `START,END:PATH` for `oxy log -L`.
502
fn parse_line_range(spec: &str) -> Result<(usize, usize, &str)> {
503
    let bad = || anyhow::anyhow!("-L {spec}: expected START,END:PATH, as 10,24:src/lib.rs");
504
    let (range, path) = spec.split_once(':').ok_or_else(bad)?;
505
    let (a, b) = range.split_once(',').ok_or_else(bad)?;
506
    Ok((
507
        a.trim().parse().map_err(|_| bad())?,
508
        b.trim().parse().map_err(|_| bad())?,
509
        path,
510
    ))
511
}
512
513
pub fn log(
514
    limit: Option<usize>,
515
    verbose: bool,
516
    path: Option<&str>,
517
    lines: Option<&str>,
518
    as_json: bool,
519
) -> Result<i32> {
fce44ae9 Andy McCall ↶ 520
    let repo = open()?;
69816d68 Andy McCall ↶ 521
    // Whether the working copy is clean and conflicted: from the manifest
522
    // when it proves the working copy clean, else from a snapshot.
523
    let (conflicted, clean) = if repo.clean_by_manifest()? {
524
        (false, true)
525
    } else {
526
        let snap = repo.snapshot_status("oxy log")?;
527
        (snap.base_snapshot.is_conflicted(), snap.statuses.is_empty())
528
    };
4cce912a Andy McCall ↶ 529
    let listing = oxy_core::timing::phase("log: entries");
83d61e80 Andy McCall ↶ 530
    let entries = match (path, lines) {
531
        (_, Some(spec)) => {
532
            let (first, last, p) = parse_line_range(spec)?;
69816d68 Andy McCall ↶ 533
            let (_, wc) = repo.working_copy()?;
534
            let base = repo.load_state_history(&wc.deps)?.maximal(&wc.deps);
535
            repo.line_history(&base, p, first, last)?
83d61e80 Andy McCall ↶ 536
        }
537
        (Some(p), None) => repo.log_for_path(p)?,
538
        (None, None) => repo.log()?,
c6aa5bd9 Andy McCall ↶ 539
    };
4cce912a Andy McCall ↶ 540
    drop(listing);
541
    let _print = oxy_core::timing::phase("log: print");
c6aa5bd9 Andy McCall ↶ 542
    if as_json {
543
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
544
        let mut items = Vec::new();
545
        for e in entries.iter().take(shown) {
546
            items.push(log_entry_json(&repo, e)?);
547
        }
75167672 Andy McCall 548
        println!(
549
            "{}",
550
            json::obj([
551
                ("bookmark", json::s(&repo.config.bookmark)),
552
                ("total", json::n(entries.len())),
553
                ("changes", json::arr(items))
554
            ])
555
        );
c6aa5bd9 Andy McCall ↶ 556
        return Ok(0);
557
    }
94084087 Andy McCall ↶ 558
    let total = entries.len();
559
    let shown = limit.unwrap_or(total).min(total);
560
    let rail = ui::rail();
561
    for (i, e) in entries.iter().take(shown).enumerate() {
fce44ae9 Andy McCall ↶ 562
        let c = &e.change;
75167672 Andy McCall 563
        let bullet = ui::log_bullet(
564
            e.is_working_copy,
565
            e.is_head,
566
            e.is_working_copy && conflicted,
567
        );
94084087 Andy McCall ↶ 568
        let mut labels = Vec::new();
fce44ae9 Andy McCall ↶ 569
        if e.is_working_copy {
94084087 Andy McCall ↶ 570
            labels.push(ui::warn("working copy"));
fce44ae9 Andy McCall ↶ 571
        }
94084087 Andy McCall ↶ 572
        if c.kind == ChangeKind::Resolution {
573
            labels.push(ui::warn("resolution"));
fce44ae9 Andy McCall ↶ 574
        }
75167672 Andy McCall 575
        let labels = if labels.is_empty() {
576
            String::new()
577
        } else {
578
            format!(
579
                " {}{}{}",
580
                ui::dim("("),
581
                labels.join(ui::dim(", ").as_str()),
582
                ui::dim(")")
583
            )
584
        };
94084087 Andy McCall ↶ 585
        let subject = if e.is_working_copy && c.message.is_empty() {
69816d68 Andy McCall ↶ 586
            ui::dim(if clean {
75167672 Andy McCall 587
                "(clean)"
588
            } else {
589
                "(uncommitted changes)"
590
            })
94084087 Andy McCall ↶ 591
        } else {
592
            ui::subject(subject_of(&c.message))
593
        };
594
        println!("{bullet} {}{labels}  {subject}", ui::id(short_meta_id(c)));
595
        let meta = format!(
596
            "{}{}{}{}{}{}{}",
597
            ui::hash(format!("#{}", e.hash.short(12))),
598
            ui::sep(),
599
            ui::author(author_name(&repo, c)),
600
            ui::sep(),
601
            ui::dim(ui::ago(c.hlc.wall_ms)),
602
            ui::sep(),
75167672 Andy McCall 603
            if e.is_working_copy {
604
                ui::dim("not yet committed")
605
            } else {
4cce912a Andy McCall ↶ 606
                signature_mark(&repo, &e.hash, Some(c))?
75167672 Andy McCall 607
            }
94084087 Andy McCall ↶ 608
        );
609
        println!("{rail} {meta}");
610
        if verbose {
611
            if !e.is_working_copy {
75167672 Andy McCall 612
                println!(
613
                    "{rail} {}",
614
                    ui::dim(format!(
615
                        "{} {}",
616
                        when(c.hlc.wall_ms),
617
                        signature_line(&repo, &e.hash)?
618
                    ))
619
                );
94084087 Andy McCall ↶ 620
            }
621
            if !c.deps.is_empty() {
75167672 Andy McCall 622
                println!(
623
                    "{rail} {} {}",
624
                    ui::dim(ui::glyph("↳", "->")),
625
                    ui::dim(deps_of(&c.deps))
626
                );
94084087 Andy McCall ↶ 627
            }
75167672 Andy McCall 628
            let body: Vec<&str> = c
629
                .message
630
                .lines()
631
                .skip(1)
632
                .skip_while(|l| l.trim().is_empty())
633
                .collect();
94084087 Andy McCall ↶ 634
            if !body.is_empty() {
635
                println!("{rail}");
636
                for line in body {
637
                    println!("{rail}   {line}");
638
                }
639
            }
fce44ae9 Andy McCall ↶ 640
        }
94084087 Andy McCall ↶ 641
        if i + 1 < shown {
642
            println!("{rail}");
fce44ae9 Andy McCall ↶ 643
        }
644
    }
94084087 Andy McCall ↶ 645
    if shown < total {
75167672 Andy McCall 646
        println!(
647
            "{}",
648
            ui::dim(format!(
649
                "{} {} more; pass -n to see them",
650
                ui::glyph("…", "..."),
651
                total - shown
652
            ))
653
        );
94084087 Andy McCall ↶ 654
    }
fce44ae9 Andy McCall ↶ 655
    Ok(0)
656
}
657
c6aa5bd9 Andy McCall ↶ 658
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
659
    let repo = open()?;
660
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
661
    if as_json {
662
        let files = repo.diff_files(hash.as_ref())?;
663
        let items = files.iter().map(|f| {
664
            json::obj([
665
                ("path", json::s(&f.path)),
666
                ("kind", json::s(&f.kind)),
667
                ("from", json::opt(f.from.as_deref(), json::s)),
668
                (
669
                    "hunks",
670
                    json::arr(f.hunks.iter().map(|h| {
671
                        json::obj([
672
                            ("base_line", json::n(h.base_line)),
75167672 Andy McCall 673
                            (
674
                                "added",
675
                                json::arr(
676
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
677
                                ),
678
                            ),
679
                            (
680
                                "removed",
681
                                json::arr(h.removed.iter().map(|(n, l)| {
682
                                    json::obj([
683
                                        ("line", json::n(*n)),
684
                                        ("text", json::s(&String::from_utf8_lossy(l))),
685
                                    ])
686
                                })),
687
                            ),
c6aa5bd9 Andy McCall ↶ 688
                        ])
689
                    })),
690
                ),
691
            ])
692
        });
75167672 Andy McCall 693
        println!(
694
            "{}",
695
            json::obj([
696
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
697
                ("files", json::arr(items))
698
            ])
699
        );
c6aa5bd9 Andy McCall ↶ 700
        return Ok(0);
701
    }
702
    match hash {
703
        Some(h) => {
704
            let c = repo.store().get_change(&h)?;
8ab265dc Andy McCall ↶ 705
            let (base, snapshot) = repo.change_base(&c)?;
c6aa5bd9 Andy McCall ↶ 706
            print!("{}", render_change(&c, &base, &snapshot));
707
        }
708
        None => {
8ab265dc Andy McCall ↶ 709
            let snap = repo.snapshot_status("oxy diff")?;
75167672 Andy McCall 710
            print!(
711
                "{}",
712
                render_change(&snap.wc, &snap.base, &snap.base_snapshot)
713
            );
c6aa5bd9 Andy McCall ↶ 714
        }
715
    }
716
    Ok(0)
717
}
718
719
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
720
    let repo = open()?;
721
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
722
    let bytes = repo.file_at(path, heads.as_deref())?;
723
    use std::io::Write as _;
724
    std::io::stdout().write_all(&bytes)?;
725
    Ok(0)
726
}
727
728
pub fn root(as_json: bool) -> Result<i32> {
729
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
730
        if as_json {
731
            println!("null");
732
        }
733
        return Ok(1);
734
    };
735
    if as_json {
75167672 Andy McCall 736
        println!(
737
            "{}",
738
            json::obj([
739
                ("root", json::s(&repo.root().to_string_lossy())),
740
                ("workspace", json::s(&repo.workspace().to_hex())),
741
                ("bookmark", json::s(&repo.config.bookmark))
742
            ])
743
        );
c6aa5bd9 Andy McCall ↶ 744
    } else {
745
        println!("{}", repo.root().display());
746
    }
747
    Ok(0)
748
}
749
750
pub fn version(as_json: bool) -> Result<i32> {
751
    if as_json {
75167672 Andy McCall 752
        println!(
753
            "{}",
754
            json::obj([
755
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
e293c90d Andy McCall ↶ 756
                // What was built: a release's or install's `oxy describe`,
757
                // a Flow build's heads, or "local build".
758
                ("build", json::s(env!("OXY_BUILD_ID"))),
75167672 Andy McCall 759
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
760
                ("format", json::n(2))
761
            ])
762
        );
c6aa5bd9 Andy McCall ↶ 763
    } else {
75167672 Andy McCall 764
        println!(
765
            "oxy {} (repository format 2, protocol {})",
e293c90d Andy McCall ↶ 766
            env!("OXY_VERSION_LONG"),
75167672 Andy McCall 767
            oxy_core::protocol::PROTOCOL_VERSION
768
        );
c6aa5bd9 Andy McCall ↶ 769
    }
770
    Ok(0)
771
}
772
773
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
774
    let repo = open()?;
775
    if paths.is_empty() && hunks.is_empty() {
776
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
777
    }
778
    let mut n = 0;
779
    if !hunks.is_empty() {
780
        n += repo.discard_hunks(hunks)?;
781
    }
782
    if !paths.is_empty() {
783
        n += repo.discard(paths)?;
784
    }
75167672 Andy McCall 785
    println!(
786
        "{} {} restored to the working copy's base",
787
        ui::done("Discarded"),
788
        plural(n, "path")
789
    );
c6aa5bd9 Andy McCall ↶ 790
    Ok(0)
791
}
792
793
pub fn hunks(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 794
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 795
    let (_, hunks) = repo.hunks()?;
796
    if as_json {
75167672 Andy McCall 797
        println!(
798
            "{}",
799
            json::arr(hunks.iter().map(|h| json::obj([
800
                ("index", json::n(h.index)),
801
                ("path", json::s(&h.path)),
802
                ("text", json::s(&h.text))
803
            ])))
804
        );
c6aa5bd9 Andy McCall ↶ 805
        return Ok(0);
806
    }
807
    if hunks.is_empty() {
75167672 Andy McCall 808
        println!(
809
            "{}",
810
            ui::dim("No hunks: the working copy matches its base.")
811
        );
c6aa5bd9 Andy McCall ↶ 812
    }
813
    for h in &hunks {
75167672 Andy McCall 814
        println!(
815
            "{} {}",
816
            ui::section(format!("hunk {}", h.index)),
817
            ui::path(&h.path)
818
        );
c6aa5bd9 Andy McCall ↶ 819
        for line in h.text.lines() {
75167672 Andy McCall 820
            let styled = if line.starts_with('+') {
821
                ui::ok(line)
822
            } else if line.starts_with('-') {
823
                ui::err(line)
824
            } else {
825
                ui::dim(line)
826
            };
c6aa5bd9 Andy McCall ↶ 827
            println!("  {styled}");
828
        }
829
    }
fce44ae9 Andy McCall ↶ 830
    Ok(0)
831
}
832
c6aa5bd9 Andy McCall ↶ 833
pub fn show(change: &str, as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 834
    let repo = open()?;
cc7a0056 Andy McCall ↶ 835
    repo.snapshot_status("oxy show")?;
fce44ae9 Andy McCall ↶ 836
    let h = repo.resolve_change(change)?;
837
    let c = repo.store().get_change(&h)?;
c6aa5bd9 Andy McCall ↶ 838
    if as_json {
839
        let files = repo.diff_files(Some(&h))?;
840
        let heads = repo.bookmark_heads()?;
75167672 Andy McCall 841
        let entry = oxy_core::repo::LogEntry {
842
            hash: h,
843
            change: oxy_core::state::ChangeMeta::of(&c),
844
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
845
            is_head: heads.contains(&h),
846
        };
c6aa5bd9 Andy McCall ↶ 847
        let mut body = log_entry_json(&repo, &entry)?;
848
        body.pop();
75167672 Andy McCall 849
        body.push_str(&format!(
850
            ",{}:{}}}",
851
            json::s("files"),
852
            json::arr(files.iter().map(|f| json::obj([
853
                ("path", json::s(&f.path)),
854
                ("kind", json::s(&f.kind)),
855
                ("from", json::opt(f.from.as_deref(), json::s))
856
            ])))
857
        ));
c6aa5bd9 Andy McCall ↶ 858
        println!("{body}");
859
        return Ok(0);
860
    }
75167672 Andy McCall 861
    println!(
862
        "{} {} {}",
863
        ui::section("change"),
864
        ui::id(short_id(&c)),
865
        ui::hash(format!("#{h}"))
866
    );
94084087 Andy McCall ↶ 867
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
75167672 Andy McCall 868
    println!(
869
        "{}",
870
        ui::kv(
871
            "author",
872
            ui::author(author_name(&repo, &oxy_core::state::ChangeMeta::of(&c)))
873
        )
874
    );
875
    println!(
876
        "{}",
877
        ui::kv(
878
            "date",
879
            format!(
880
                "{} {}",
881
                when(c.hlc.wall_ms),
882
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
883
            )
884
        )
885
    );
94084087 Andy McCall ↶ 886
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
887
    println!("{}", ui::kv("sig", signature_line(&repo, &h)?));
888
    println!();
75167672 Andy McCall 889
    for line in (if c.message.is_empty() {
890
        "(no description)"
891
    } else {
892
        &c.message
893
    })
894
    .lines()
895
    {
94084087 Andy McCall ↶ 896
        println!("    {line}");
897
    }
898
    println!();
fce44ae9 Andy McCall ↶ 899
    print!("{}", repo.describe_change(&h)?);
900
    Ok(0)
901
}
902
1c2bd9ab Andy McCall ↶ 903
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 904
    let repo = open()?;
905
    let heads = if changes.is_empty() {
906
        repo.bookmark_heads()?
907
    } else {
132b884b Andy McCall ↶ 908
        let mut heads = Vec::new();
909
        for c in changes {
910
            heads.extend(repo.resolve_heads(c)?);
911
        }
912
        heads
fce44ae9 Andy McCall ↶ 913
    };
75167672 Andy McCall 914
    let spec = if changes.is_empty() {
915
        repo.config.bookmark.clone()
916
    } else {
917
        changes.join(" ")
918
    };
135212de Andy McCall ↶ 919
    let sp = ui::spinner(&format!("Checking out {spec}…"));
1c2bd9ab Andy McCall ↶ 920
    let command = format!("oxy checkout {spec}");
921
    let (r, carried) = if carry {
922
        repo.checkout_carry(&heads, &spec, &command)?
923
    } else {
924
        (repo.checkout(&heads, discard, &command)?, vec![])
925
    };
75167672 Andy McCall 926
    sp.done(&format!(
1c2bd9ab Andy McCall ↶ 927
        "{} on {}: {} written, {} removed{}",
75167672 Andy McCall 928
        ui::done("Working copy"),
929
        ui::bookmark(&spec),
930
        plural(r.written, "file"),
1c2bd9ab Andy McCall ↶ 931
        r.removed,
932
        if carried.is_empty() {
933
            String::new()
934
        } else {
935
            format!("; carried {}", plural(carried.len(), "changed path"))
936
        }
75167672 Andy McCall 937
    ));
4dee277c Andy McCall ↶ 938
    for n in &r.notes {
939
        println!("  {} {n}", ui::note());
940
    }
fce44ae9 Andy McCall ↶ 941
    if r.conflicted {
75167672 Andy McCall 942
        println!(
943
            "  {} {}",
944
            ui::caution(),
945
            ui::warn("this state has conflicts; see oxy status")
946
        );
fce44ae9 Andy McCall ↶ 947
    }
948
    Ok(0)
949
}
950
c6aa5bd9 Andy McCall ↶ 951
pub fn resolve(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 952
    let repo = open()?;
953
    let snap = repo.snapshot("oxy resolve")?;
c6aa5bd9 Andy McCall ↶ 954
    if as_json {
955
        println!("{}", repo.status_json(&snap)?);
75167672 Andy McCall 956
        return Ok(if snap.base_snapshot.is_conflicted() {
957
            2
958
        } else {
959
            0
960
        });
c6aa5bd9 Andy McCall ↶ 961
    }
fce44ae9 Andy McCall ↶ 962
    if !snap.base_snapshot.is_conflicted() {
963
        println!("The working copy's base has no conflicts.");
964
        return Ok(0);
965
    }
966
    let mut remaining = 0;
967
    for (p, f) in &snap.base_snapshot.files {
968
        if !f.is_conflicted() {
969
            continue;
970
        }
75167672 Andy McCall 971
        match snap
972
            .statuses
973
            .iter()
974
            .find(|s| s.path == *p)
975
            .map(|s| s.status)
976
        {
fce44ae9 Andy McCall ↶ 977
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
978
            Some(ChangeStatus::ConflictEdited) => {
979
                remaining += 1;
980
                println!("markers    {p}");
981
            }
982
            _ => {
983
                remaining += 1;
984
                println!("unresolved {p}");
985
            }
986
        }
987
    }
988
    for c in &snap.base_snapshot.tree.conflicts {
989
        remaining += 1;
990
        println!("tree       {c:?}");
991
    }
992
    if remaining == 0 {
993
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
994
        Ok(0)
995
    } else {
996
        Ok(2)
997
    }
998
}
999
1000
pub fn undo() -> Result<i32> {
1001
    let repo = open()?;
1002
    let op = repo.undo()?;
94084087 Andy McCall ↶ 1003
    println!("{} now at: {}", ui::done("Undone;"), ui::dim(&op.command));
fce44ae9 Andy McCall ↶ 1004
    Ok(0)
1005
}
1006
c6aa5bd9 Andy McCall ↶ 1007
pub fn op_log(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 1008
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 1009
    if as_json {
1010
        let ops = repo.op_log()?;
1011
        println!(
1012
            "{}",
1013
            json::arr(ops.iter().enumerate().map(|(i, (r, op))| {
1014
                json::obj([
1015
                    ("id", json::s(&r.to_hex())),
1016
                    ("when_ms", json::n(op.hlc.wall_ms)),
1017
                    ("command", json::s(&op.command)),
1018
                    ("snapshot", json::b(op.command.ends_with("(snapshot)"))),
1019
                    ("current", json::b(i == 0)),
1020
                ])
1021
            }))
1022
        );
1023
        return Ok(0);
1024
    }
fce44ae9 Andy McCall ↶ 1025
    for (i, (r, op)) in repo.op_log()?.into_iter().enumerate() {
75167672 Andy McCall 1026
        let bullet = if i == 0 {
1027
            ui::ok(ui::glyph("●", "@"))
1028
        } else {
1029
            ui::dim(ui::glyph("○", "o"))
1030
        };
94084087 Andy McCall ↶ 1031
        let cmd = subject_of(&op.command).split("\\n").next().unwrap_or("");
75167672 Andy McCall 1032
        println!(
1033
            "{bullet} {}{}{}  {}",
1034
            ui::hash(r.short(12)),
1035
            ui::sep(),
1036
            ui::dim(format!("{:<16}", ui::ago(op.hlc.wall_ms))),
1037
            if i == 0 {
1038
                ui::subject(cmd)
1039
            } else {
1040
                cmd.to_string()
1041
            }
1042
        );
fce44ae9 Andy McCall ↶ 1043
    }
1044
    Ok(0)
1045
}
d02e545d Andy McCall ↶ 1046
ba160f60 Andy McCall ↶ 1047
pub fn gc(now: bool) -> Result<i32> {
d02e545d Andy McCall ↶ 1048
    let repo = open()?;
135212de Andy McCall ↶ 1049
    let sp = ui::spinner("Packing and pruning…");
ba160f60 Andy McCall ↶ 1050
    let r = repo.gc(now)?;
135212de Andy McCall ↶ 1051
    sp.clear();
ba160f60 Andy McCall ↶ 1052
    if r.packed.objects > 0 {
d02e545d Andy McCall ↶ 1053
        println!(
da652d63 Andy McCall ↶ 1054
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
1055
            plural(r.packed.objects, "object"),
ba160f60 Andy McCall ↶ 1056
            r.packed.raw_bytes,
1057
            r.packed.packed_bytes,
1058
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
d02e545d Andy McCall ↶ 1059
        );
1060
    }
75167672 Andy McCall 1061
    println!(
1062
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
ba160f60 Andy McCall ↶ 1063
        plural(r.reachable, "object"),
1064
        plural(r.pruned.objects, "unreachable object"),
1065
        r.pruned.bytes,
75167672 Andy McCall 1066
        if r.pruned.deferred > 0 {
1067
            format!(
1068
                "; {} deferred by the grace period (use --now)",
1069
                plural(r.pruned.deferred, "object")
1070
            )
1071
        } else {
1072
            String::new()
1073
        },
1074
        if r.merged_packs > 0 {
1075
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1076
        } else {
1077
            String::new()
1078
        },
ba160f60 Andy McCall ↶ 1079
        plural(repo.store().pack_count(), "pack")
1080
    );
d02e545d Andy McCall ↶ 1081
    Ok(0)
1082
}
614541c3 Andy McCall ↶ 1083
3e5772cc Andy McCall ↶ 1084
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
1085
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1086
    use oxy_core::repo::Health;
1087
    let repo = open()?;
1088
    let sp = ui::spinner(if offline {
1089
        "Checking…"
1090
    } else {
1091
        "Checking, and contacting remotes…"
1092
    });
1093
    let r = repo.doctor(!offline);
1094
    sp.clear();
1095
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
1096
    let word = |h: Health| match h {
1097
        Health::Ok => "ok",
1098
        Health::Warn => "warning",
1099
        Health::Fail => "fail",
1100
    };
1101
    if as_json {
1102
        let checks: Vec<String> = r
1103
            .checks
1104
            .iter()
1105
            .map(|c| {
1106
                json::obj([
1107
                    ("area", json::s(&c.area)),
1108
                    ("health", json::s(word(c.health))),
1109
                    ("message", json::s(&c.message)),
1110
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
1111
                ])
1112
            })
1113
            .collect();
1114
        println!(
1115
            "{}",
1116
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1117
        );
1118
        return Ok(code);
1119
    }
1120
    let mut last = "";
1121
    for c in &r.checks {
1122
        if c.area != last {
1123
            println!("{}", ui::section(&c.area));
1124
            last = &c.area;
1125
        }
1126
        let mark = match c.health {
1127
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
1128
            Health::Warn => ui::caution(),
1129
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1130
        };
1131
        println!("  {mark} {}", c.message);
1132
        if let Some(h) = &c.hint {
1133
            println!("    {} {}", ui::dim("→"), ui::dim(h));
1134
        }
1135
    }
1136
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
1137
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
1138
    if fails + warns == 0 {
1139
        println!("{}", ui::done("Everything looks right."));
1140
    } else {
1141
        println!(
1142
            "{} {}, {}.",
1143
            if fails > 0 {
1144
                ui::err(ui::glyph("✖", "x"))
1145
            } else {
1146
                ui::caution()
1147
            },
1148
            plural(fails, "problem"),
1149
            plural(warns, "warning")
1150
        );
1151
    }
1152
    Ok(code)
1153
}
1154
387335ff Andy McCall ↶ 1155
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
1156
pub fn fsck(as_json: bool) -> Result<i32> {
1157
    use oxy_core::repo::Severity;
1158
    let repo = open()?;
1159
    let sp = ui::spinner("Checking every object…");
1160
    let r = repo.fsck()?;
1161
    sp.clear();
1162
    let code = if r.errors() > 0 { 1 } else { 0 };
1163
    if as_json {
1164
        let problems: Vec<String> = r
1165
            .problems
1166
            .iter()
1167
            .map(|p| {
1168
                json::obj([
1169
                    (
1170
                        "severity",
1171
                        json::s(match p.severity {
1172
                            Severity::Error => "error",
1173
                            Severity::Warning => "warning",
1174
                        }),
1175
                    ),
1176
                    (
1177
                        "object",
1178
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1179
                    ),
1180
                    ("what", json::s(&p.what)),
1181
                ])
1182
            })
1183
            .collect();
1184
        println!(
1185
            "{}",
1186
            json::obj([
1187
                ("ok", json::b(code == 0)),
1188
                ("objects", json::n(r.objects)),
1189
                ("ops", json::n(r.ops)),
1190
                ("changes", json::n(r.changes)),
1191
                ("signed", json::n(r.signed)),
1192
                ("unsigned", json::n(r.unsigned)),
1193
                ("checkpoints", json::n(r.checkpoints)),
1194
                ("attestations", json::n(r.attestations)),
1195
                ("errors", json::n(r.errors())),
1196
                ("warnings", json::n(r.warnings())),
1197
                ("problems", json::arr(problems)),
1198
            ])
1199
        );
1200
        return Ok(code);
1201
    }
1202
    println!(
1203
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
1204
        plural(r.objects, "object"),
1205
        plural(r.ops, "operation"),
1206
        plural(r.changes, "change"),
1207
        r.signed,
1208
        r.unsigned,
1209
        plural(r.checkpoints, "checkpoint"),
1210
        plural(r.attestations, "attestation"),
1211
    );
1212
    for p in &r.problems {
1213
        let obj = p
1214
            .object
1215
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
1216
            .unwrap_or_default();
1217
        match p.severity {
1218
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
1219
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1220
        }
1221
    }
1222
    if r.problems.is_empty() {
1223
        println!("{}", ui::done("No problems found."));
1224
    } else if code == 0 {
1225
        println!(
1226
            "{}",
1227
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
1228
        );
1229
    } else {
1230
        println!(
1231
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
1232
            ui::err(ui::glyph("✖", "x")),
1233
            plural(r.errors(), "error"),
1234
            plural(r.warnings(), "warning")
1235
        );
1236
    }
1237
    Ok(code)
1238
}
1239
79d03f82 Andy McCall ↶ 1240
/// The head the working copy sits on, for commands that default to it. With
1241
/// several heads beneath the working copy, the most recently made one is
1242
/// chosen and announced.
614541c3 Andy McCall ↶ 1243
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
cc7a0056 Andy McCall ↶ 1244
    let snap = repo.snapshot_status("oxy")?;
614541c3 Andy McCall ↶ 1245
    let base = snap.base.maximal(&snap.wc.deps);
1246
    match base.as_slice() {
79d03f82 Andy McCall ↶ 1247
        [] => anyhow::bail!("the working copy sits on no change yet"),
614541c3 Andy McCall ↶ 1248
        [h] => Ok(*h),
79d03f82 Andy McCall ↶ 1249
        many => {
1250
            let latest = many
1251
                .iter()
1252
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
1253
                .copied()
1254
                .unwrap();
1255
            let c = repo.store().get_change(&latest)?;
75167672 Andy McCall 1256
            println!(
1257
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
1258
                short_id(&c),
1259
                latest.short(12),
1260
                many.len()
1261
            );
79d03f82 Andy McCall ↶ 1262
            Ok(latest)
1263
        }
614541c3 Andy McCall ↶ 1264
    }
1265
}
1266
6a81dbab Andy McCall ↶ 1267
/// `oxy describe` without -m: the working copy's name for a build.
1268
pub fn describe_name(as_json: bool) -> Result<i32> {
1269
    let repo = open()?;
1270
    let d = repo.describe_working_copy()?;
1271
    if as_json {
1272
        println!(
1273
            "{}",
1274
            json::obj([
1275
                ("describe", json::s(&d.line())),
1276
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
1277
                ("distance", json::n(d.distance)),
1278
                ("bookmark", json::s(&d.bookmark)),
1279
                ("change", json::s(&d.change.to_hex())),
1280
                ("hash", json::s(&d.hash.to_hex())),
1281
                ("dirty", json::b(d.dirty)),
1282
            ])
1283
        );
1284
    } else {
1285
        println!("{}", d.line());
1286
    }
1287
    Ok(0)
1288
}
1289
614541c3 Andy McCall ↶ 1290
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
1291
    let repo = open()?;
1292
    let h = match change {
1293
        Some(c) => repo.resolve_change(c)?,
1294
        None => current_head(&repo)?,
1295
    };
1296
    let new = repo.describe(&h, message)?;
1297
    let c = repo.store().get_change(&new)?;
75167672 Andy McCall 1298
    println!(
1299
        "{} {} {}  {}",
1300
        ui::done("Described"),
1301
        ui::id(short_id(&c)),
1302
        ui::hash(format!("#{}", new.short(12))),
1303
        ui::subject(subject_of(message))
1304
    );
614541c3 Andy McCall ↶ 1305
    Ok(0)
1306
}
1307
23b217d7 Andy McCall ↶ 1308
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
614541c3 Andy McCall ↶ 1309
    let repo = open()?;
23b217d7 Andy McCall ↶ 1310
    let new = match into {
1311
        Some(spec) => {
1312
            let target = repo.resolve_change(spec)?;
1313
            repo.amend_into(&target, message)?
1314
        }
1315
        None => repo.amend(message)?,
1316
    };
614541c3 Andy McCall ↶ 1317
    let c = repo.store().get_change(&new)?;
75167672 Andy McCall 1318
    println!(
1319
        "{} {} {}  {}",
1320
        ui::done("Amended"),
1321
        ui::id(short_id(&c)),
1322
        ui::hash(format!("#{}", new.short(12))),
1323
        ui::subject(subject_of(&c.message))
1324
    );
614541c3 Andy McCall ↶ 1325
    Ok(0)
1326
}
1327
1328
pub fn abandon(change: &str) -> Result<i32> {
1329
    let repo = open()?;
1330
    let h = repo.resolve_change(change)?;
1331
    let c = repo.store().get_change(&h)?;
6706bdcf Andy McCall ↶ 1332
    let notes = repo.abandon(&h)?;
75167672 Andy McCall 1333
    println!(
1334
        "{} {} {}  {}",
1335
        ui::done("Abandoned"),
1336
        ui::id(short_id(&c)),
1337
        ui::hash(format!("#{}", h.short(12))),
1338
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
1339
    );
6706bdcf Andy McCall ↶ 1340
    for n in notes {
94084087 Andy McCall ↶ 1341
        println!("  {} {n}", ui::note());
6706bdcf Andy McCall ↶ 1342
    }
614541c3 Andy McCall ↶ 1343
    Ok(0)
1344
}
252e8cb2 Andy McCall ↶ 1345
1346
pub fn checkpoint() -> Result<i32> {
1347
    let repo = open()?;
135212de Andy McCall ↶ 1348
    let sp = ui::spinner("Writing checkpoint…");
252e8cb2 Andy McCall ↶ 1349
    let (r, changes, bytes) = repo.checkpoint()?;
75167672 Andy McCall 1350
    sp.done(&format!(
1351
        "{} {} of {} ({} bytes) for {}",
1352
        ui::done("Checkpoint"),
1353
        ui::hash(format!("#{}", r.short(12))),
1354
        plural(changes, "change"),
1355
        bytes,
1356
        ui::id(&repo.config.bookmark)
1357
    ));
135212de Andy McCall ↶ 1358
    Ok(0)
1359
}
1360
1361
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
694805cc Andy McCall ↶ 1362
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
75167672 Andy McCall 1363
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
1364
        return Ok(1);
1365
    };
135212de Andy McCall ↶ 1366
    let info = repo.quick_status()?;
75167672 Andy McCall 1367
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
1368
        oxy_core::repo::GLYPH_PROMPT_FORMAT
1369
    } else {
1370
        format
1371
    };
694805cc Andy McCall ↶ 1372
    let line = match color {
1373
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
1374
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
1375
        Some(_) => info.format_colored(fmt, ("", "")),
1376
        None => info.format(fmt),
1377
    };
1378
    println!("{line}");
252e8cb2 Andy McCall ↶ 1379
    Ok(0)
1380
}
7421309f Andy McCall ↶ 1381
1382
pub fn sparse(paths: &[String]) -> Result<i32> {
1383
    let mut repo = open()?;
1384
    if paths.is_empty() {
1385
        if repo.config.sparse_paths.is_empty() {
1386
            println!("No sparse filter: the whole tree is materialized.");
1387
        } else {
1388
            println!("{}", ui::heading("Sparse filter"));
1389
            for p in &repo.config.sparse_paths {
1390
                println!("  {}", ui::path(p));
1391
            }
1392
        }
1393
        return Ok(0);
1394
    }
1395
    let snap = repo.snapshot("oxy sparse")?;
1396
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
75167672 Andy McCall 1397
        anyhow::bail!(
1398
            "the working copy has changes; commit them before changing the sparse filter"
1399
        );
7421309f Andy McCall ↶ 1400
    }
1401
    repo.config.set("filter.paths", &paths.join(","))?;
1402
    repo.save_config()?;
1403
    let heads = repo.bookmark_heads()?;
1404
    let sp = ui::spinner("Re-checking out with the new filter…");
1405
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
75167672 Andy McCall 1406
    sp.done(&format!(
1407
        "{} {}: {} written, {} removed",
1408
        ui::ok("Sparse filter set to"),
1409
        ui::path(paths.join(",")),
1410
        plural(r.written, "file"),
1411
        r.removed
1412
    ));
7421309f Andy McCall ↶ 1413
    Ok(0)
1414
}
132b884b Andy McCall ↶ 1415
1416
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
1417
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1418
    repo.snapshot_status("oxy tag")?;
132b884b Andy McCall ↶ 1419
    let heads = if changes.is_empty() {
1420
        repo.bookmark_heads()?
1421
    } else {
1422
        let mut heads = Vec::new();
1423
        for c in changes {
1424
            heads.extend(repo.resolve_heads(c)?);
1425
        }
1426
        heads
1427
    };
1428
    let t = repo.tag_create(name, &heads, message)?;
1429
    println!(
94084087 Andy McCall ↶ 1430
        "{} {} {} {} ({}){}",
1431
        ui::done("Tagged"),
1432
        ui::bookmark(&t.name),
1433
        ui::dim(ui::glyph("→", "->")),
132b884b Andy McCall ↶ 1434
        ui::hash(format!("#{}", t.state.short(12))),
1435
        plural(t.heads.len(), "head"),
75167672 Andy McCall 1436
        t.signer
1437
            .map(|s| format!(", signed by {s}"))
1438
            .unwrap_or_else(|| ui::dim(", unsigned"))
132b884b Andy McCall ↶ 1439
    );
1440
    Ok(0)
1441
}
1442
1196b29b Andy McCall ↶ 1443
pub fn tag_list(as_json: bool) -> Result<i32> {
132b884b Andy McCall ↶ 1444
    let repo = open()?;
1445
    let tags = repo.tags()?;
1196b29b Andy McCall ↶ 1446
    if as_json {
1447
        println!(
1448
            "{}",
1449
            json::arr(tags.iter().map(|t| {
1450
                json::obj([
1451
                    ("name", json::s(&t.name)),
1452
                    ("state", json::s(&t.state.to_hex())),
1453
                    ("heads", json::hashes(&t.heads)),
1454
                    ("message", json::s(&t.message)),
75167672 Andy McCall 1455
                    (
1456
                        "signer",
1457
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
1458
                    ),
1196b29b Andy McCall ↶ 1459
                ])
1460
            }))
1461
        );
1462
        return Ok(0);
1463
    }
132b884b Andy McCall ↶ 1464
    if tags.is_empty() {
1465
        println!("{}", ui::dim("No tags."));
1466
    }
1467
    for t in tags {
1468
        println!(
94084087 Andy McCall ↶ 1469
            "{} {} {}{}{}{}",
1470
            ui::ok(ui::glyph("⚑", "#")),
1471
            ui::bookmark(&t.name),
6a81dbab Andy McCall ↶ 1472
            // The heads, as `oxy log` shows changes, not the state hash.
1473
            ui::hash(
1474
                t.heads
1475
                    .iter()
1476
                    .map(|h| format!("#{}", h.short(12)))
1477
                    .collect::<Vec<_>>()
1478
                    .join(" ")
1479
            ),
94084087 Andy McCall ↶ 1480
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
75167672 Andy McCall 1481
            if t.message.is_empty() {
1482
                String::new()
1483
            } else {
1484
                format!("  {}", ui::subject(subject_of(&t.message)))
1485
            },
1486
            t.signer
1487
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
1488
                .unwrap_or_default()
132b884b Andy McCall ↶ 1489
        );
1490
    }
1491
    Ok(0)
1492
}
4e88e774 Andy McCall ↶ 1493
1494
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
1495
    let repo = open()?;
1496
    let heads = if changes.is_empty() {
1497
        None
1498
    } else {
1499
        let mut heads = Vec::new();
1500
        for c in changes {
1501
            heads.extend(repo.resolve_heads(c)?);
1502
        }
1503
        Some(heads)
1504
    };
1505
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
1506
    let ws = repo.workspace_add(path, heads.as_deref())?;
75167672 Andy McCall 1507
    sp.done(&format!(
1508
        "{} {} (workspace {})",
1509
        ui::done("Workspace created at"),
1510
        ui::path(ws.root().display()),
1511
        ui::id(ws.workspace().short(8))
1512
    ));
4e88e774 Andy McCall ↶ 1513
    Ok(0)
1514
}
1515
1196b29b Andy McCall ↶ 1516
pub fn workspace_list(as_json: bool) -> Result<i32> {
4e88e774 Andy McCall ↶ 1517
    let repo = open()?;
1196b29b Andy McCall ↶ 1518
    if as_json {
1519
        println!(
1520
            "{}",
1521
            json::arr(repo.workspaces()?.iter().map(|w| {
1522
                json::obj([
1523
                    ("id", json::s(&w.id.to_hex())),
1524
                    ("path", json::s(&w.path.to_string_lossy())),
1525
                    ("current", json::b(w.current)),
75167672 Andy McCall 1526
                    (
1527
                        "working_copy",
1528
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
1529
                    ),
1196b29b Andy McCall ↶ 1530
                ])
1531
            }))
1532
        );
1533
        return Ok(0);
1534
    }
4e88e774 Andy McCall ↶ 1535
    for w in repo.workspaces()? {
1536
        println!(
1537
            "{} {} {}{}",
75167672 Andy McCall 1538
            if w.current {
1539
                ui::ok(ui::glyph("●", "*"))
1540
            } else {
1541
                ui::dim(ui::glyph("○", "o"))
1542
            },
4e88e774 Andy McCall ↶ 1543
            ui::id(w.id.short(8)),
1544
            ui::path(w.path.display()),
75167672 Andy McCall 1545
            w.working_copy
1546
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
1547
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
4e88e774 Andy McCall ↶ 1548
        );
1549
    }
1550
    Ok(0)
1551
}
1552
1553
pub fn workspace_forget(spec: &str) -> Result<i32> {
1554
    let repo = open()?;
1555
    let all = repo.workspaces()?;
1556
    let target = std::fs::canonicalize(spec).ok();
75167672 Andy McCall 1557
    let matches: Vec<_> = all
1558
        .iter()
1559
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
1560
        .collect();
4e88e774 Andy McCall ↶ 1561
    let w = match matches.as_slice() {
1562
        [w] => *w,
1563
        [] => anyhow::bail!("no workspace matches {spec:?}"),
1564
        _ => anyhow::bail!("{spec:?} is ambiguous"),
1565
    };
1566
    repo.workspace_forget(&w.id)?;
75167672 Andy McCall 1567
    println!(
1568
        "{} workspace {} at {}; its files were left in place.",
1569
        ui::done("Forgot"),
1570
        ui::id(w.id.short(8)),
1571
        ui::path(w.path.display())
1572
    );
4e88e774 Andy McCall ↶ 1573
    Ok(0)
1574
}
cdb5beba Andy McCall ↶ 1575
1576
pub fn lock(path: &str) -> Result<i32> {
1577
    let repo = open()?;
1578
    repo.lock_path(path)?;
75167672 Andy McCall 1579
    println!(
1580
        "{} {} {}",
1581
        ui::done("Locked"),
1582
        ui::path(path),
1583
        ui::dim("(advisory, local)")
1584
    );
cdb5beba Andy McCall ↶ 1585
    Ok(0)
1586
}
1587
1588
pub fn unlock(path: &str) -> Result<i32> {
1589
    let repo = open()?;
1590
    repo.unlock_path(path)?;
94084087 Andy McCall ↶ 1591
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
cdb5beba Andy McCall ↶ 1592
    Ok(0)
1593
}
23b217d7 Andy McCall ↶ 1594
1595
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
1596
    let repo = open()?;
1597
    let h = repo.resolve_change(change)?;
1598
    let (h1, h2) = repo.split(&h, paths)?;
1599
    let c1 = repo.store().get_change(&h1)?;
1600
    let c2 = repo.store().get_change(&h2)?;
75167672 Andy McCall 1601
    println!(
1602
        "{} into {} {} and {} {}",
1603
        ui::done("Split"),
1604
        ui::id(short_id(&c1)),
1605
        ui::hash(format!("#{}", h1.short(12))),
1606
        ui::id(short_id(&c2)),
1607
        ui::hash(format!("#{}", h2.short(12)))
1608
    );
23b217d7 Andy McCall ↶ 1609
    Ok(0)
1610
}
7b9809e6 Andy McCall ↶ 1611
1612
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
1613
    let mut heads = Vec::new();
1614
    for c in changes {
1615
        heads.extend(repo.resolve_heads(c)?);
1616
    }
1617
    Ok(heads)
1618
}
1619
4fe7d604 Andy McCall ↶ 1620
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 1621
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1622
    repo.snapshot_status("oxy bookmark create")?;
75167672 Andy McCall 1623
    let heads = if changes.is_empty() {
1624
        None
1625
    } else {
4fe7d604 Andy McCall ↶ 1626
        let named = heads_from(&repo, changes)?;
1627
        let (_, wc) = repo.working_copy()?;
1628
        let gap = repo.state_gap(&wc.deps, &named)?;
1629
        if upto {
1630
            Some(gap.upto)
1631
        } else if only || gap.earlier.is_empty() {
1632
            Some(named)
1633
        } else {
1634
            anyhow::bail!(
1635
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
1636
                 A state is its heads and what they depend on, not everything recorded before them.\n\
1637
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
1638
                 or --only for just {0} and what it depends on.",
1639
                changes.join(" "),
1640
                plural(gap.earlier.len(), "change"),
1641
                listed_changes(&repo, &gap.earlier)
1642
            );
1643
        }
75167672 Andy McCall 1644
    };
7b9809e6 Andy McCall ↶ 1645
    let heads = repo.bookmark_create(name, heads.as_deref())?;
75167672 Andy McCall 1646
    println!(
1647
        "{} bookmark {} {} {}",
1648
        ui::done("Created"),
1649
        ui::bookmark(name),
1650
        ui::dim(ui::glyph("→", "->")),
1651
        ui::dim(plural(heads.len(), "head"))
1652
    );
1653
    println!(
1654
        "  {} {}",
1655
        ui::note(),
1656
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
1657
    );
7b9809e6 Andy McCall ↶ 1658
    Ok(0)
1659
}
1660
4fe7d604 Andy McCall ↶ 1661
/// Up to five changes, newest last, as `  #hash subject` lines.
1662
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
1663
    let shown = changes.len().min(5);
1664
    let mut lines: Vec<String> = changes[changes.len() - shown..]
1665
        .iter()
1666
        .map(|h| {
1667
            let subject = repo
1668
                .store()
1669
                .get_change(h)
1670
                .map(|c| subject_of(&c.message).to_string())
1671
                .unwrap_or_default();
1672
            format!("  #{} {subject}", h.short(12))
1673
        })
1674
        .collect();
1675
    if changes.len() > shown {
1676
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
1677
    }
1678
    lines.join("\n")
1679
}
1680
7b9809e6 Andy McCall ↶ 1681
pub fn bookmark_set(name: &str, changes: &[String]) -> Result<i32> {
1682
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1683
    repo.snapshot_status("oxy bookmark set")?;
7b9809e6 Andy McCall ↶ 1684
    let heads = heads_from(&repo, changes)?;
1685
    let heads = repo.bookmark_set(name, &heads)?;
75167672 Andy McCall 1686
    println!(
1687
        "{} bookmark {} {} {}",
1688
        ui::done("Moved"),
1689
        ui::bookmark(name),
1690
        ui::dim(ui::glyph("→", "->")),
1691
        ui::dim(plural(heads.len(), "head"))
1692
    );
7b9809e6 Andy McCall ↶ 1693
    Ok(0)
1694
}
1695
1696
pub fn bookmark_delete(name: &str) -> Result<i32> {
1697
    let repo = open()?;
1698
    repo.bookmark_delete(name)?;
75167672 Andy McCall 1699
    println!(
1700
        "{} bookmark {} {}",
1701
        ui::done("Deleted"),
1702
        ui::bookmark(name),
1703
        ui::dim("(its changes stay until unreachable)")
1704
    );
7b9809e6 Andy McCall ↶ 1705
    Ok(0)
1706
}
1707
c6aa5bd9 Andy McCall ↶ 1708
pub fn bookmark_list(as_json: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 1709
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 1710
    if as_json {
1711
        let items = repo.bookmarks()?.into_iter().map(|b| {
1712
            json::obj([
1713
                ("name", json::s(&b.name)),
1714
                ("heads", json::hashes(&b.heads)),
1715
                ("current", json::b(b.current)),
1716
                ("ahead", json::opt(b.ahead, json::n)),
1717
                ("behind", json::opt(b.behind, json::n)),
1718
            ])
1719
        });
1720
        println!("{}", json::arr(items));
1721
        return Ok(0);
1722
    }
7b9809e6 Andy McCall ↶ 1723
    for b in repo.bookmarks()? {
75167672 Andy McCall 1724
        let mark = if b.current {
1725
            ui::ok(ui::glyph("●", "*"))
1726
        } else {
1727
            ui::dim(ui::glyph("○", "o"))
1728
        };
7b9809e6 Andy McCall ↶ 1729
        let mut tail = String::new();
1730
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
1731
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
1732
        }
1733
        if let Some(n) = b.behind.filter(|n| *n > 0) {
1734
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
1735
        }
75167672 Andy McCall 1736
        let head = b
1737
            .heads
1738
            .first()
1739
            .map(|h| {
1740
                repo.store()
1741
                    .get_change(h)
1742
                    .map(|c| ui::subject(subject_of(&c.message)))
1743
                    .unwrap_or_default()
1744
            })
1745
            .unwrap_or_else(|| ui::dim("(empty)"));
1746
        println!(
1747
            "{mark} {}{}{}{tail}  {head}",
1748
            ui::bookmark(&b.name),
1749
            ui::sep(),
1750
            ui::dim(plural(b.heads.len(), "head"))
1751
        );
7b9809e6 Andy McCall ↶ 1752
    }
1753
    Ok(0)
1754
}
1755
61e3bce7 Andy McCall ↶ 1756
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 1757
    let mut repo = open()?;
4fe7d604 Andy McCall ↶ 1758
    let from = repo.config.bookmark.clone();
1759
    let before = repo
1760
        .working_copy()
1761
        .map(|(_, wc)| wc.deps)
1762
        .unwrap_or_default();
7b9809e6 Andy McCall ↶ 1763
    let sp = ui::spinner(&format!("Switching to {name}…"));
61e3bce7 Andy McCall ↶ 1764
    let (r, carried) = if carry {
1765
        repo.bookmark_switch_carry(name)?
1766
    } else {
1767
        (repo.bookmark_switch(name, discard)?, vec![])
1768
    };
75167672 Andy McCall 1769
    sp.done(&format!(
61e3bce7 Andy McCall ↶ 1770
        "{} to {}: {} written, {} removed{}",
75167672 Andy McCall 1771
        ui::done("Switched"),
1772
        ui::bookmark(name),
1773
        plural(r.written, "file"),
61e3bce7 Andy McCall ↶ 1774
        r.removed,
1775
        if carried.is_empty() {
1776
            String::new()
1777
        } else {
1778
            format!("; carried {}", plural(carried.len(), "changed path"))
1779
        }
75167672 Andy McCall 1780
    ));
7b9809e6 Andy McCall ↶ 1781
    if r.conflicted {
75167672 Andy McCall 1782
        println!(
1783
            "  {} {}",
1784
            ui::caution(),
1785
            ui::warn("this state has conflicts; see oxy status")
1786
        );
4fe7d604 Andy McCall ↶ 1787
    }
1788
    // Say when the new state leaves out work the old one had: a state is
1789
    // its heads and what they depend on, which can be far less than a Git
1790
    // user expects.
1791
    let after = repo
1792
        .working_copy()
1793
        .map(|(_, wc)| wc.deps)
1794
        .unwrap_or_default();
1795
    if let Ok(gap) = repo.state_gap(&before, &after) {
1796
        if gap.lacks > 0 {
1797
            println!(
1798
                "  {} {}",
1799
                ui::note(),
1800
                ui::dim(format!(
1801
                    "{name} lacks {} that {from} has",
1802
                    plural(gap.lacks, "change")
1803
                ))
1804
            );
1805
        }
7b9809e6 Andy McCall ↶ 1806
    }
1807
    Ok(0)
1808
}
1809
1810
pub fn merge(bookmark: &str) -> Result<i32> {
1811
    let repo = open()?;
1812
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
1813
    let r = repo.merge(bookmark)?;
1814
    if !r.changed {
75167672 Andy McCall 1815
        sp.done(&format!(
1816
            "{} {}",
1817
            ui::ok(ui::glyph("✔", "*")),
1818
            ui::dim(format!(
1819
                "{} already contains {bookmark}",
1820
                repo.config.bookmark
1821
            ))
1822
        ));
7b9809e6 Andy McCall ↶ 1823
        return Ok(0);
1824
    }
1825
    sp.done(&format!(
1826
        "{} {} into {}: now {}{}",
1827
        ui::done("Merged"),
1828
        ui::bookmark(bookmark),
1829
        ui::bookmark(&repo.config.bookmark),
1830
        plural(r.heads.len(), "head"),
75167672 Andy McCall 1831
        ui::dim(if r.checked_out {
1832
            "; working copy updated"
1833
        } else {
1834
            "; run oxy checkout to update the working copy"
1835
        })
7b9809e6 Andy McCall ↶ 1836
    ));
1837
    let snap = repo.snapshot("oxy merge")?;
1838
    if snap.base_snapshot.is_conflicted() {
75167672 Andy McCall 1839
        println!(
1840
            "  {} {}",
1841
            ui::caution(),
1842
            ui::warn("the result has conflicts; see oxy status")
1843
        );
7b9809e6 Andy McCall ↶ 1844
    }
1845
    Ok(0)
1846
}
1847
728da0f9 Andy McCall ↶ 1848
pub fn squash(change: &str, into: &str) -> Result<i32> {
1849
    let repo = open()?;
1850
    let c = repo.resolve_change(change)?;
1851
    let d = repo.resolve_change(into)?;
1852
    let sp = ui::spinner("Squashing…");
1853
    let h = repo.squash(&c, &d)?;
1854
    let new = repo.store().get_change(&h)?;
75167672 Andy McCall 1855
    sp.done(&format!(
1856
        "{} into {} {}  {}",
1857
        ui::done("Squashed"),
1858
        ui::id(short_id(&new)),
1859
        ui::hash(format!("#{}", h.short(12))),
1860
        ui::subject(subject_of(&new.message))
1861
    ));
728da0f9 Andy McCall ↶ 1862
    Ok(0)
1863
}
1864
1865
pub fn rebase(change: &str, onto: &[String]) -> Result<i32> {
1866
    let repo = open()?;
1867
    let c = repo.resolve_change(change)?;
1868
    let mut heads = Vec::new();
1869
    for o in onto {
1870
        heads.extend(repo.resolve_heads(o)?);
1871
    }
1872
    let sp = ui::spinner("Rebasing…");
1873
    let h = repo.rebase(&c, &heads)?;
1874
    let new = repo.store().get_change(&h)?;
75167672 Andy McCall 1875
    sp.done(&format!(
1876
        "{} {} {}  {}",
1877
        ui::done("Rebased"),
1878
        ui::id(short_id(&new)),
1879
        ui::hash(format!("#{}", h.short(12))),
1880
        ui::dim(format!(
1881
            "now depends on {}",
1882
            plural(new.deps.len(), "change")
1883
        ))
1884
    ));
728da0f9 Andy McCall ↶ 1885
    Ok(0)
1886
}