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