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