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