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