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