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