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