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