OXYGENHUB
# 2bf22305bc48 oxygen / src / cli / workspace.rs
66.3 KiB · Rust · last changed oxy log draws a graph: lanes, bookmarks inline, unique ID prefixes (closes #50) 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};
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);
2bf22305 Andy McCall ↶ 598
    // Lay out a little past what is shown, so edges into the cut are drawn.
599
    let window: Vec<(ChangeHash, Vec<ChangeHash>)> = entries
600
        .iter()
601
        .take((shown + MAX_EDGE).min(total))
602
        .map(|e| (e.hash, e.change.deps.clone()))
603
        .collect();
604
    let rows = oxy_core::lanes::graph(&window, MAX_EDGE);
605
    // Highlight the shortest prefix that names each change: against the
606
    // whole log, which is what `resolve_change` searches.
607
    let everything;
608
    let all = if path.is_some() || lines.is_some() {
609
        everything = repo.log()?;
610
        &everything
611
    } else {
612
        &entries
613
    };
614
    let id_prefix = unique_prefixes(all.iter().map(|e| e.change.change_id.to_hex()));
615
    let labels = reference_labels(&repo)?;
616
    for (e, row) in entries.iter().take(shown).zip(&rows) {
fce44ae9 Andy McCall ↶ 617
        let c = &e.change;
75167672 Andy McCall 618
        let bullet = ui::log_bullet(
619
            e.is_working_copy,
620
            e.is_head,
621
            e.is_working_copy && conflicted,
622
        );
2bf22305 Andy McCall ↶ 623
        let id = c.change_id.to_hex();
624
        let n = id_prefix.get(&id).copied().unwrap_or(8).min(8);
625
        let mut head = vec![format!("{}{}", ui::id(&id[..n]), ui::dim(&id[n..8]))];
626
        head.push(ui::author(author_name(&repo, c)));
627
        head.push(ui::dim(ui::ago(c.hlc.wall_ms)));
628
        if let Some(names) = labels.get(&e.hash) {
629
            head.push(names.join(" "));
fce44ae9 Andy McCall ↶ 630
        }
94084087 Andy McCall ↶ 631
        if c.kind == ChangeKind::Resolution {
2bf22305 Andy McCall ↶ 632
            head.push(ui::warn("resolution"));
fce44ae9 Andy McCall ↶ 633
        }
2bf22305 Andy McCall ↶ 634
        if !e.is_working_copy {
635
            head.push(ui::hash(format!("#{}", e.hash.short(8))));
636
            head.push(signature_mark(&repo, &e.hash, Some(c))?);
637
        }
638
        println!("{}{}", node_line(row, &bullet), head.join(" "));
94084087 Andy McCall ↶ 639
        let subject = if e.is_working_copy && c.message.is_empty() {
69816d68 Andy McCall ↶ 640
            ui::dim(if clean {
2bf22305 Andy McCall ↶ 641
                "(working copy, clean)"
75167672 Andy McCall 642
            } else {
2bf22305 Andy McCall ↶ 643
                "(working copy, uncommitted changes)"
75167672 Andy McCall 644
            })
2bf22305 Andy McCall ↶ 645
        } else if c.message.trim().is_empty() {
646
            ui::dim("(no description)")
94084087 Andy McCall ↶ 647
        } else {
2bf22305 Andy McCall ↶ 648
            subject_of(&c.message).to_string()
94084087 Andy McCall ↶ 649
        };
2bf22305 Andy McCall ↶ 650
        println!("{}{subject}", below_line(row));
94084087 Andy McCall ↶ 651
        if verbose {
2bf22305 Andy McCall ↶ 652
            let rail = continuation(row);
94084087 Andy McCall ↶ 653
            if !e.is_working_copy {
75167672 Andy McCall 654
                println!(
2bf22305 Andy McCall ↶ 655
                    "{rail}{}",
75167672 Andy McCall 656
                    ui::dim(format!(
657
                        "{} {}",
658
                        when(c.hlc.wall_ms),
659
                        signature_line(&repo, &e.hash)?
660
                    ))
661
                );
94084087 Andy McCall ↶ 662
            }
663
            if !c.deps.is_empty() {
75167672 Andy McCall 664
                println!(
2bf22305 Andy McCall ↶ 665
                    "{rail}{} {}",
75167672 Andy McCall 666
                    ui::dim(ui::glyph("↳", "->")),
667
                    ui::dim(deps_of(&c.deps))
668
                );
94084087 Andy McCall ↶ 669
            }
75167672 Andy McCall 670
            let body: Vec<&str> = c
671
                .message
672
                .lines()
673
                .skip(1)
674
                .skip_while(|l| l.trim().is_empty())
675
                .collect();
2bf22305 Andy McCall ↶ 676
            for line in body {
677
                println!("{rail}  {line}");
94084087 Andy McCall ↶ 678
            }
fce44ae9 Andy McCall ↶ 679
        }
680
    }
94084087 Andy McCall ↶ 681
    if shown < total {
2bf22305 Andy McCall ↶ 682
        if let Some(last) = rows.get(shown.saturating_sub(1)) {
683
            let cut: String = last
684
                .below
685
                .iter()
686
                .map(|c| match c {
687
                    Cell::Blank | Cell::Elided | Cell::JoinRight => "  ",
688
                    _ => "~ ",
689
                })
690
                .collect();
691
            if cut.trim().is_empty() {
692
                println!("{}", ui::dim("~"));
693
            } else {
694
                println!("{}", ui::dim(cut.trim_end()));
695
            }
696
        }
75167672 Andy McCall 697
        println!(
698
            "{}",
699
            ui::dim(format!(
700
                "{} {} more; pass -n to see them",
701
                ui::glyph("…", "..."),
702
                total - shown
703
            ))
704
        );
94084087 Andy McCall ↶ 705
    }
fce44ae9 Andy McCall ↶ 706
    Ok(0)
2bf22305 Andy McCall ↶ 707
}
708
709
/// Rows a drawn edge may span in `oxy log`; a longer one is elided (`~`).
710
const MAX_EDGE: usize = 12;
711
712
use oxy_core::hash::ChangeHash;
713
use oxy_core::lanes::{Cell, GraphRow};
714
715
/// A graph cell, two columns wide.
716
fn cell(c: Cell) -> &'static str {
717
    match c {
718
        Cell::Blank => "  ",
719
        Cell::Line => ui::glyph("│ ", "| "),
720
        Cell::Elided => "~ ",
721
        Cell::JoinLeft => ui::glyph("├─", "|-"),
722
        Cell::JoinPass => ui::glyph("──", "--"),
723
        Cell::JoinCross => ui::glyph("┼─", "+-"),
724
        Cell::JoinRight => ui::glyph("╯ ", "' "),
725
    }
726
}
727
728
/// The graph part of a change's own line, its bullet in its column.
729
fn node_line(row: &GraphRow, bullet: &str) -> String {
730
    let width = row
731
        .passing
732
        .iter()
733
        .copied()
734
        .max()
735
        .unwrap_or(0)
736
        .max(row.column)
737
        + 1;
738
    let mut out = String::new();
739
    for c in 0..width {
740
        if c == row.column {
741
            out.push_str(bullet);
742
            out.push(' ');
743
        } else if row.passing.contains(&c) {
744
            out.push_str(&ui::dim(cell(Cell::Line)));
745
        } else {
746
            out.push_str("  ");
747
        }
748
    }
749
    out.push(' ');
750
    out
751
}
752
753
/// The graph part of the line under a change: lanes carrying on, a join,
754
/// or `~` for an elided edge.
755
fn below_line(row: &GraphRow) -> String {
756
    let g: String = row.below.iter().map(|c| cell(*c)).collect();
757
    format!("{} ", ui::dim(g))
758
}
759
760
/// The graph part of any further line of a change (`-v`).
761
fn continuation(row: &GraphRow) -> String {
762
    let g: String = row
763
        .below
764
        .iter()
765
        .map(|c| match c {
766
            Cell::Line | Cell::JoinLeft | Cell::JoinCross => cell(Cell::Line),
767
            _ => "  ",
768
        })
769
        .collect();
770
    format!("{} ", ui::dim(g))
771
}
772
773
/// For each hex ID, the length of its shortest prefix no other ID shares.
774
fn unique_prefixes(ids: impl Iterator<Item = String>) -> std::collections::HashMap<String, usize> {
775
    let mut v: Vec<String> = ids.collect();
776
    v.sort();
777
    v.dedup();
778
    let common = |a: &str, b: &str| a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
779
    let mut out = std::collections::HashMap::with_capacity(v.len());
780
    for i in 0..v.len() {
781
        let before = if i > 0 { common(&v[i - 1], &v[i]) } else { 0 };
782
        let after = if i + 1 < v.len() {
783
            common(&v[i], &v[i + 1])
784
        } else {
785
            0
786
        };
787
        out.insert(v[i].clone(), before.max(after) + 1);
788
    }
789
    out
790
}
791
792
/// Bookmark, remote bookmark and tag names to show beside the changes they
793
/// point at. A name is shown on each head of its state; one with more than
794
/// three heads names too much of the log to help, so it is left out (oxy
795
/// bookmark list shows it). A remote bookmark at the same state as the
796
/// local one of that name is not repeated.
797
fn reference_labels(repo: &Repo) -> Result<std::collections::HashMap<ChangeHash, Vec<String>>> {
798
    const MAX_HEADS: usize = 3;
799
    let view = repo.view()?;
800
    let mut out: std::collections::HashMap<ChangeHash, Vec<String>> = Default::default();
801
    let mut add = |heads: Vec<ChangeHash>, label: String| {
802
        if heads.len() <= MAX_HEADS {
803
            for h in heads {
804
                out.entry(h).or_default().push(label.clone());
805
            }
806
        }
807
    };
808
    for (name, st) in &view.bookmarks {
809
        add(repo.store().get_state(st)?.heads, ui::bookmark(name));
810
    }
811
    for (remote, bookmarks) in &view.remotes {
812
        for (name, st) in bookmarks {
813
            if view.bookmarks.get(name) == Some(st) {
814
                continue;
815
            }
816
            add(
817
                repo.store().get_state(st)?.heads,
818
                ui::dim(format!("{remote}/{name}")),
819
            );
820
        }
821
    }
822
    for t in repo.tags()? {
823
        add(t.heads.clone(), ui::warn(&t.name));
824
    }
825
    Ok(out)
fce44ae9 Andy McCall ↶ 826
}
827
c6aa5bd9 Andy McCall ↶ 828
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
829
    let repo = open()?;
830
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
831
    if as_json {
832
        let files = repo.diff_files(hash.as_ref())?;
833
        let items = files.iter().map(|f| {
834
            json::obj([
835
                ("path", json::s(&f.path)),
836
                ("kind", json::s(&f.kind)),
837
                ("from", json::opt(f.from.as_deref(), json::s)),
838
                (
839
                    "hunks",
840
                    json::arr(f.hunks.iter().map(|h| {
841
                        json::obj([
842
                            ("base_line", json::n(h.base_line)),
75167672 Andy McCall 843
                            (
844
                                "added",
845
                                json::arr(
846
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
847
                                ),
848
                            ),
849
                            (
850
                                "removed",
851
                                json::arr(h.removed.iter().map(|(n, l)| {
852
                                    json::obj([
853
                                        ("line", json::n(*n)),
854
                                        ("text", json::s(&String::from_utf8_lossy(l))),
855
                                    ])
856
                                })),
857
                            ),
c6aa5bd9 Andy McCall ↶ 858
                        ])
859
                    })),
860
                ),
861
            ])
862
        });
75167672 Andy McCall 863
        println!(
864
            "{}",
865
            json::obj([
866
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
867
                ("files", json::arr(items))
868
            ])
869
        );
c6aa5bd9 Andy McCall ↶ 870
        return Ok(0);
871
    }
872
    match hash {
873
        Some(h) => {
874
            let c = repo.store().get_change(&h)?;
8ab265dc Andy McCall ↶ 875
            let (base, snapshot) = repo.change_base(&c)?;
c6aa5bd9 Andy McCall ↶ 876
            print!("{}", render_change(&c, &base, &snapshot));
877
        }
878
        None => {
8ab265dc Andy McCall ↶ 879
            let snap = repo.snapshot_status("oxy diff")?;
75167672 Andy McCall 880
            print!(
881
                "{}",
882
                render_change(&snap.wc, &snap.base, &snap.base_snapshot)
883
            );
c6aa5bd9 Andy McCall ↶ 884
        }
885
    }
886
    Ok(0)
887
}
888
889
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
890
    let repo = open()?;
891
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
892
    let bytes = repo.file_at(path, heads.as_deref())?;
893
    use std::io::Write as _;
894
    std::io::stdout().write_all(&bytes)?;
895
    Ok(0)
896
}
897
898
pub fn root(as_json: bool) -> Result<i32> {
899
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
900
        if as_json {
901
            println!("null");
902
        }
903
        return Ok(1);
904
    };
905
    if as_json {
75167672 Andy McCall 906
        println!(
907
            "{}",
908
            json::obj([
909
                ("root", json::s(&repo.root().to_string_lossy())),
910
                ("workspace", json::s(&repo.workspace().to_hex())),
911
                ("bookmark", json::s(&repo.config.bookmark))
912
            ])
913
        );
c6aa5bd9 Andy McCall ↶ 914
    } else {
915
        println!("{}", repo.root().display());
916
    }
917
    Ok(0)
918
}
919
920
pub fn version(as_json: bool) -> Result<i32> {
921
    if as_json {
75167672 Andy McCall 922
        println!(
923
            "{}",
924
            json::obj([
925
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
926
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
927
                ("format", json::n(2))
928
            ])
929
        );
c6aa5bd9 Andy McCall ↶ 930
    } else {
75167672 Andy McCall 931
        println!(
932
            "oxy {} (repository format 2, protocol {})",
933
            env!("CARGO_PKG_VERSION"),
934
            oxy_core::protocol::PROTOCOL_VERSION
935
        );
c6aa5bd9 Andy McCall ↶ 936
    }
937
    Ok(0)
938
}
939
940
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
941
    let repo = open()?;
942
    if paths.is_empty() && hunks.is_empty() {
943
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
944
    }
945
    let mut n = 0;
946
    if !hunks.is_empty() {
947
        n += repo.discard_hunks(hunks)?;
948
    }
949
    if !paths.is_empty() {
950
        n += repo.discard(paths)?;
951
    }
75167672 Andy McCall 952
    println!(
953
        "{} {} restored to the working copy's base",
954
        ui::done("Discarded"),
955
        plural(n, "path")
956
    );
c6aa5bd9 Andy McCall ↶ 957
    Ok(0)
958
}
959
960
pub fn hunks(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 961
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 962
    let (_, hunks) = repo.hunks()?;
963
    if as_json {
75167672 Andy McCall 964
        println!(
965
            "{}",
966
            json::arr(hunks.iter().map(|h| json::obj([
967
                ("index", json::n(h.index)),
968
                ("path", json::s(&h.path)),
969
                ("text", json::s(&h.text))
970
            ])))
971
        );
c6aa5bd9 Andy McCall ↶ 972
        return Ok(0);
973
    }
974
    if hunks.is_empty() {
75167672 Andy McCall 975
        println!(
976
            "{}",
977
            ui::dim("No hunks: the working copy matches its base.")
978
        );
c6aa5bd9 Andy McCall ↶ 979
    }
980
    for h in &hunks {
75167672 Andy McCall 981
        println!(
982
            "{} {}",
983
            ui::section(format!("hunk {}", h.index)),
984
            ui::path(&h.path)
985
        );
c6aa5bd9 Andy McCall ↶ 986
        for line in h.text.lines() {
75167672 Andy McCall 987
            let styled = if line.starts_with('+') {
988
                ui::ok(line)
989
            } else if line.starts_with('-') {
990
                ui::err(line)
991
            } else {
992
                ui::dim(line)
993
            };
c6aa5bd9 Andy McCall ↶ 994
            println!("  {styled}");
995
        }
996
    }
fce44ae9 Andy McCall ↶ 997
    Ok(0)
998
}
999
c6aa5bd9 Andy McCall ↶ 1000
pub fn show(change: &str, as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 1001
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1002
    repo.snapshot_status("oxy show")?;
fce44ae9 Andy McCall ↶ 1003
    let h = repo.resolve_change(change)?;
1004
    let c = repo.store().get_change(&h)?;
c6aa5bd9 Andy McCall ↶ 1005
    if as_json {
1006
        let files = repo.diff_files(Some(&h))?;
1007
        let heads = repo.bookmark_heads()?;
75167672 Andy McCall 1008
        let entry = oxy_core::repo::LogEntry {
1009
            hash: h,
1010
            change: oxy_core::state::ChangeMeta::of(&c),
1011
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
1012
            is_head: heads.contains(&h),
1013
        };
c6aa5bd9 Andy McCall ↶ 1014
        let mut body = log_entry_json(&repo, &entry)?;
1015
        body.pop();
75167672 Andy McCall 1016
        body.push_str(&format!(
1017
            ",{}:{}}}",
1018
            json::s("files"),
1019
            json::arr(files.iter().map(|f| json::obj([
1020
                ("path", json::s(&f.path)),
1021
                ("kind", json::s(&f.kind)),
1022
                ("from", json::opt(f.from.as_deref(), json::s))
1023
            ])))
1024
        ));
c6aa5bd9 Andy McCall ↶ 1025
        println!("{body}");
1026
        return Ok(0);
1027
    }
75167672 Andy McCall 1028
    println!(
1029
        "{} {} {}",
1030
        ui::section("change"),
1031
        ui::id(short_id(&c)),
1032
        ui::hash(format!("#{h}"))
1033
    );
94084087 Andy McCall ↶ 1034
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
75167672 Andy McCall 1035
    println!(
1036
        "{}",
1037
        ui::kv(
1038
            "author",
1039
            ui::author(author_name(&repo, &oxy_core::state::ChangeMeta::of(&c)))
1040
        )
1041
    );
1042
    println!(
1043
        "{}",
1044
        ui::kv(
1045
            "date",
1046
            format!(
1047
                "{} {}",
1048
                when(c.hlc.wall_ms),
1049
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
1050
            )
1051
        )
1052
    );
94084087 Andy McCall ↶ 1053
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
1054
    println!("{}", ui::kv("sig", signature_line(&repo, &h)?));
1055
    println!();
75167672 Andy McCall 1056
    for line in (if c.message.is_empty() {
1057
        "(no description)"
1058
    } else {
1059
        &c.message
1060
    })
1061
    .lines()
1062
    {
94084087 Andy McCall ↶ 1063
        println!("    {line}");
1064
    }
1065
    println!();
fce44ae9 Andy McCall ↶ 1066
    print!("{}", repo.describe_change(&h)?);
1067
    Ok(0)
1068
}
1069
1c2bd9ab Andy McCall ↶ 1070
pub fn checkout(changes: &[String], discard: bool, carry: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 1071
    let repo = open()?;
1072
    let heads = if changes.is_empty() {
1073
        repo.bookmark_heads()?
1074
    } else {
132b884b Andy McCall ↶ 1075
        let mut heads = Vec::new();
1076
        for c in changes {
1077
            heads.extend(repo.resolve_heads(c)?);
1078
        }
1079
        heads
fce44ae9 Andy McCall ↶ 1080
    };
75167672 Andy McCall 1081
    let spec = if changes.is_empty() {
1082
        repo.config.bookmark.clone()
1083
    } else {
1084
        changes.join(" ")
1085
    };
135212de Andy McCall ↶ 1086
    let sp = ui::spinner(&format!("Checking out {spec}…"));
1c2bd9ab Andy McCall ↶ 1087
    let command = format!("oxy checkout {spec}");
1088
    let (r, carried) = if carry {
1089
        repo.checkout_carry(&heads, &spec, &command)?
1090
    } else {
1091
        (repo.checkout(&heads, discard, &command)?, vec![])
1092
    };
75167672 Andy McCall 1093
    sp.done(&format!(
1c2bd9ab Andy McCall ↶ 1094
        "{} on {}: {} written, {} removed{}",
75167672 Andy McCall 1095
        ui::done("Working copy"),
1096
        ui::bookmark(&spec),
1097
        plural(r.written, "file"),
1c2bd9ab Andy McCall ↶ 1098
        r.removed,
1099
        if carried.is_empty() {
1100
            String::new()
1101
        } else {
1102
            format!("; carried {}", plural(carried.len(), "changed path"))
1103
        }
75167672 Andy McCall 1104
    ));
4dee277c Andy McCall ↶ 1105
    for n in &r.notes {
1106
        println!("  {} {n}", ui::note());
1107
    }
fce44ae9 Andy McCall ↶ 1108
    if r.conflicted {
75167672 Andy McCall 1109
        println!(
1110
            "  {} {}",
1111
            ui::caution(),
1112
            ui::warn("this state has conflicts; see oxy status")
1113
        );
fce44ae9 Andy McCall ↶ 1114
    }
1115
    Ok(0)
1116
}
1117
c6aa5bd9 Andy McCall ↶ 1118
pub fn resolve(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 1119
    let repo = open()?;
1120
    let snap = repo.snapshot("oxy resolve")?;
c6aa5bd9 Andy McCall ↶ 1121
    if as_json {
1122
        println!("{}", repo.status_json(&snap)?);
75167672 Andy McCall 1123
        return Ok(if snap.base_snapshot.is_conflicted() {
1124
            2
1125
        } else {
1126
            0
1127
        });
c6aa5bd9 Andy McCall ↶ 1128
    }
fce44ae9 Andy McCall ↶ 1129
    if !snap.base_snapshot.is_conflicted() {
1130
        println!("The working copy's base has no conflicts.");
1131
        return Ok(0);
1132
    }
1133
    let mut remaining = 0;
1134
    for (p, f) in &snap.base_snapshot.files {
1135
        if !f.is_conflicted() {
1136
            continue;
1137
        }
75167672 Andy McCall 1138
        match snap
1139
            .statuses
1140
            .iter()
1141
            .find(|s| s.path == *p)
1142
            .map(|s| s.status)
1143
        {
fce44ae9 Andy McCall ↶ 1144
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
1145
            Some(ChangeStatus::ConflictEdited) => {
1146
                remaining += 1;
1147
                println!("markers    {p}");
1148
            }
1149
            _ => {
1150
                remaining += 1;
1151
                println!("unresolved {p}");
1152
            }
1153
        }
1154
    }
1155
    for c in &snap.base_snapshot.tree.conflicts {
1156
        remaining += 1;
1157
        println!("tree       {c:?}");
1158
    }
1159
    if remaining == 0 {
1160
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
1161
        Ok(0)
1162
    } else {
1163
        Ok(2)
1164
    }
1165
}
1166
1167
pub fn undo() -> Result<i32> {
1168
    let repo = open()?;
1169
    let op = repo.undo()?;
94084087 Andy McCall ↶ 1170
    println!("{} now at: {}", ui::done("Undone;"), ui::dim(&op.command));
fce44ae9 Andy McCall ↶ 1171
    Ok(0)
1172
}
1173
c6aa5bd9 Andy McCall ↶ 1174
pub fn op_log(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 1175
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 1176
    if as_json {
1177
        let ops = repo.op_log()?;
1178
        println!(
1179
            "{}",
1180
            json::arr(ops.iter().enumerate().map(|(i, (r, op))| {
1181
                json::obj([
1182
                    ("id", json::s(&r.to_hex())),
1183
                    ("when_ms", json::n(op.hlc.wall_ms)),
1184
                    ("command", json::s(&op.command)),
1185
                    ("snapshot", json::b(op.command.ends_with("(snapshot)"))),
1186
                    ("current", json::b(i == 0)),
1187
                ])
1188
            }))
1189
        );
1190
        return Ok(0);
1191
    }
fce44ae9 Andy McCall ↶ 1192
    for (i, (r, op)) in repo.op_log()?.into_iter().enumerate() {
75167672 Andy McCall 1193
        let bullet = if i == 0 {
1194
            ui::ok(ui::glyph("●", "@"))
1195
        } else {
1196
            ui::dim(ui::glyph("○", "o"))
1197
        };
94084087 Andy McCall ↶ 1198
        let cmd = subject_of(&op.command).split("\\n").next().unwrap_or("");
75167672 Andy McCall 1199
        println!(
1200
            "{bullet} {}{}{}  {}",
1201
            ui::hash(r.short(12)),
1202
            ui::sep(),
1203
            ui::dim(format!("{:<16}", ui::ago(op.hlc.wall_ms))),
1204
            if i == 0 {
1205
                ui::subject(cmd)
1206
            } else {
1207
                cmd.to_string()
1208
            }
1209
        );
fce44ae9 Andy McCall ↶ 1210
    }
1211
    Ok(0)
1212
}
d02e545d Andy McCall ↶ 1213
ba160f60 Andy McCall ↶ 1214
pub fn gc(now: bool) -> Result<i32> {
d02e545d Andy McCall ↶ 1215
    let repo = open()?;
135212de Andy McCall ↶ 1216
    let sp = ui::spinner("Packing and pruning…");
ba160f60 Andy McCall ↶ 1217
    let r = repo.gc(now)?;
135212de Andy McCall ↶ 1218
    sp.clear();
ba160f60 Andy McCall ↶ 1219
    if r.packed.objects > 0 {
d02e545d Andy McCall ↶ 1220
        println!(
da652d63 Andy McCall ↶ 1221
            "Packed {} into one pack: {} bytes -> {} bytes ({:.0}%).",
1222
            plural(r.packed.objects, "object"),
ba160f60 Andy McCall ↶ 1223
            r.packed.raw_bytes,
1224
            r.packed.packed_bytes,
1225
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
d02e545d Andy McCall ↶ 1226
        );
1227
    }
75167672 Andy McCall 1228
    println!(
1229
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
ba160f60 Andy McCall ↶ 1230
        plural(r.reachable, "object"),
1231
        plural(r.pruned.objects, "unreachable object"),
1232
        r.pruned.bytes,
75167672 Andy McCall 1233
        if r.pruned.deferred > 0 {
1234
            format!(
1235
                "; {} deferred by the grace period (use --now)",
1236
                plural(r.pruned.deferred, "object")
1237
            )
1238
        } else {
1239
            String::new()
1240
        },
1241
        if r.merged_packs > 0 {
1242
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1243
        } else {
1244
            String::new()
1245
        },
ba160f60 Andy McCall ↶ 1246
        plural(repo.store().pack_count(), "pack")
1247
    );
d02e545d Andy McCall ↶ 1248
    Ok(0)
1249
}
614541c3 Andy McCall ↶ 1250
3e5772cc Andy McCall ↶ 1251
/// `oxy doctor`: exit 1 when a check fails, 0 otherwise (warnings allowed).
1252
pub fn doctor(offline: bool, as_json: bool) -> Result<i32> {
1253
    use oxy_core::repo::Health;
1254
    let repo = open()?;
1255
    let sp = ui::spinner(if offline {
1256
        "Checking…"
1257
    } else {
1258
        "Checking, and contacting remotes…"
1259
    });
1260
    let r = repo.doctor(!offline);
1261
    sp.clear();
1262
    let code = if r.worst() == Health::Fail { 1 } else { 0 };
1263
    let word = |h: Health| match h {
1264
        Health::Ok => "ok",
1265
        Health::Warn => "warning",
1266
        Health::Fail => "fail",
1267
    };
1268
    if as_json {
1269
        let checks: Vec<String> = r
1270
            .checks
1271
            .iter()
1272
            .map(|c| {
1273
                json::obj([
1274
                    ("area", json::s(&c.area)),
1275
                    ("health", json::s(word(c.health))),
1276
                    ("message", json::s(&c.message)),
1277
                    ("hint", json::opt(c.hint.as_deref(), json::s)),
1278
                ])
1279
            })
1280
            .collect();
1281
        println!(
1282
            "{}",
1283
            json::obj([("ok", json::b(code == 0)), ("checks", json::arr(checks))])
1284
        );
1285
        return Ok(code);
1286
    }
1287
    let mut last = "";
1288
    for c in &r.checks {
1289
        if c.area != last {
1290
            println!("{}", ui::section(&c.area));
1291
            last = &c.area;
1292
        }
1293
        let mark = match c.health {
1294
            Health::Ok => ui::ok(ui::glyph("✔", "v")),
1295
            Health::Warn => ui::caution(),
1296
            Health::Fail => ui::err(ui::glyph("✖", "x")),
1297
        };
1298
        println!("  {mark} {}", c.message);
1299
        if let Some(h) = &c.hint {
1300
            println!("    {} {}", ui::dim("→"), ui::dim(h));
1301
        }
1302
    }
1303
    let fails = r.checks.iter().filter(|c| c.health == Health::Fail).count();
1304
    let warns = r.checks.iter().filter(|c| c.health == Health::Warn).count();
1305
    if fails + warns == 0 {
1306
        println!("{}", ui::done("Everything looks right."));
1307
    } else {
1308
        println!(
1309
            "{} {}, {}.",
1310
            if fails > 0 {
1311
                ui::err(ui::glyph("✖", "x"))
1312
            } else {
1313
                ui::caution()
1314
            },
1315
            plural(fails, "problem"),
1316
            plural(warns, "warning")
1317
        );
1318
    }
1319
    Ok(code)
1320
}
1321
387335ff Andy McCall ↶ 1322
/// `oxy fsck`: exit 0 when sound (warnings allowed), 1 on any error.
1323
pub fn fsck(as_json: bool) -> Result<i32> {
1324
    use oxy_core::repo::Severity;
1325
    let repo = open()?;
1326
    let sp = ui::spinner("Checking every object…");
1327
    let r = repo.fsck()?;
1328
    sp.clear();
1329
    let code = if r.errors() > 0 { 1 } else { 0 };
1330
    if as_json {
1331
        let problems: Vec<String> = r
1332
            .problems
1333
            .iter()
1334
            .map(|p| {
1335
                json::obj([
1336
                    (
1337
                        "severity",
1338
                        json::s(match p.severity {
1339
                            Severity::Error => "error",
1340
                            Severity::Warning => "warning",
1341
                        }),
1342
                    ),
1343
                    (
1344
                        "object",
1345
                        json::opt(p.object.map(|o| o.to_hex()).as_deref(), json::s),
1346
                    ),
1347
                    ("what", json::s(&p.what)),
1348
                ])
1349
            })
1350
            .collect();
1351
        println!(
1352
            "{}",
1353
            json::obj([
1354
                ("ok", json::b(code == 0)),
1355
                ("objects", json::n(r.objects)),
1356
                ("ops", json::n(r.ops)),
1357
                ("changes", json::n(r.changes)),
1358
                ("signed", json::n(r.signed)),
1359
                ("unsigned", json::n(r.unsigned)),
1360
                ("checkpoints", json::n(r.checkpoints)),
1361
                ("attestations", json::n(r.attestations)),
1362
                ("errors", json::n(r.errors())),
1363
                ("warnings", json::n(r.warnings())),
1364
                ("problems", json::arr(problems)),
1365
            ])
1366
        );
1367
        return Ok(code);
1368
    }
1369
    println!(
1370
        "Checked {}, {}, {} ({} signed or sealed, {} unsigned), {}, {}.",
1371
        plural(r.objects, "object"),
1372
        plural(r.ops, "operation"),
1373
        plural(r.changes, "change"),
1374
        r.signed,
1375
        r.unsigned,
1376
        plural(r.checkpoints, "checkpoint"),
1377
        plural(r.attestations, "attestation"),
1378
    );
1379
    for p in &r.problems {
1380
        let obj = p
1381
            .object
1382
            .map(|o| format!("{} ", ui::hash(format!("#{}", o.short(12)))))
1383
            .unwrap_or_default();
1384
        match p.severity {
1385
            Severity::Error => println!("{} {obj}{}", ui::err(ui::glyph("✖", "x")), p.what),
1386
            Severity::Warning => println!("{} {obj}{}", ui::caution(), p.what),
1387
        }
1388
    }
1389
    if r.problems.is_empty() {
1390
        println!("{}", ui::done("No problems found."));
1391
    } else if code == 0 {
1392
        println!(
1393
            "{}",
1394
            ui::done(format!("Sound, with {}.", plural(r.warnings(), "warning")))
1395
        );
1396
    } else {
1397
        println!(
1398
            "{} {} and {}. Fetch missing objects from a remote with `oxy pull`, or clone afresh and compare.",
1399
            ui::err(ui::glyph("✖", "x")),
1400
            plural(r.errors(), "error"),
1401
            plural(r.warnings(), "warning")
1402
        );
1403
    }
1404
    Ok(code)
1405
}
1406
79d03f82 Andy McCall ↶ 1407
/// The head the working copy sits on, for commands that default to it. With
1408
/// several heads beneath the working copy, the most recently made one is
1409
/// chosen and announced.
614541c3 Andy McCall ↶ 1410
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
cc7a0056 Andy McCall ↶ 1411
    let snap = repo.snapshot_status("oxy")?;
614541c3 Andy McCall ↶ 1412
    let base = snap.base.maximal(&snap.wc.deps);
1413
    match base.as_slice() {
79d03f82 Andy McCall ↶ 1414
        [] => anyhow::bail!("the working copy sits on no change yet"),
614541c3 Andy McCall ↶ 1415
        [h] => Ok(*h),
79d03f82 Andy McCall ↶ 1416
        many => {
1417
            let latest = many
1418
                .iter()
1419
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
1420
                .copied()
1421
                .unwrap();
1422
            let c = repo.store().get_change(&latest)?;
75167672 Andy McCall 1423
            println!(
1424
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
1425
                short_id(&c),
1426
                latest.short(12),
1427
                many.len()
1428
            );
79d03f82 Andy McCall ↶ 1429
            Ok(latest)
1430
        }
614541c3 Andy McCall ↶ 1431
    }
1432
}
1433
6a81dbab Andy McCall ↶ 1434
/// `oxy describe` without -m: the working copy's name for a build.
1435
pub fn describe_name(as_json: bool) -> Result<i32> {
1436
    let repo = open()?;
1437
    let d = repo.describe_working_copy()?;
1438
    if as_json {
1439
        println!(
1440
            "{}",
1441
            json::obj([
1442
                ("describe", json::s(&d.line())),
1443
                ("tag", json::opt(d.tag.as_ref(), |t| json::s(t))),
1444
                ("distance", json::n(d.distance)),
1445
                ("bookmark", json::s(&d.bookmark)),
1446
                ("change", json::s(&d.change.to_hex())),
1447
                ("hash", json::s(&d.hash.to_hex())),
1448
                ("dirty", json::b(d.dirty)),
1449
            ])
1450
        );
1451
    } else {
1452
        println!("{}", d.line());
1453
    }
1454
    Ok(0)
1455
}
1456
614541c3 Andy McCall ↶ 1457
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
1458
    let repo = open()?;
1459
    let h = match change {
1460
        Some(c) => repo.resolve_change(c)?,
1461
        None => current_head(&repo)?,
1462
    };
1463
    let new = repo.describe(&h, message)?;
1464
    let c = repo.store().get_change(&new)?;
75167672 Andy McCall 1465
    println!(
1466
        "{} {} {}  {}",
1467
        ui::done("Described"),
1468
        ui::id(short_id(&c)),
1469
        ui::hash(format!("#{}", new.short(12))),
1470
        ui::subject(subject_of(message))
1471
    );
614541c3 Andy McCall ↶ 1472
    Ok(0)
1473
}
1474
23b217d7 Andy McCall ↶ 1475
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
614541c3 Andy McCall ↶ 1476
    let repo = open()?;
23b217d7 Andy McCall ↶ 1477
    let new = match into {
1478
        Some(spec) => {
1479
            let target = repo.resolve_change(spec)?;
1480
            repo.amend_into(&target, message)?
1481
        }
1482
        None => repo.amend(message)?,
1483
    };
614541c3 Andy McCall ↶ 1484
    let c = repo.store().get_change(&new)?;
75167672 Andy McCall 1485
    println!(
1486
        "{} {} {}  {}",
1487
        ui::done("Amended"),
1488
        ui::id(short_id(&c)),
1489
        ui::hash(format!("#{}", new.short(12))),
1490
        ui::subject(subject_of(&c.message))
1491
    );
614541c3 Andy McCall ↶ 1492
    Ok(0)
1493
}
1494
1495
pub fn abandon(change: &str) -> Result<i32> {
1496
    let repo = open()?;
1497
    let h = repo.resolve_change(change)?;
1498
    let c = repo.store().get_change(&h)?;
6706bdcf Andy McCall ↶ 1499
    let notes = repo.abandon(&h)?;
75167672 Andy McCall 1500
    println!(
1501
        "{} {} {}  {}",
1502
        ui::done("Abandoned"),
1503
        ui::id(short_id(&c)),
1504
        ui::hash(format!("#{}", h.short(12))),
1505
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
1506
    );
6706bdcf Andy McCall ↶ 1507
    for n in notes {
94084087 Andy McCall ↶ 1508
        println!("  {} {n}", ui::note());
6706bdcf Andy McCall ↶ 1509
    }
614541c3 Andy McCall ↶ 1510
    Ok(0)
1511
}
252e8cb2 Andy McCall ↶ 1512
1513
pub fn checkpoint() -> Result<i32> {
1514
    let repo = open()?;
135212de Andy McCall ↶ 1515
    let sp = ui::spinner("Writing checkpoint…");
252e8cb2 Andy McCall ↶ 1516
    let (r, changes, bytes) = repo.checkpoint()?;
75167672 Andy McCall 1517
    sp.done(&format!(
1518
        "{} {} of {} ({} bytes) for {}",
1519
        ui::done("Checkpoint"),
1520
        ui::hash(format!("#{}", r.short(12))),
1521
        plural(changes, "change"),
1522
        bytes,
1523
        ui::id(&repo.config.bookmark)
1524
    ));
135212de Andy McCall ↶ 1525
    Ok(0)
1526
}
1527
1528
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
694805cc Andy McCall ↶ 1529
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
75167672 Andy McCall 1530
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
1531
        return Ok(1);
1532
    };
135212de Andy McCall ↶ 1533
    let info = repo.quick_status()?;
75167672 Andy McCall 1534
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
1535
        oxy_core::repo::GLYPH_PROMPT_FORMAT
1536
    } else {
1537
        format
1538
    };
694805cc Andy McCall ↶ 1539
    let line = match color {
1540
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
1541
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
1542
        Some(_) => info.format_colored(fmt, ("", "")),
1543
        None => info.format(fmt),
1544
    };
1545
    println!("{line}");
252e8cb2 Andy McCall ↶ 1546
    Ok(0)
1547
}
7421309f Andy McCall ↶ 1548
1549
pub fn sparse(paths: &[String]) -> Result<i32> {
1550
    let mut repo = open()?;
1551
    if paths.is_empty() {
1552
        if repo.config.sparse_paths.is_empty() {
1553
            println!("No sparse filter: the whole tree is materialized.");
1554
        } else {
1555
            println!("{}", ui::heading("Sparse filter"));
1556
            for p in &repo.config.sparse_paths {
1557
                println!("  {}", ui::path(p));
1558
            }
1559
        }
1560
        return Ok(0);
1561
    }
1562
    let snap = repo.snapshot("oxy sparse")?;
1563
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
75167672 Andy McCall 1564
        anyhow::bail!(
1565
            "the working copy has changes; commit them before changing the sparse filter"
1566
        );
7421309f Andy McCall ↶ 1567
    }
1568
    repo.config.set("filter.paths", &paths.join(","))?;
1569
    repo.save_config()?;
1570
    let heads = repo.bookmark_heads()?;
1571
    let sp = ui::spinner("Re-checking out with the new filter…");
1572
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
75167672 Andy McCall 1573
    sp.done(&format!(
1574
        "{} {}: {} written, {} removed",
1575
        ui::ok("Sparse filter set to"),
1576
        ui::path(paths.join(",")),
1577
        plural(r.written, "file"),
1578
        r.removed
1579
    ));
7421309f Andy McCall ↶ 1580
    Ok(0)
1581
}
132b884b Andy McCall ↶ 1582
1583
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
1584
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1585
    repo.snapshot_status("oxy tag")?;
132b884b Andy McCall ↶ 1586
    let heads = if changes.is_empty() {
1587
        repo.bookmark_heads()?
1588
    } else {
1589
        let mut heads = Vec::new();
1590
        for c in changes {
1591
            heads.extend(repo.resolve_heads(c)?);
1592
        }
1593
        heads
1594
    };
1595
    let t = repo.tag_create(name, &heads, message)?;
1596
    println!(
94084087 Andy McCall ↶ 1597
        "{} {} {} {} ({}){}",
1598
        ui::done("Tagged"),
1599
        ui::bookmark(&t.name),
1600
        ui::dim(ui::glyph("→", "->")),
132b884b Andy McCall ↶ 1601
        ui::hash(format!("#{}", t.state.short(12))),
1602
        plural(t.heads.len(), "head"),
75167672 Andy McCall 1603
        t.signer
1604
            .map(|s| format!(", signed by {s}"))
1605
            .unwrap_or_else(|| ui::dim(", unsigned"))
132b884b Andy McCall ↶ 1606
    );
1607
    Ok(0)
1608
}
1609
1196b29b Andy McCall ↶ 1610
pub fn tag_list(as_json: bool) -> Result<i32> {
132b884b Andy McCall ↶ 1611
    let repo = open()?;
1612
    let tags = repo.tags()?;
1196b29b Andy McCall ↶ 1613
    if as_json {
1614
        println!(
1615
            "{}",
1616
            json::arr(tags.iter().map(|t| {
1617
                json::obj([
1618
                    ("name", json::s(&t.name)),
1619
                    ("state", json::s(&t.state.to_hex())),
1620
                    ("heads", json::hashes(&t.heads)),
1621
                    ("message", json::s(&t.message)),
75167672 Andy McCall 1622
                    (
1623
                        "signer",
1624
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
1625
                    ),
1196b29b Andy McCall ↶ 1626
                ])
1627
            }))
1628
        );
1629
        return Ok(0);
1630
    }
132b884b Andy McCall ↶ 1631
    if tags.is_empty() {
1632
        println!("{}", ui::dim("No tags."));
1633
    }
1634
    for t in tags {
1635
        println!(
94084087 Andy McCall ↶ 1636
            "{} {} {}{}{}{}",
1637
            ui::ok(ui::glyph("⚑", "#")),
1638
            ui::bookmark(&t.name),
6a81dbab Andy McCall ↶ 1639
            // The heads, as `oxy log` shows changes, not the state hash.
1640
            ui::hash(
1641
                t.heads
1642
                    .iter()
1643
                    .map(|h| format!("#{}", h.short(12)))
1644
                    .collect::<Vec<_>>()
1645
                    .join(" ")
1646
            ),
94084087 Andy McCall ↶ 1647
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
75167672 Andy McCall 1648
            if t.message.is_empty() {
1649
                String::new()
1650
            } else {
1651
                format!("  {}", ui::subject(subject_of(&t.message)))
1652
            },
1653
            t.signer
1654
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
1655
                .unwrap_or_default()
132b884b Andy McCall ↶ 1656
        );
1657
    }
1658
    Ok(0)
1659
}
4e88e774 Andy McCall ↶ 1660
1661
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
1662
    let repo = open()?;
1663
    let heads = if changes.is_empty() {
1664
        None
1665
    } else {
1666
        let mut heads = Vec::new();
1667
        for c in changes {
1668
            heads.extend(repo.resolve_heads(c)?);
1669
        }
1670
        Some(heads)
1671
    };
1672
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
1673
    let ws = repo.workspace_add(path, heads.as_deref())?;
75167672 Andy McCall 1674
    sp.done(&format!(
1675
        "{} {} (workspace {})",
1676
        ui::done("Workspace created at"),
1677
        ui::path(ws.root().display()),
1678
        ui::id(ws.workspace().short(8))
1679
    ));
4e88e774 Andy McCall ↶ 1680
    Ok(0)
1681
}
1682
1196b29b Andy McCall ↶ 1683
pub fn workspace_list(as_json: bool) -> Result<i32> {
4e88e774 Andy McCall ↶ 1684
    let repo = open()?;
1196b29b Andy McCall ↶ 1685
    if as_json {
1686
        println!(
1687
            "{}",
1688
            json::arr(repo.workspaces()?.iter().map(|w| {
1689
                json::obj([
1690
                    ("id", json::s(&w.id.to_hex())),
1691
                    ("path", json::s(&w.path.to_string_lossy())),
1692
                    ("current", json::b(w.current)),
75167672 Andy McCall 1693
                    (
1694
                        "working_copy",
1695
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
1696
                    ),
1196b29b Andy McCall ↶ 1697
                ])
1698
            }))
1699
        );
1700
        return Ok(0);
1701
    }
4e88e774 Andy McCall ↶ 1702
    for w in repo.workspaces()? {
1703
        println!(
1704
            "{} {} {}{}",
75167672 Andy McCall 1705
            if w.current {
1706
                ui::ok(ui::glyph("●", "*"))
1707
            } else {
1708
                ui::dim(ui::glyph("○", "o"))
1709
            },
4e88e774 Andy McCall ↶ 1710
            ui::id(w.id.short(8)),
1711
            ui::path(w.path.display()),
75167672 Andy McCall 1712
            w.working_copy
1713
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
1714
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
4e88e774 Andy McCall ↶ 1715
        );
1716
    }
1717
    Ok(0)
1718
}
1719
1720
pub fn workspace_forget(spec: &str) -> Result<i32> {
1721
    let repo = open()?;
1722
    let all = repo.workspaces()?;
1723
    let target = std::fs::canonicalize(spec).ok();
75167672 Andy McCall 1724
    let matches: Vec<_> = all
1725
        .iter()
1726
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
1727
        .collect();
4e88e774 Andy McCall ↶ 1728
    let w = match matches.as_slice() {
1729
        [w] => *w,
1730
        [] => anyhow::bail!("no workspace matches {spec:?}"),
1731
        _ => anyhow::bail!("{spec:?} is ambiguous"),
1732
    };
1733
    repo.workspace_forget(&w.id)?;
75167672 Andy McCall 1734
    println!(
1735
        "{} workspace {} at {}; its files were left in place.",
1736
        ui::done("Forgot"),
1737
        ui::id(w.id.short(8)),
1738
        ui::path(w.path.display())
1739
    );
4e88e774 Andy McCall ↶ 1740
    Ok(0)
1741
}
cdb5beba Andy McCall ↶ 1742
1743
pub fn lock(path: &str) -> Result<i32> {
1744
    let repo = open()?;
1745
    repo.lock_path(path)?;
75167672 Andy McCall 1746
    println!(
1747
        "{} {} {}",
1748
        ui::done("Locked"),
1749
        ui::path(path),
1750
        ui::dim("(advisory, local)")
1751
    );
cdb5beba Andy McCall ↶ 1752
    Ok(0)
1753
}
1754
1755
pub fn unlock(path: &str) -> Result<i32> {
1756
    let repo = open()?;
1757
    repo.unlock_path(path)?;
94084087 Andy McCall ↶ 1758
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
cdb5beba Andy McCall ↶ 1759
    Ok(0)
1760
}
23b217d7 Andy McCall ↶ 1761
1762
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
1763
    let repo = open()?;
1764
    let h = repo.resolve_change(change)?;
1765
    let (h1, h2) = repo.split(&h, paths)?;
1766
    let c1 = repo.store().get_change(&h1)?;
1767
    let c2 = repo.store().get_change(&h2)?;
75167672 Andy McCall 1768
    println!(
1769
        "{} into {} {} and {} {}",
1770
        ui::done("Split"),
1771
        ui::id(short_id(&c1)),
1772
        ui::hash(format!("#{}", h1.short(12))),
1773
        ui::id(short_id(&c2)),
1774
        ui::hash(format!("#{}", h2.short(12)))
1775
    );
23b217d7 Andy McCall ↶ 1776
    Ok(0)
1777
}
7b9809e6 Andy McCall ↶ 1778
1779
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
1780
    let mut heads = Vec::new();
1781
    for c in changes {
1782
        heads.extend(repo.resolve_heads(c)?);
1783
    }
1784
    Ok(heads)
1785
}
1786
4fe7d604 Andy McCall ↶ 1787
pub fn bookmark_create(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 1788
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1789
    repo.snapshot_status("oxy bookmark create")?;
75167672 Andy McCall 1790
    let heads = if changes.is_empty() {
1791
        None
1792
    } else {
4fe7d604 Andy McCall ↶ 1793
        let named = heads_from(&repo, changes)?;
1794
        let (_, wc) = repo.working_copy()?;
1795
        let gap = repo.state_gap(&wc.deps, &named)?;
1796
        if upto {
1797
            Some(gap.upto)
1798
        } else if only || gap.earlier.is_empty() {
1799
            Some(named)
1800
        } else {
1801
            anyhow::bail!(
1802
                "{name} at {} would lack {} of the current state recorded before it:\n{}\n\
1803
                 A state is its heads and what they depend on, not everything recorded before them.\n\
1804
                 Pass --upto for everything of the current state up to {0} (as a Git branch would hold),\n\
1805
                 or --only for just {0} and what it depends on.",
1806
                changes.join(" "),
1807
                plural(gap.earlier.len(), "change"),
1808
                listed_changes(&repo, &gap.earlier)
1809
            );
1810
        }
75167672 Andy McCall 1811
    };
7b9809e6 Andy McCall ↶ 1812
    let heads = repo.bookmark_create(name, heads.as_deref())?;
75167672 Andy McCall 1813
    println!(
1814
        "{} bookmark {} {} {}",
1815
        ui::done("Created"),
1816
        ui::bookmark(name),
1817
        ui::dim(ui::glyph("→", "->")),
1818
        ui::dim(plural(heads.len(), "head"))
1819
    );
1820
    println!(
1821
        "  {} {}",
1822
        ui::note(),
1823
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
1824
    );
7b9809e6 Andy McCall ↶ 1825
    Ok(0)
1826
}
1827
4fe7d604 Andy McCall ↶ 1828
/// Up to five changes, newest last, as `  #hash subject` lines.
1829
fn listed_changes(repo: &Repo, changes: &[oxy_core::hash::ChangeHash]) -> String {
1830
    let shown = changes.len().min(5);
1831
    let mut lines: Vec<String> = changes[changes.len() - shown..]
1832
        .iter()
1833
        .map(|h| {
1834
            let subject = repo
1835
                .store()
1836
                .get_change(h)
1837
                .map(|c| subject_of(&c.message).to_string())
1838
                .unwrap_or_default();
1839
            format!("  #{} {subject}", h.short(12))
1840
        })
1841
        .collect();
1842
    if changes.len() > shown {
1843
        lines.insert(0, format!("  … and {} earlier", changes.len() - shown));
1844
    }
1845
    lines.join("\n")
1846
}
1847
06d16dc2 Andy McCall ↶ 1848
pub fn bookmark_set(name: &str, changes: &[String], upto: bool, only: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 1849
    let repo = open()?;
cc7a0056 Andy McCall ↶ 1850
    repo.snapshot_status("oxy bookmark set")?;
06d16dc2 Andy McCall ↶ 1851
    let named = heads_from(&repo, changes)?;
1852
    // What the bookmark holds now and the new heads would leave out.
1853
    let current = repo
1854
        .bookmarks()?
1855
        .into_iter()
1856
        .find(|b| b.name == name)
1857
        .map(|b| b.heads)
1858
        .ok_or_else(|| anyhow::anyhow!("no bookmark {name}"))?;
1859
    let gap = repo.state_gap(&current, &named)?;
1860
    let heads = if upto {
1861
        gap.upto
1862
    } else if only || gap.earlier.is_empty() {
1863
        named
1864
    } else {
1865
        anyhow::bail!(
1866
            "{name} at {} would lose {} it holds now, recorded before it:\n{}\n\
1867
             A state is its heads and what they depend on, not everything recorded before them.\n\
1868
             Pass --upto to keep everything {name} holds up to {0} (as a Git branch would),\n\
1869
             or --only for just {0} and what it depends on.",
1870
            changes.join(" "),
1871
            plural(gap.earlier.len(), "change"),
1872
            listed_changes(&repo, &gap.earlier)
1873
        );
1874
    };
7b9809e6 Andy McCall ↶ 1875
    let heads = repo.bookmark_set(name, &heads)?;
75167672 Andy McCall 1876
    println!(
1877
        "{} bookmark {} {} {}",
1878
        ui::done("Moved"),
1879
        ui::bookmark(name),
1880
        ui::dim(ui::glyph("→", "->")),
1881
        ui::dim(plural(heads.len(), "head"))
1882
    );
7b9809e6 Andy McCall ↶ 1883
    Ok(0)
1884
}
1885
1886
pub fn bookmark_delete(name: &str) -> Result<i32> {
1887
    let repo = open()?;
1888
    repo.bookmark_delete(name)?;
75167672 Andy McCall 1889
    println!(
1890
        "{} bookmark {} {}",
1891
        ui::done("Deleted"),
1892
        ui::bookmark(name),
1893
        ui::dim("(its changes stay until unreachable)")
1894
    );
7b9809e6 Andy McCall ↶ 1895
    Ok(0)
1896
}
1897
14edbaaf Andy McCall ↶ 1898
pub fn bookmark_list(all: bool, as_json: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 1899
    let repo = open()?;
14edbaaf Andy McCall ↶ 1900
    let remote_only = repo.remote_only_bookmarks()?;
c6aa5bd9 Andy McCall ↶ 1901
    if as_json {
14edbaaf Andy McCall ↶ 1902
        let mut items: Vec<String> = repo
1903
            .bookmarks()?
1904
            .into_iter()
1905
            .map(|b| {
1906
                json::obj([
1907
                    ("name", json::s(&b.name)),
1908
                    ("heads", json::hashes(&b.heads)),
1909
                    ("current", json::b(b.current)),
1910
                    ("ahead", json::opt(b.ahead, json::n)),
1911
                    ("behind", json::opt(b.behind, json::n)),
1912
                ])
1913
            })
1914
            .collect();
1915
        if all {
1916
            items.extend(remote_only.iter().map(|b| {
1917
                json::obj([
1918
                    ("name", json::s(&format!("{}/{}", b.remote, b.name))),
1919
                    ("heads", json::hashes(&b.heads)),
1920
                    ("current", json::b(false)),
1921
                    ("ahead", "null".into()),
1922
                    ("behind", "null".into()),
1923
                    ("remote", json::s(&b.remote)),
1924
                ])
1925
            }));
1926
        }
c6aa5bd9 Andy McCall ↶ 1927
        println!("{}", json::arr(items));
1928
        return Ok(0);
1929
    }
7b9809e6 Andy McCall ↶ 1930
    for b in repo.bookmarks()? {
75167672 Andy McCall 1931
        let mark = if b.current {
1932
            ui::ok(ui::glyph("●", "*"))
1933
        } else {
1934
            ui::dim(ui::glyph("○", "o"))
1935
        };
7b9809e6 Andy McCall ↶ 1936
        let mut tail = String::new();
1937
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
1938
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
1939
        }
1940
        if let Some(n) = b.behind.filter(|n| *n > 0) {
1941
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
1942
        }
75167672 Andy McCall 1943
        let head = b
1944
            .heads
1945
            .first()
1946
            .map(|h| {
1947
                repo.store()
1948
                    .get_change(h)
1949
                    .map(|c| ui::subject(subject_of(&c.message)))
1950
                    .unwrap_or_default()
1951
            })
1952
            .unwrap_or_else(|| ui::dim("(empty)"));
1953
        println!(
1954
            "{mark} {}{}{}{tail}  {head}",
1955
            ui::bookmark(&b.name),
14edbaaf Andy McCall ↶ 1956
            ui::sep(),
1957
            ui::dim(plural(b.heads.len(), "head"))
1958
        );
1959
    }
1960
    if remote_only.is_empty() {
1961
        return Ok(0);
1962
    }
1963
    if !all {
1964
        println!(
1965
            "{}",
1966
            ui::dim(format!(
1967
                "  and {} only on a remote: oxy bookmark list --all",
1968
                plural(remote_only.len(), "bookmark")
1969
            ))
1970
        );
1971
        return Ok(0);
1972
    }
1973
    for b in &remote_only {
1974
        println!(
1975
            "{} {}{}{}",
1976
            ui::dim(ui::glyph("◌", ".")),
1977
            ui::dim(format!("{}/{}", b.remote, b.name)),
75167672 Andy McCall 1978
            ui::sep(),
1979
            ui::dim(plural(b.heads.len(), "head"))
1980
        );
7b9809e6 Andy McCall ↶ 1981
    }
14edbaaf Andy McCall ↶ 1982
    println!(
1983
        "  {} {}",
1984
        ui::note(),
1985
        ui::dim("oxy bookmark switch NAME makes a local bookmark from a remote's")
1986
    );
7b9809e6 Andy McCall ↶ 1987
    Ok(0)
1988
}
1989
61e3bce7 Andy McCall ↶ 1990
pub fn bookmark_switch(name: &str, discard: bool, carry: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 1991
    let mut repo = open()?;
4fe7d604 Andy McCall ↶ 1992
    let from = repo.config.bookmark.clone();
14edbaaf Andy McCall ↶ 1993
    let (local, created_from) = repo.local_bookmark_for(name)?;
1994
    if let Some(remote) = created_from {
1995
        println!(
1996
            "{} {} from {}",
1997
            ui::done("Created"),
1998
            ui::bookmark(&local),
1999
            ui::dim(format!("{remote}/{local}"))
2000
        );
2001
    }
2002
    let name = local.as_str();
7b9809e6 Andy McCall ↶ 2003
    let sp = ui::spinner(&format!("Switching to {name}…"));
61e3bce7 Andy McCall ↶ 2004
    let (r, carried) = if carry {
2005
        repo.bookmark_switch_carry(name)?
2006
    } else {
2007
        (repo.bookmark_switch(name, discard)?, vec![])
2008
    };
75167672 Andy McCall 2009
    sp.done(&format!(
61e3bce7 Andy McCall ↶ 2010
        "{} to {}: {} written, {} removed{}",
75167672 Andy McCall 2011
        ui::done("Switched"),
2012
        ui::bookmark(name),
2013
        plural(r.written, "file"),
61e3bce7 Andy McCall ↶ 2014
        r.removed,
2015
        if carried.is_empty() {
2016
            String::new()
2017
        } else {
2018
            format!("; carried {}", plural(carried.len(), "changed path"))
2019
        }
75167672 Andy McCall 2020
    ));
7b9809e6 Andy McCall ↶ 2021
    if r.conflicted {
75167672 Andy McCall 2022
        println!(
2023
            "  {} {}",
2024
            ui::caution(),
2025
            ui::warn("this state has conflicts; see oxy status")
2026
        );
4fe7d604 Andy McCall ↶ 2027
    }
2028
    // Say when the new state leaves out work the old one had: a state is
2029
    // its heads and what they depend on, which can be far less than a Git
2030
    // user expects.
d3cd7ef9 Andy McCall ↶ 2031
    if r.lacks > 0 {
2032
        println!(
2033
            "  {} {}",
2034
            ui::note(),
2035
            ui::dim(format!(
2036
                "{name} lacks {} that {from} has",
2037
                plural(r.lacks, "change")
2038
            ))
2039
        );
7b9809e6 Andy McCall ↶ 2040
    }
14edbaaf Andy McCall ↶ 2041
    super::sync::subrepos_behind(&repo);
7b9809e6 Andy McCall ↶ 2042
    Ok(0)
2043
}
2044
2045
pub fn merge(bookmark: &str) -> Result<i32> {
2046
    let repo = open()?;
2047
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
2048
    let r = repo.merge(bookmark)?;
2049
    if !r.changed {
75167672 Andy McCall 2050
        sp.done(&format!(
2051
            "{} {}",
2052
            ui::ok(ui::glyph("✔", "*")),
2053
            ui::dim(format!(
2054
                "{} already contains {bookmark}",
2055
                repo.config.bookmark
2056
            ))
2057
        ));
7b9809e6 Andy McCall ↶ 2058
        return Ok(0);
2059
    }
2060
    sp.done(&format!(
2061
        "{} {} into {}: now {}{}",
2062
        ui::done("Merged"),
2063
        ui::bookmark(bookmark),
2064
        ui::bookmark(&repo.config.bookmark),
2065
        plural(r.heads.len(), "head"),
75167672 Andy McCall 2066
        ui::dim(if r.checked_out {
2067
            "; working copy updated"
2068
        } else {
2069
            "; run oxy checkout to update the working copy"
2070
        })
7b9809e6 Andy McCall ↶ 2071
    ));
2072
    let snap = repo.snapshot("oxy merge")?;
2073
    if snap.base_snapshot.is_conflicted() {
75167672 Andy McCall 2074
        println!(
2075
            "  {} {}",
2076
            ui::caution(),
2077
            ui::warn("the result has conflicts; see oxy status")
2078
        );
7b9809e6 Andy McCall ↶ 2079
    }
2080
    Ok(0)
2081
}
2082
728da0f9 Andy McCall ↶ 2083
pub fn squash(change: &str, into: &str) -> Result<i32> {
2084
    let repo = open()?;
2085
    let c = repo.resolve_change(change)?;
2086
    let d = repo.resolve_change(into)?;
2087
    let sp = ui::spinner("Squashing…");
2088
    let h = repo.squash(&c, &d)?;
2089
    let new = repo.store().get_change(&h)?;
75167672 Andy McCall 2090
    sp.done(&format!(
2091
        "{} into {} {}  {}",
2092
        ui::done("Squashed"),
2093
        ui::id(short_id(&new)),
2094
        ui::hash(format!("#{}", h.short(12))),
2095
        ui::subject(subject_of(&new.message))
2096
    ));
728da0f9 Andy McCall ↶ 2097
    Ok(0)
2098
}
2099
e266b7d4 Andy McCall ↶ 2100
pub fn rebase(change: &str, onto: &[String], into_working_copy: bool) -> Result<i32> {
728da0f9 Andy McCall ↶ 2101
    let repo = open()?;
2102
    let c = repo.resolve_change(change)?;
2103
    let mut heads = Vec::new();
2104
    for o in onto {
2105
        heads.extend(repo.resolve_heads(o)?);
2106
    }
2107
    let sp = ui::spinner("Rebasing…");
e266b7d4 Andy McCall ↶ 2108
    let h = match repo.rebase(&c, &heads) {
2109
        Err(oxy_core::repo::RepoError::Conflicted(_)) if into_working_copy => {
2110
            let r = repo.rebase_into_working_copy(&c, &heads)?;
2111
            sp.done(&format!(
2112
                "{} {} into {}: now {}",
2113
                ui::done("Merged"),
2114
                onto.join(" "),
2115
                ui::bookmark(&repo.config.bookmark),
2116
                plural(r.heads.len(), "head"),
2117
            ));
2118
            if r.checked_out {
2119
                println!(
2120
                    "  {} {}",
2121
                    ui::caution(),
2122
                    ui::warn("the conflict is in the working copy: fix the marked files (see oxy status), then oxy commit")
2123
                );
2124
            } else {
2125
                println!(
2126
                    "  {} {}",
2127
                    ui::caution(),
2128
                    ui::warn("the working copy has changes of its own: commit or discard them, then oxy checkout to take the conflict in")
2129
                );
2130
            }
2131
            return Ok(0);
2132
        }
2133
        other => other?,
2134
    };
728da0f9 Andy McCall ↶ 2135
    let new = repo.store().get_change(&h)?;
75167672 Andy McCall 2136
    sp.done(&format!(
2137
        "{} {} {}  {}",
2138
        ui::done("Rebased"),
2139
        ui::id(short_id(&new)),
2140
        ui::hash(format!("#{}", h.short(12))),
2141
        ui::dim(format!(
2142
            "now depends on {}",
2143
            plural(new.deps.len(), "change")
2144
        ))
2145
    ));
728da0f9 Andy McCall ↶ 2146
    Ok(0)
2147
}