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