OXYGENHUB
# 214a3f27f8f6 oxygen / src / cli / workspace.rs
46.3 KiB · Rust · last changed Unbound hosted repositories adopt the first pusher's id 1 month ago source blame history raw
fce44ae9 Andy McCall ↶ 1
//! Commands that act on the local repository and working copy.
2
75167672 Andy McCall 3
use super::format::{
4
    author_name, deps_line, deps_of, plural, short_id, short_meta_id, signature_line,
5
    signature_mark, subject_of, when,
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};
14
use std::path::PathBuf;
15
e02bf0cd Andy McCall ↶ 16
pub fn init(path: Option<PathBuf>, bare: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 17
    let path = path.unwrap_or(std::env::current_dir()?);
75167672 Andy McCall 18
    let repo = if bare {
19
        Repo::init_bare(&path)?
20
    } else {
21
        Repo::init(&path)?
22
    };
23
    println!(
24
        "{} {}oxy repository in {}",
25
        ui::done("Initialized"),
26
        if bare { "bare " } else { "" },
27
        ui::path(repo.root().display())
28
    );
29
    println!(
30
        "{}",
31
        ui::kv("bookmark", ui::bookmark(&repo.config.bookmark))
32
    );
33
    println!(
34
        "{}",
35
        ui::kv(
36
            "author",
37
            format!(
38
                "{} <{}>",
39
                ui::author(&repo.config.author_name),
40
                repo.config.author_email
41
            )
42
        )
43
    );
fce44ae9 Andy McCall ↶ 44
    Ok(0)
45
}
46
47
fn status_tag(s: ChangeStatus) -> &'static str {
48
    match s {
49
        ChangeStatus::Added => "A",
50
        ChangeStatus::Modified => "M",
51
        ChangeStatus::Removed => "D",
6e723b81 Andy McCall ↶ 52
        ChangeStatus::Renamed => "R",
fce44ae9 Andy McCall ↶ 53
        ChangeStatus::ModeChanged => "X",
54
        ChangeStatus::ConflictEdited => "C!",
6e723b81 Andy McCall ↶ 55
        ChangeStatus::Resolved => "V",
fce44ae9 Andy McCall ↶ 56
    }
57
}
58
50a046e4 Andy McCall ↶ 59
pub fn status(json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 60
    let repo = open()?;
135212de Andy McCall ↶ 61
    let sp = ui::spinner("Snapshotting the working copy…");
fce44ae9 Andy McCall ↶ 62
    let snap = repo.snapshot("oxy status")?;
63
    let heads = repo.bookmark_heads()?;
135212de Andy McCall ↶ 64
    sp.clear();
50a046e4 Andy McCall ↶ 65
    if json {
66
        println!("{}", repo.status_json(&snap)?);
75167672 Andy McCall 67
        return Ok(if snap.base_snapshot.is_conflicted() {
68
            2
69
        } else {
70
            0
71
        });
50a046e4 Andy McCall ↶ 72
    }
135212de Andy McCall ↶ 73
    println!(
94084087 Andy McCall ↶ 74
        "{} {}{}working copy {}{}{}",
75
        ui::dim("On"),
76
        ui::bookmark(&repo.config.bookmark),
77
        ui::sep(),
135212de Andy McCall ↶ 78
        ui::id(snap.wc.change_id.short(8)),
94084087 Andy McCall ↶ 79
        ui::sep(),
80
        ui::dim(plural(heads.len(), "head"))
135212de Andy McCall ↶ 81
    );
fce44ae9 Andy McCall ↶ 82
    if snap.statuses.is_empty() {
75167672 Andy McCall 83
        println!(
84
            "  {} {}",
85
            ui::ok(ui::glyph("✔", "*")),
86
            ui::dim("nothing to commit, working copy clean")
87
        );
94084087 Andy McCall ↶ 88
    } else {
89
        println!();
90
        for s in &snap.statuses {
75167672 Andy McCall 91
            println!(
92
                "  {} {}",
93
                ui::status_mark(status_tag(s.status)),
94
                ui::path(&s.path)
95
            );
94084087 Andy McCall ↶ 96
        }
fce44ae9 Andy McCall ↶ 97
    }
98
    if !snap.base_snapshot.is_conflicted() {
99
        return Ok(0);
100
    }
135212de Andy McCall ↶ 101
    println!();
75167672 Andy McCall 102
    println!(
103
        "{} {}",
104
        ui::section(ui::err("Conflicts")),
105
        ui::dim("edit the marked files, or the .oxy-conflict-N candidates, then commit")
106
    );
fce44ae9 Andy McCall ↶ 107
    for c in &snap.base_snapshot.tree.conflicts {
94084087 Andy McCall ↶ 108
        println!("  {} tree: {c:?}", ui::err(ui::glyph("✱", "!")));
fce44ae9 Andy McCall ↶ 109
    }
110
    for (p, f) in &snap.base_snapshot.files {
111
        if f.is_conflicted() {
75167672 Andy McCall 112
            let state = match snap
113
                .statuses
114
                .iter()
115
                .find(|s| s.path == *p)
116
                .map(|s| s.status)
117
            {
118
                Some(ChangeStatus::Resolved) => {
119
                    ui::ok(format!("{} resolved in working copy", ui::glyph("✔", "*")))
120
                }
121
                Some(ChangeStatus::ConflictEdited) => {
122
                    ui::warn(format!("{} markers remain", ui::glyph("‼", "!")))
123
                }
94084087 Andy McCall ↶ 124
                _ => ui::err(format!("{} unresolved", ui::glyph("✱", "!"))),
fce44ae9 Andy McCall ↶ 125
            };
135212de Andy McCall ↶ 126
            println!("  {}  {state}", ui::path(p));
fce44ae9 Andy McCall ↶ 127
        }
128
    }
129
    Ok(2)
130
}
131
75167672 Andy McCall 132
pub fn commit(
133
    message: &str,
134
    depends_on: &[String],
135
    paths: &[String],
136
    interactive: bool,
137
    hunks: &[usize],
138
) -> Result<i32> {
fce44ae9 Andy McCall ↶ 139
    let repo = open()?;
140
    let mut deps = Vec::new();
141
    for d in depends_on {
142
        deps.push(repo.resolve_change(d)?);
143
    }
c6aa5bd9 Andy McCall ↶ 144
    let selection = if !hunks.is_empty() {
145
        oxy_core::repo::Selection::Hunks(hunks.to_vec())
146
    } else if interactive {
957fee30 Andy McCall ↶ 147
        let (_, hunks) = repo.hunks()?;
148
        if hunks.is_empty() {
149
            anyhow::bail!("nothing to commit: the working copy matches its base");
150
        }
75167672 Andy McCall 151
        let hunks: Vec<_> = hunks
152
            .into_iter()
153
            .filter(|h| {
154
                paths.is_empty()
155
                    || paths.iter().any(|p| {
156
                        h.path == *p || h.path.starts_with(&format!("{}/", p.trim_end_matches('/')))
157
                    })
158
            })
159
            .collect();
957fee30 Andy McCall ↶ 160
        let mut chosen = Vec::new();
161
        let stdin = std::io::stdin();
162
        let mut take_rest = false;
163
        for (n, h) in hunks.iter().enumerate() {
164
            if take_rest {
165
                chosen.push(h.index);
166
                continue;
167
            }
75167672 Andy McCall 168
            println!(
169
                "{} {} {}",
170
                ui::section(format!("hunk {} of {}", n + 1, hunks.len())),
171
                ui::path(&h.path),
172
                ui::dim(format!("(#{})", h.index))
173
            );
957fee30 Andy McCall ↶ 174
            for line in h.text.lines() {
75167672 Andy McCall 175
                let styled = if line.starts_with('+') {
176
                    ui::ok(line)
177
                } else if line.starts_with('-') {
178
                    ui::err(line)
179
                } else {
180
                    ui::dim(line)
181
                };
957fee30 Andy McCall ↶ 182
                println!("  {styled}");
183
            }
184
            loop {
75167672 Andy McCall 185
                print!(
186
                    "{} ",
187
                    ui::warn("Commit this hunk? [y]es [n]o [a]ll remaining [q]uit:")
188
                );
957fee30 Andy McCall ↶ 189
                use std::io::Write as _;
190
                std::io::stdout().flush()?;
191
                let mut answer = String::new();
192
                if stdin.read_line(&mut answer)? == 0 {
193
                    anyhow::bail!("aborted");
194
                }
195
                match answer.trim() {
196
                    "y" | "Y" => {
197
                        chosen.push(h.index);
198
                        break;
199
                    }
200
                    "n" | "N" | "" => break,
201
                    "a" | "A" => {
202
                        chosen.push(h.index);
203
                        take_rest = true;
204
                        break;
205
                    }
206
                    "q" | "Q" => anyhow::bail!("aborted; nothing committed"),
207
                    _ => continue,
208
                }
209
            }
210
        }
211
        if chosen.is_empty() {
212
            anyhow::bail!("no hunks chosen; nothing committed");
213
        }
214
        oxy_core::repo::Selection::Hunks(chosen)
215
    } else if paths.is_empty() {
216
        oxy_core::repo::Selection::All
217
    } else {
218
        oxy_core::repo::Selection::Paths(paths.to_vec())
219
    };
135212de Andy McCall ↶ 220
    let sp = ui::spinner("Committing…");
957fee30 Andy McCall ↶ 221
    let h = repo.commit_selection(message, &deps, &selection)?;
fce44ae9 Andy McCall ↶ 222
    let c = repo.store().get_change(&h)?;
75167672 Andy McCall 223
    sp.done(&format!(
224
        "{} {} {}  {}",
225
        ui::done("Committed"),
226
        ui::id(short_id(&c)),
227
        ui::hash(format!("#{}", h.short(12))),
228
        ui::subject(subject_of(message))
229
    ));
957fee30 Andy McCall ↶ 230
    if !matches!(selection, oxy_core::repo::Selection::All) {
231
        let rest = repo.snapshot("oxy commit")?;
232
        if !rest.statuses.is_empty() {
75167672 Andy McCall 233
            println!(
234
                "  {} {}",
235
                ui::note(),
236
                ui::dim(format!(
237
                    "{} left uncommitted",
238
                    plural(rest.statuses.len(), "path")
239
                ))
240
            );
957fee30 Andy McCall ↶ 241
        }
242
    }
243
    Ok(0)
244
}
245
246
pub fn blame(path: &str, json: bool) -> Result<i32> {
247
    let repo = open()?;
248
    let lines = repo.blame(path)?;
249
    if json {
250
        let items = lines.iter().map(|l| {
251
            format!(
252
                "{{\"line\":{},\"change_id\":{},\"hash\":{},\"index\":{},\"author\":{},\"when_ms\":{}}}",
253
                l.line,
254
                oxy_core::repo::json_str(&l.change_id.to_hex()),
255
                oxy_core::repo::json_str(&l.hash.to_hex()),
256
                l.index,
257
                oxy_core::repo::json_str(&l.author),
258
                l.when_ms
259
            )
260
        });
261
        println!("{}", oxy_core::repo::json_array(items));
262
        return Ok(0);
263
    }
75167672 Andy McCall 264
    let width = lines
265
        .iter()
266
        .map(|l| l.author.chars().count())
267
        .max()
268
        .unwrap_or(0)
269
        .min(20);
957fee30 Andy McCall ↶ 270
    let digits = lines.len().to_string().len();
271
    for l in &lines {
272
        let author: String = l.author.chars().take(20).collect();
273
        let text = String::from_utf8_lossy(&l.text);
274
        println!(
275
            "{} {} {} {:>digits$}{} {}",
276
            ui::id(l.change_id.short(8)),
277
            ui::author(format!("{author:<width$}")),
278
            ui::dim(ui::ago(l.when_ms)),
279
            l.line,
280
            ui::dim(ui::glyph("│", "|")),
281
            text.trim_end_matches('\n')
282
        );
283
    }
284
    Ok(0)
285
}
286
287
fn bisect_report(repo: &Repo, step: &oxy_core::repo::BisectStep) -> Result<i32> {
288
    use oxy_core::repo::BisectStep::*;
289
    match step {
290
        NeedMarks { good, bad } => {
75167672 Andy McCall 291
            println!(
292
                "{} {} {}",
293
                ui::note(),
294
                ui::dim(format!("{good} good, {bad} bad;")),
295
                ui::dim(if *good == 0 {
296
                    "mark a known-good change or bookmark: oxy bisect good CHANGE"
297
                } else {
298
                    "mark a known-bad change or bookmark: oxy bisect bad CHANGE"
299
                })
300
            );
957fee30 Andy McCall ↶ 301
            Ok(0)
302
        }
75167672 Andy McCall 303
        Testing {
304
            heads,
305
            remaining,
306
            steps_left,
307
        } => {
308
            println!(
309
                "{} {} {}",
310
                ui::done("Testing"),
311
                ui::dim(format!(
312
                    "{} in the state under test;",
313
                    plural(heads.len(), "head")
314
                )),
315
                ui::dim(format!(
316
                    "{remaining} candidates left, about {steps_left} more steps"
317
                ))
318
            );
319
            println!(
320
                "  {} {}",
321
                ui::note(),
322
                ui::dim("run your test, then oxy bisect good | bad | skip")
323
            );
957fee30 Andy McCall ↶ 324
            Ok(0)
325
        }
326
        Found { culprit } => {
327
            let c = repo.store().get_change(culprit)?;
75167672 Andy McCall 328
            println!(
329
                "{} {} {}  {}",
330
                ui::done("Found"),
331
                ui::id(short_id(&c)),
332
                ui::hash(format!("#{}", culprit.short(12))),
333
                ui::subject(subject_of(&c.message))
334
            );
957fee30 Andy McCall ↶ 335
            println!("  {} {}", ui::note(), ui::dim("the first change whose inclusion makes the state bad; oxy bisect reset to return"));
336
            Ok(0)
337
        }
338
        Inconclusive { candidates } => {
75167672 Andy McCall 339
            println!(
340
                "{} {}",
341
                ui::caution(),
342
                ui::warn(format!(
343
                    "every remaining candidate was skipped ({}); oxy bisect reset to return",
344
                    plural(candidates.len(), "change")
345
                ))
346
            );
957fee30 Andy McCall ↶ 347
            Ok(1)
348
        }
349
    }
350
}
351
352
pub fn bisect_start() -> Result<i32> {
353
    let repo = open()?;
354
    repo.bisect_start()?;
75167672 Andy McCall 355
    println!(
356
        "{} bisect; {}",
357
        ui::done("Started"),
358
        ui::dim("now: oxy bisect good CHANGE and oxy bisect bad CHANGE")
359
    );
957fee30 Andy McCall ↶ 360
    Ok(0)
361
}
362
363
pub fn bisect_mark(good: Option<bool>, changes: &[String]) -> Result<i32> {
364
    let repo = open()?;
365
    let mut heads = Vec::new();
366
    for c in changes {
367
        heads.extend(repo.resolve_heads(c)?);
368
    }
369
    let step = repo.bisect_mark(good, &heads)?;
370
    bisect_report(&repo, &step)
371
}
372
373
pub fn bisect_run(command: &[String]) -> Result<i32> {
374
    let repo = open()?;
375
    let step = repo.bisect_run(command)?;
376
    bisect_report(&repo, &step)
377
}
378
c6aa5bd9 Andy McCall ↶ 379
pub fn bisect_status(as_json: bool) -> Result<i32> {
957fee30 Andy McCall ↶ 380
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 381
    if as_json {
382
        use oxy_core::repo::BisectStep::*;
383
        let v = match repo.bisect_status()? {
384
            None => "null".to_string(),
75167672 Andy McCall 385
            Some(NeedMarks { good, bad }) => json::obj([
386
                ("state", json::s("need-marks")),
387
                ("good", json::n(good)),
388
                ("bad", json::n(bad)),
389
            ]),
390
            Some(Testing {
391
                heads,
392
                remaining,
393
                steps_left,
394
            }) => json::obj([
395
                ("state", json::s("testing")),
396
                ("heads", json::hashes(&heads)),
397
                ("remaining", json::n(remaining)),
398
                ("steps_left", json::n(steps_left)),
399
            ]),
400
            Some(Found { culprit }) => json::obj([
401
                ("state", json::s("found")),
402
                ("culprit", json::s(&culprit.to_hex())),
403
            ]),
404
            Some(Inconclusive { candidates }) => json::obj([
405
                ("state", json::s("inconclusive")),
406
                ("candidates", json::hashes(&candidates)),
407
            ]),
c6aa5bd9 Andy McCall ↶ 408
        };
409
        println!("{v}");
410
        return Ok(0);
411
    }
957fee30 Andy McCall ↶ 412
    match repo.bisect_status()? {
413
        None => {
414
            println!("{}", ui::dim("No bisect in progress."));
415
            Ok(0)
416
        }
417
        Some(step) => bisect_report(&repo, &step),
418
    }
419
}
420
421
pub fn bisect_reset() -> Result<i32> {
422
    let repo = open()?;
423
    repo.bisect_reset()?;
424
    println!("{} bisect; working copy restored", ui::done("Reset"));
fce44ae9 Andy McCall ↶ 425
    Ok(0)
426
}
427
94084087 Andy McCall ↶ 428
/// The log: one entry per change, newest first, joined by a rail. The
429
/// default view is the subject and a metadata line; `verbose` adds the full
430
/// message, dependencies, and the authenticating key.
c6aa5bd9 Andy McCall ↶ 431
fn signature_json(repo: &Repo, h: &oxy_core::hash::ChangeHash) -> Result<String> {
432
    Ok(match repo.authenticate_change(h)? {
433
        SignatureStatus::Unsigned => json::obj([("status", json::s("unsigned"))]),
75167672 Andy McCall 434
        SignatureStatus::Valid {
435
            key,
436
            name,
437
            email,
438
            sealed,
439
            revoked,
440
        } => json::obj([
c6aa5bd9 Andy McCall ↶ 441
            ("status", json::s(if sealed { "sealed" } else { "signed" })),
442
            ("key", json::s(&key.to_hex())),
443
            ("name", json::s(&name)),
444
            ("email", json::s(&email)),
445
            ("revoked", json::b(revoked)),
446
        ]),
75167672 Andy McCall 447
        SignatureStatus::Invalid(why) => {
448
            json::obj([("status", json::s("invalid")), ("reason", json::s(&why))])
449
        }
c6aa5bd9 Andy McCall ↶ 450
    })
451
}
452
453
fn log_entry_json(repo: &Repo, e: &oxy_core::repo::LogEntry) -> Result<String> {
454
    let c = &e.change;
455
    Ok(json::obj([
456
        ("hash", json::s(&e.hash.to_hex())),
457
        ("change_id", json::s(&c.change_id.to_hex())),
458
        ("author", json::s(&author_name(repo, c))),
459
        ("author_key", json::s(&c.author.to_hex())),
460
        ("when_ms", json::n(c.hlc.wall_ms)),
461
        ("message", json::s(&c.message)),
462
        ("kind", json::s(&format!("{:?}", c.kind).to_lowercase())),
463
        ("deps", json::hashes(&c.deps)),
464
        ("head", json::b(e.is_head)),
465
        ("working_copy", json::b(e.is_working_copy)),
75167672 Andy McCall 466
        (
467
            "signature",
468
            if e.is_working_copy {
469
                "null".into()
470
            } else {
471
                signature_json(repo, &e.hash)?
472
            },
473
        ),
c6aa5bd9 Andy McCall ↶ 474
    ]))
475
}
476
477
pub fn log(limit: Option<usize>, verbose: bool, path: Option<&str>, as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 478
    let repo = open()?;
94084087 Andy McCall ↶ 479
    let snap = repo.snapshot("oxy log")?;
480
    let conflicted = snap.base_snapshot.is_conflicted();
c6aa5bd9 Andy McCall ↶ 481
    let entries = match path {
482
        Some(p) => repo.log_for_path(p)?,
483
        None => repo.log()?,
484
    };
485
    if as_json {
486
        let shown = limit.unwrap_or(entries.len()).min(entries.len());
487
        let mut items = Vec::new();
488
        for e in entries.iter().take(shown) {
489
            items.push(log_entry_json(&repo, e)?);
490
        }
75167672 Andy McCall 491
        println!(
492
            "{}",
493
            json::obj([
494
                ("bookmark", json::s(&repo.config.bookmark)),
495
                ("total", json::n(entries.len())),
496
                ("changes", json::arr(items))
497
            ])
498
        );
c6aa5bd9 Andy McCall ↶ 499
        return Ok(0);
500
    }
94084087 Andy McCall ↶ 501
    let total = entries.len();
502
    let shown = limit.unwrap_or(total).min(total);
503
    let rail = ui::rail();
504
    for (i, e) in entries.iter().take(shown).enumerate() {
fce44ae9 Andy McCall ↶ 505
        let c = &e.change;
75167672 Andy McCall 506
        let bullet = ui::log_bullet(
507
            e.is_working_copy,
508
            e.is_head,
509
            e.is_working_copy && conflicted,
510
        );
94084087 Andy McCall ↶ 511
        let mut labels = Vec::new();
fce44ae9 Andy McCall ↶ 512
        if e.is_working_copy {
94084087 Andy McCall ↶ 513
            labels.push(ui::warn("working copy"));
fce44ae9 Andy McCall ↶ 514
        }
94084087 Andy McCall ↶ 515
        if c.kind == ChangeKind::Resolution {
516
            labels.push(ui::warn("resolution"));
fce44ae9 Andy McCall ↶ 517
        }
75167672 Andy McCall 518
        let labels = if labels.is_empty() {
519
            String::new()
520
        } else {
521
            format!(
522
                " {}{}{}",
523
                ui::dim("("),
524
                labels.join(ui::dim(", ").as_str()),
525
                ui::dim(")")
526
            )
527
        };
94084087 Andy McCall ↶ 528
        let subject = if e.is_working_copy && c.message.is_empty() {
75167672 Andy McCall 529
            ui::dim(if snap.statuses.is_empty() {
530
                "(clean)"
531
            } else {
532
                "(uncommitted changes)"
533
            })
94084087 Andy McCall ↶ 534
        } else {
535
            ui::subject(subject_of(&c.message))
536
        };
537
        println!("{bullet} {}{labels}  {subject}", ui::id(short_meta_id(c)));
538
        let meta = format!(
539
            "{}{}{}{}{}{}{}",
540
            ui::hash(format!("#{}", e.hash.short(12))),
541
            ui::sep(),
542
            ui::author(author_name(&repo, c)),
543
            ui::sep(),
544
            ui::dim(ui::ago(c.hlc.wall_ms)),
545
            ui::sep(),
75167672 Andy McCall 546
            if e.is_working_copy {
547
                ui::dim("not yet committed")
548
            } else {
549
                signature_mark(&repo, &e.hash)?
550
            }
94084087 Andy McCall ↶ 551
        );
552
        println!("{rail} {meta}");
553
        if verbose {
554
            if !e.is_working_copy {
75167672 Andy McCall 555
                println!(
556
                    "{rail} {}",
557
                    ui::dim(format!(
558
                        "{} {}",
559
                        when(c.hlc.wall_ms),
560
                        signature_line(&repo, &e.hash)?
561
                    ))
562
                );
94084087 Andy McCall ↶ 563
            }
564
            if !c.deps.is_empty() {
75167672 Andy McCall 565
                println!(
566
                    "{rail} {} {}",
567
                    ui::dim(ui::glyph("↳", "->")),
568
                    ui::dim(deps_of(&c.deps))
569
                );
94084087 Andy McCall ↶ 570
            }
75167672 Andy McCall 571
            let body: Vec<&str> = c
572
                .message
573
                .lines()
574
                .skip(1)
575
                .skip_while(|l| l.trim().is_empty())
576
                .collect();
94084087 Andy McCall ↶ 577
            if !body.is_empty() {
578
                println!("{rail}");
579
                for line in body {
580
                    println!("{rail}   {line}");
581
                }
582
            }
fce44ae9 Andy McCall ↶ 583
        }
94084087 Andy McCall ↶ 584
        if i + 1 < shown {
585
            println!("{rail}");
fce44ae9 Andy McCall ↶ 586
        }
587
    }
94084087 Andy McCall ↶ 588
    if shown < total {
75167672 Andy McCall 589
        println!(
590
            "{}",
591
            ui::dim(format!(
592
                "{} {} more; pass -n to see them",
593
                ui::glyph("…", "..."),
594
                total - shown
595
            ))
596
        );
94084087 Andy McCall ↶ 597
    }
fce44ae9 Andy McCall ↶ 598
    Ok(0)
599
}
600
c6aa5bd9 Andy McCall ↶ 601
pub fn diff(change: Option<&str>, as_json: bool) -> Result<i32> {
602
    let repo = open()?;
603
    let hash = change.map(|c| repo.resolve_change(c)).transpose()?;
604
    if as_json {
605
        let files = repo.diff_files(hash.as_ref())?;
606
        let items = files.iter().map(|f| {
607
            json::obj([
608
                ("path", json::s(&f.path)),
609
                ("kind", json::s(&f.kind)),
610
                ("from", json::opt(f.from.as_deref(), json::s)),
611
                (
612
                    "hunks",
613
                    json::arr(f.hunks.iter().map(|h| {
614
                        json::obj([
615
                            ("base_line", json::n(h.base_line)),
75167672 Andy McCall 616
                            (
617
                                "added",
618
                                json::arr(
619
                                    h.added.iter().map(|l| json::s(&String::from_utf8_lossy(l))),
620
                                ),
621
                            ),
622
                            (
623
                                "removed",
624
                                json::arr(h.removed.iter().map(|(n, l)| {
625
                                    json::obj([
626
                                        ("line", json::n(*n)),
627
                                        ("text", json::s(&String::from_utf8_lossy(l))),
628
                                    ])
629
                                })),
630
                            ),
c6aa5bd9 Andy McCall ↶ 631
                        ])
632
                    })),
633
                ),
634
            ])
635
        });
75167672 Andy McCall 636
        println!(
637
            "{}",
638
            json::obj([
639
                ("change", json::opt(hash, |h| json::s(&h.to_hex()))),
640
                ("files", json::arr(items))
641
            ])
642
        );
c6aa5bd9 Andy McCall ↶ 643
        return Ok(0);
644
    }
645
    match hash {
646
        Some(h) => {
647
            let c = repo.store().get_change(&h)?;
648
            let base = repo.load_state(&c.deps)?;
649
            let snapshot = base.materialize();
650
            print!("{}", render_change(&c, &base, &snapshot));
651
        }
652
        None => {
653
            let snap = repo.snapshot("oxy diff")?;
75167672 Andy McCall 654
            print!(
655
                "{}",
656
                render_change(&snap.wc, &snap.base, &snap.base_snapshot)
657
            );
c6aa5bd9 Andy McCall ↶ 658
        }
659
    }
660
    Ok(0)
661
}
662
663
pub fn cat(path: &str, change: Option<&str>) -> Result<i32> {
664
    let repo = open()?;
665
    let heads = change.map(|c| repo.resolve_heads(c)).transpose()?;
666
    let bytes = repo.file_at(path, heads.as_deref())?;
667
    use std::io::Write as _;
668
    std::io::stdout().write_all(&bytes)?;
669
    Ok(0)
670
}
671
672
pub fn root(as_json: bool) -> Result<i32> {
673
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
674
        if as_json {
675
            println!("null");
676
        }
677
        return Ok(1);
678
    };
679
    if as_json {
75167672 Andy McCall 680
        println!(
681
            "{}",
682
            json::obj([
683
                ("root", json::s(&repo.root().to_string_lossy())),
684
                ("workspace", json::s(&repo.workspace().to_hex())),
685
                ("bookmark", json::s(&repo.config.bookmark))
686
            ])
687
        );
c6aa5bd9 Andy McCall ↶ 688
    } else {
689
        println!("{}", repo.root().display());
690
    }
691
    Ok(0)
692
}
693
694
pub fn version(as_json: bool) -> Result<i32> {
695
    if as_json {
75167672 Andy McCall 696
        println!(
697
            "{}",
698
            json::obj([
699
                ("version", json::s(env!("CARGO_PKG_VERSION"))),
700
                ("protocol", json::n(oxy_core::protocol::PROTOCOL_VERSION)),
701
                ("format", json::n(2))
702
            ])
703
        );
c6aa5bd9 Andy McCall ↶ 704
    } else {
75167672 Andy McCall 705
        println!(
706
            "oxy {} (repository format 2, protocol {})",
707
            env!("CARGO_PKG_VERSION"),
708
            oxy_core::protocol::PROTOCOL_VERSION
709
        );
c6aa5bd9 Andy McCall ↶ 710
    }
711
    Ok(0)
712
}
713
714
pub fn discard(paths: &[String], hunks: &[usize]) -> Result<i32> {
715
    let repo = open()?;
716
    if paths.is_empty() && hunks.is_empty() {
717
        anyhow::bail!("name paths to restore, or --hunks to undo chosen hunks");
718
    }
719
    let mut n = 0;
720
    if !hunks.is_empty() {
721
        n += repo.discard_hunks(hunks)?;
722
    }
723
    if !paths.is_empty() {
724
        n += repo.discard(paths)?;
725
    }
75167672 Andy McCall 726
    println!(
727
        "{} {} restored to the working copy's base",
728
        ui::done("Discarded"),
729
        plural(n, "path")
730
    );
c6aa5bd9 Andy McCall ↶ 731
    Ok(0)
732
}
733
734
pub fn hunks(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 735
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 736
    let (_, hunks) = repo.hunks()?;
737
    if as_json {
75167672 Andy McCall 738
        println!(
739
            "{}",
740
            json::arr(hunks.iter().map(|h| json::obj([
741
                ("index", json::n(h.index)),
742
                ("path", json::s(&h.path)),
743
                ("text", json::s(&h.text))
744
            ])))
745
        );
c6aa5bd9 Andy McCall ↶ 746
        return Ok(0);
747
    }
748
    if hunks.is_empty() {
75167672 Andy McCall 749
        println!(
750
            "{}",
751
            ui::dim("No hunks: the working copy matches its base.")
752
        );
c6aa5bd9 Andy McCall ↶ 753
    }
754
    for h in &hunks {
75167672 Andy McCall 755
        println!(
756
            "{} {}",
757
            ui::section(format!("hunk {}", h.index)),
758
            ui::path(&h.path)
759
        );
c6aa5bd9 Andy McCall ↶ 760
        for line in h.text.lines() {
75167672 Andy McCall 761
            let styled = if line.starts_with('+') {
762
                ui::ok(line)
763
            } else if line.starts_with('-') {
764
                ui::err(line)
765
            } else {
766
                ui::dim(line)
767
            };
c6aa5bd9 Andy McCall ↶ 768
            println!("  {styled}");
769
        }
770
    }
fce44ae9 Andy McCall ↶ 771
    Ok(0)
772
}
773
c6aa5bd9 Andy McCall ↶ 774
pub fn show(change: &str, as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 775
    let repo = open()?;
776
    repo.snapshot("oxy show")?;
777
    let h = repo.resolve_change(change)?;
778
    let c = repo.store().get_change(&h)?;
c6aa5bd9 Andy McCall ↶ 779
    if as_json {
780
        let files = repo.diff_files(Some(&h))?;
781
        let heads = repo.bookmark_heads()?;
75167672 Andy McCall 782
        let entry = oxy_core::repo::LogEntry {
783
            hash: h,
784
            change: oxy_core::state::ChangeMeta::of(&c),
785
            is_working_copy: c.kind == oxy_core::objects::ChangeKind::WorkingCopy,
786
            is_head: heads.contains(&h),
787
        };
c6aa5bd9 Andy McCall ↶ 788
        let mut body = log_entry_json(&repo, &entry)?;
789
        body.pop();
75167672 Andy McCall 790
        body.push_str(&format!(
791
            ",{}:{}}}",
792
            json::s("files"),
793
            json::arr(files.iter().map(|f| json::obj([
794
                ("path", json::s(&f.path)),
795
                ("kind", json::s(&f.kind)),
796
                ("from", json::opt(f.from.as_deref(), json::s))
797
            ])))
798
        ));
c6aa5bd9 Andy McCall ↶ 799
        println!("{body}");
800
        return Ok(0);
801
    }
75167672 Andy McCall 802
    println!(
803
        "{} {} {}",
804
        ui::section("change"),
805
        ui::id(short_id(&c)),
806
        ui::hash(format!("#{h}"))
807
    );
94084087 Andy McCall ↶ 808
    println!("{}", ui::kv("kind", format!("{:?}", c.kind).to_lowercase()));
75167672 Andy McCall 809
    println!(
810
        "{}",
811
        ui::kv(
812
            "author",
813
            ui::author(author_name(&repo, &oxy_core::state::ChangeMeta::of(&c)))
814
        )
815
    );
816
    println!(
817
        "{}",
818
        ui::kv(
819
            "date",
820
            format!(
821
                "{} {}",
822
                when(c.hlc.wall_ms),
823
                ui::dim(format!("({})", ui::ago(c.hlc.wall_ms)))
824
            )
825
        )
826
    );
94084087 Andy McCall ↶ 827
    println!("{}", ui::kv("deps", ui::dim(deps_line(&c))));
828
    println!("{}", ui::kv("sig", signature_line(&repo, &h)?));
829
    println!();
75167672 Andy McCall 830
    for line in (if c.message.is_empty() {
831
        "(no description)"
832
    } else {
833
        &c.message
834
    })
835
    .lines()
836
    {
94084087 Andy McCall ↶ 837
        println!("    {line}");
838
    }
839
    println!();
fce44ae9 Andy McCall ↶ 840
    print!("{}", repo.describe_change(&h)?);
841
    Ok(0)
842
}
843
844
pub fn checkout(changes: &[String], discard: bool) -> Result<i32> {
845
    let repo = open()?;
846
    let heads = if changes.is_empty() {
847
        repo.bookmark_heads()?
848
    } else {
132b884b Andy McCall ↶ 849
        let mut heads = Vec::new();
850
        for c in changes {
851
            heads.extend(repo.resolve_heads(c)?);
852
        }
853
        heads
fce44ae9 Andy McCall ↶ 854
    };
75167672 Andy McCall 855
    let spec = if changes.is_empty() {
856
        repo.config.bookmark.clone()
857
    } else {
858
        changes.join(" ")
859
    };
135212de Andy McCall ↶ 860
    let sp = ui::spinner(&format!("Checking out {spec}…"));
fce44ae9 Andy McCall ↶ 861
    let r = repo.checkout(&heads, discard, &format!("oxy checkout {spec}"))?;
75167672 Andy McCall 862
    sp.done(&format!(
863
        "{} on {}: {} written, {} removed",
864
        ui::done("Working copy"),
865
        ui::bookmark(&spec),
866
        plural(r.written, "file"),
867
        r.removed
868
    ));
4dee277c Andy McCall ↶ 869
    for n in &r.notes {
870
        println!("  {} {n}", ui::note());
871
    }
fce44ae9 Andy McCall ↶ 872
    if r.conflicted {
75167672 Andy McCall 873
        println!(
874
            "  {} {}",
875
            ui::caution(),
876
            ui::warn("this state has conflicts; see oxy status")
877
        );
fce44ae9 Andy McCall ↶ 878
    }
879
    Ok(0)
880
}
881
c6aa5bd9 Andy McCall ↶ 882
pub fn resolve(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 883
    let repo = open()?;
884
    let snap = repo.snapshot("oxy resolve")?;
c6aa5bd9 Andy McCall ↶ 885
    if as_json {
886
        println!("{}", repo.status_json(&snap)?);
75167672 Andy McCall 887
        return Ok(if snap.base_snapshot.is_conflicted() {
888
            2
889
        } else {
890
            0
891
        });
c6aa5bd9 Andy McCall ↶ 892
    }
fce44ae9 Andy McCall ↶ 893
    if !snap.base_snapshot.is_conflicted() {
894
        println!("The working copy's base has no conflicts.");
895
        return Ok(0);
896
    }
897
    let mut remaining = 0;
898
    for (p, f) in &snap.base_snapshot.files {
899
        if !f.is_conflicted() {
900
            continue;
901
        }
75167672 Andy McCall 902
        match snap
903
            .statuses
904
            .iter()
905
            .find(|s| s.path == *p)
906
            .map(|s| s.status)
907
        {
fce44ae9 Andy McCall ↶ 908
            Some(ChangeStatus::Resolved) => println!("resolved   {p}"),
909
            Some(ChangeStatus::ConflictEdited) => {
910
                remaining += 1;
911
                println!("markers    {p}");
912
            }
913
            _ => {
914
                remaining += 1;
915
                println!("unresolved {p}");
916
            }
917
        }
918
    }
919
    for c in &snap.base_snapshot.tree.conflicts {
920
        remaining += 1;
921
        println!("tree       {c:?}");
922
    }
923
    if remaining == 0 {
924
        println!("All conflicts are resolved; `oxy commit` will record the resolution.");
925
        Ok(0)
926
    } else {
927
        Ok(2)
928
    }
929
}
930
931
pub fn undo() -> Result<i32> {
932
    let repo = open()?;
933
    let op = repo.undo()?;
94084087 Andy McCall ↶ 934
    println!("{} now at: {}", ui::done("Undone;"), ui::dim(&op.command));
fce44ae9 Andy McCall ↶ 935
    Ok(0)
936
}
937
c6aa5bd9 Andy McCall ↶ 938
pub fn op_log(as_json: bool) -> Result<i32> {
fce44ae9 Andy McCall ↶ 939
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 940
    if as_json {
941
        let ops = repo.op_log()?;
942
        println!(
943
            "{}",
944
            json::arr(ops.iter().enumerate().map(|(i, (r, op))| {
945
                json::obj([
946
                    ("id", json::s(&r.to_hex())),
947
                    ("when_ms", json::n(op.hlc.wall_ms)),
948
                    ("command", json::s(&op.command)),
949
                    ("snapshot", json::b(op.command.ends_with("(snapshot)"))),
950
                    ("current", json::b(i == 0)),
951
                ])
952
            }))
953
        );
954
        return Ok(0);
955
    }
fce44ae9 Andy McCall ↶ 956
    for (i, (r, op)) in repo.op_log()?.into_iter().enumerate() {
75167672 Andy McCall 957
        let bullet = if i == 0 {
958
            ui::ok(ui::glyph("●", "@"))
959
        } else {
960
            ui::dim(ui::glyph("○", "o"))
961
        };
94084087 Andy McCall ↶ 962
        let cmd = subject_of(&op.command).split("\\n").next().unwrap_or("");
75167672 Andy McCall 963
        println!(
964
            "{bullet} {}{}{}  {}",
965
            ui::hash(r.short(12)),
966
            ui::sep(),
967
            ui::dim(format!("{:<16}", ui::ago(op.hlc.wall_ms))),
968
            if i == 0 {
969
                ui::subject(cmd)
970
            } else {
971
                cmd.to_string()
972
            }
973
        );
fce44ae9 Andy McCall ↶ 974
    }
975
    Ok(0)
976
}
d02e545d Andy McCall ↶ 977
ba160f60 Andy McCall ↶ 978
pub fn gc(now: bool) -> Result<i32> {
d02e545d Andy McCall ↶ 979
    let repo = open()?;
135212de Andy McCall ↶ 980
    let sp = ui::spinner("Packing and pruning…");
ba160f60 Andy McCall ↶ 981
    let r = repo.gc(now)?;
135212de Andy McCall ↶ 982
    sp.clear();
ba160f60 Andy McCall ↶ 983
    if r.packed.objects > 0 {
d02e545d Andy McCall ↶ 984
        println!(
ba160f60 Andy McCall ↶ 985
            "Packed {}: {} bytes -> {} bytes ({:.0}%).",
986
            plural(r.packed.objects, "loose object"),
987
            r.packed.raw_bytes,
988
            r.packed.packed_bytes,
989
            100.0 * r.packed.packed_bytes as f64 / r.packed.raw_bytes.max(1) as f64
d02e545d Andy McCall ↶ 990
        );
991
    }
75167672 Andy McCall 992
    println!(
993
        "{} reachable; pruned {} ({} bytes){}{}; {} present.",
ba160f60 Andy McCall ↶ 994
        plural(r.reachable, "object"),
995
        plural(r.pruned.objects, "unreachable object"),
996
        r.pruned.bytes,
75167672 Andy McCall 997
        if r.pruned.deferred > 0 {
998
            format!(
999
                "; {} deferred by the grace period (use --now)",
1000
                plural(r.pruned.deferred, "object")
1001
            )
1002
        } else {
1003
            String::new()
1004
        },
1005
        if r.merged_packs > 0 {
1006
            format!("; merged {} into one", plural(r.merged_packs, "pack"))
1007
        } else {
1008
            String::new()
1009
        },
ba160f60 Andy McCall ↶ 1010
        plural(repo.store().pack_count(), "pack")
1011
    );
d02e545d Andy McCall ↶ 1012
    Ok(0)
1013
}
614541c3 Andy McCall ↶ 1014
79d03f82 Andy McCall ↶ 1015
/// The head the working copy sits on, for commands that default to it. With
1016
/// several heads beneath the working copy, the most recently made one is
1017
/// chosen and announced.
614541c3 Andy McCall ↶ 1018
fn current_head(repo: &Repo) -> Result<oxy_core::hash::ChangeHash> {
1019
    let snap = repo.snapshot("oxy")?;
1020
    let base = snap.base.maximal(&snap.wc.deps);
1021
    match base.as_slice() {
79d03f82 Andy McCall ↶ 1022
        [] => anyhow::bail!("the working copy sits on no change yet"),
614541c3 Andy McCall ↶ 1023
        [h] => Ok(*h),
79d03f82 Andy McCall ↶ 1024
        many => {
1025
            let latest = many
1026
                .iter()
1027
                .max_by_key(|h| snap.base.get(h).map(|c| (c.hlc, **h)))
1028
                .copied()
1029
                .unwrap();
1030
            let c = repo.store().get_change(&latest)?;
75167672 Andy McCall 1031
            println!(
1032
                "Defaulting to {} #{} (most recent of the {} heads under the working copy)",
1033
                short_id(&c),
1034
                latest.short(12),
1035
                many.len()
1036
            );
79d03f82 Andy McCall ↶ 1037
            Ok(latest)
1038
        }
614541c3 Andy McCall ↶ 1039
    }
1040
}
1041
1042
pub fn describe(message: &str, change: Option<&str>) -> Result<i32> {
1043
    let repo = open()?;
1044
    let h = match change {
1045
        Some(c) => repo.resolve_change(c)?,
1046
        None => current_head(&repo)?,
1047
    };
1048
    let new = repo.describe(&h, message)?;
1049
    let c = repo.store().get_change(&new)?;
75167672 Andy McCall 1050
    println!(
1051
        "{} {} {}  {}",
1052
        ui::done("Described"),
1053
        ui::id(short_id(&c)),
1054
        ui::hash(format!("#{}", new.short(12))),
1055
        ui::subject(subject_of(message))
1056
    );
614541c3 Andy McCall ↶ 1057
    Ok(0)
1058
}
1059
23b217d7 Andy McCall ↶ 1060
pub fn amend(message: Option<&str>, into: Option<&str>) -> Result<i32> {
614541c3 Andy McCall ↶ 1061
    let repo = open()?;
23b217d7 Andy McCall ↶ 1062
    let new = match into {
1063
        Some(spec) => {
1064
            let target = repo.resolve_change(spec)?;
1065
            repo.amend_into(&target, message)?
1066
        }
1067
        None => repo.amend(message)?,
1068
    };
614541c3 Andy McCall ↶ 1069
    let c = repo.store().get_change(&new)?;
75167672 Andy McCall 1070
    println!(
1071
        "{} {} {}  {}",
1072
        ui::done("Amended"),
1073
        ui::id(short_id(&c)),
1074
        ui::hash(format!("#{}", new.short(12))),
1075
        ui::subject(subject_of(&c.message))
1076
    );
614541c3 Andy McCall ↶ 1077
    Ok(0)
1078
}
1079
1080
pub fn abandon(change: &str) -> Result<i32> {
1081
    let repo = open()?;
1082
    let h = repo.resolve_change(change)?;
1083
    let c = repo.store().get_change(&h)?;
6706bdcf Andy McCall ↶ 1084
    let notes = repo.abandon(&h)?;
75167672 Andy McCall 1085
    println!(
1086
        "{} {} {}  {}",
1087
        ui::done("Abandoned"),
1088
        ui::id(short_id(&c)),
1089
        ui::hash(format!("#{}", h.short(12))),
1090
        ui::dim("its content remains on disk as uncommitted work if the working copy sat on it")
1091
    );
6706bdcf Andy McCall ↶ 1092
    for n in notes {
94084087 Andy McCall ↶ 1093
        println!("  {} {n}", ui::note());
6706bdcf Andy McCall ↶ 1094
    }
614541c3 Andy McCall ↶ 1095
    Ok(0)
1096
}
252e8cb2 Andy McCall ↶ 1097
1098
pub fn checkpoint() -> Result<i32> {
1099
    let repo = open()?;
135212de Andy McCall ↶ 1100
    let sp = ui::spinner("Writing checkpoint…");
252e8cb2 Andy McCall ↶ 1101
    let (r, changes, bytes) = repo.checkpoint()?;
75167672 Andy McCall 1102
    sp.done(&format!(
1103
        "{} {} of {} ({} bytes) for {}",
1104
        ui::done("Checkpoint"),
1105
        ui::hash(format!("#{}", r.short(12))),
1106
        plural(changes, "change"),
1107
        bytes,
1108
        ui::id(&repo.config.bookmark)
1109
    ));
135212de Andy McCall ↶ 1110
    Ok(0)
1111
}
1112
1113
/// For shell prompts: silent (exit 1) outside a repository, otherwise one line.
694805cc Andy McCall ↶ 1114
pub fn prompt(format: &str, glyphs: bool, color: Option<&str>) -> Result<i32> {
75167672 Andy McCall 1115
    let Ok(repo) = Repo::open(&std::env::current_dir()?) else {
1116
        return Ok(1);
1117
    };
135212de Andy McCall ↶ 1118
    let info = repo.quick_status()?;
75167672 Andy McCall 1119
    let fmt = if glyphs && format == oxy_core::repo::DEFAULT_PROMPT_FORMAT {
1120
        oxy_core::repo::GLYPH_PROMPT_FORMAT
1121
    } else {
1122
        format
1123
    };
694805cc Andy McCall ↶ 1124
    let line = match color {
1125
        Some("bash") => info.format_colored(fmt, ("\\[", "\\]")),
1126
        Some("zsh") => info.format_colored(fmt, ("%{", "%}")),
1127
        Some(_) => info.format_colored(fmt, ("", "")),
1128
        None => info.format(fmt),
1129
    };
1130
    println!("{line}");
252e8cb2 Andy McCall ↶ 1131
    Ok(0)
1132
}
7421309f Andy McCall ↶ 1133
1134
pub fn sparse(paths: &[String]) -> Result<i32> {
1135
    let mut repo = open()?;
1136
    if paths.is_empty() {
1137
        if repo.config.sparse_paths.is_empty() {
1138
            println!("No sparse filter: the whole tree is materialized.");
1139
        } else {
1140
            println!("{}", ui::heading("Sparse filter"));
1141
            for p in &repo.config.sparse_paths {
1142
                println!("  {}", ui::path(p));
1143
            }
1144
        }
1145
        return Ok(0);
1146
    }
1147
    let snap = repo.snapshot("oxy sparse")?;
1148
    if !snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty() {
75167672 Andy McCall 1149
        anyhow::bail!(
1150
            "the working copy has changes; commit them before changing the sparse filter"
1151
        );
7421309f Andy McCall ↶ 1152
    }
1153
    repo.config.set("filter.paths", &paths.join(","))?;
1154
    repo.save_config()?;
1155
    let heads = repo.bookmark_heads()?;
1156
    let sp = ui::spinner("Re-checking out with the new filter…");
1157
    let r = repo.checkout(&heads, true, "oxy sparse (checkout)")?;
75167672 Andy McCall 1158
    sp.done(&format!(
1159
        "{} {}: {} written, {} removed",
1160
        ui::ok("Sparse filter set to"),
1161
        ui::path(paths.join(",")),
1162
        plural(r.written, "file"),
1163
        r.removed
1164
    ));
7421309f Andy McCall ↶ 1165
    Ok(0)
1166
}
132b884b Andy McCall ↶ 1167
1168
pub fn tag_create(name: &str, changes: &[String], message: &str) -> Result<i32> {
1169
    let repo = open()?;
1170
    repo.snapshot("oxy tag")?;
1171
    let heads = if changes.is_empty() {
1172
        repo.bookmark_heads()?
1173
    } else {
1174
        let mut heads = Vec::new();
1175
        for c in changes {
1176
            heads.extend(repo.resolve_heads(c)?);
1177
        }
1178
        heads
1179
    };
1180
    let t = repo.tag_create(name, &heads, message)?;
1181
    println!(
94084087 Andy McCall ↶ 1182
        "{} {} {} {} ({}){}",
1183
        ui::done("Tagged"),
1184
        ui::bookmark(&t.name),
1185
        ui::dim(ui::glyph("→", "->")),
132b884b Andy McCall ↶ 1186
        ui::hash(format!("#{}", t.state.short(12))),
1187
        plural(t.heads.len(), "head"),
75167672 Andy McCall 1188
        t.signer
1189
            .map(|s| format!(", signed by {s}"))
1190
            .unwrap_or_else(|| ui::dim(", unsigned"))
132b884b Andy McCall ↶ 1191
    );
1192
    Ok(0)
1193
}
1194
1196b29b Andy McCall ↶ 1195
pub fn tag_list(as_json: bool) -> Result<i32> {
132b884b Andy McCall ↶ 1196
    let repo = open()?;
1197
    let tags = repo.tags()?;
1196b29b Andy McCall ↶ 1198
    if as_json {
1199
        println!(
1200
            "{}",
1201
            json::arr(tags.iter().map(|t| {
1202
                json::obj([
1203
                    ("name", json::s(&t.name)),
1204
                    ("state", json::s(&t.state.to_hex())),
1205
                    ("heads", json::hashes(&t.heads)),
1206
                    ("message", json::s(&t.message)),
75167672 Andy McCall 1207
                    (
1208
                        "signer",
1209
                        json::opt(t.signer.as_ref(), |s| json::s(&s.to_string())),
1210
                    ),
1196b29b Andy McCall ↶ 1211
                ])
1212
            }))
1213
        );
1214
        return Ok(0);
1215
    }
132b884b Andy McCall ↶ 1216
    if tags.is_empty() {
1217
        println!("{}", ui::dim("No tags."));
1218
    }
1219
    for t in tags {
1220
        println!(
94084087 Andy McCall ↶ 1221
            "{} {} {}{}{}{}",
1222
            ui::ok(ui::glyph("⚑", "#")),
1223
            ui::bookmark(&t.name),
132b884b Andy McCall ↶ 1224
            ui::hash(format!("#{}", t.state.short(12))),
94084087 Andy McCall ↶ 1225
            ui::sep() + &ui::dim(plural(t.heads.len(), "head")),
75167672 Andy McCall 1226
            if t.message.is_empty() {
1227
                String::new()
1228
            } else {
1229
                format!("  {}", ui::subject(subject_of(&t.message)))
1230
            },
1231
            t.signer
1232
                .map(|s| ui::sep() + &ui::ok(format!("{} {s}", ui::glyph("✔", "v"))))
1233
                .unwrap_or_default()
132b884b Andy McCall ↶ 1234
        );
1235
    }
1236
    Ok(0)
1237
}
4e88e774 Andy McCall ↶ 1238
1239
pub fn workspace_add(path: &std::path::Path, changes: &[String]) -> Result<i32> {
1240
    let repo = open()?;
1241
    let heads = if changes.is_empty() {
1242
        None
1243
    } else {
1244
        let mut heads = Vec::new();
1245
        for c in changes {
1246
            heads.extend(repo.resolve_heads(c)?);
1247
        }
1248
        Some(heads)
1249
    };
1250
    let sp = ui::spinner(&format!("Creating workspace at {}…", path.display()));
1251
    let ws = repo.workspace_add(path, heads.as_deref())?;
75167672 Andy McCall 1252
    sp.done(&format!(
1253
        "{} {} (workspace {})",
1254
        ui::done("Workspace created at"),
1255
        ui::path(ws.root().display()),
1256
        ui::id(ws.workspace().short(8))
1257
    ));
4e88e774 Andy McCall ↶ 1258
    Ok(0)
1259
}
1260
1196b29b Andy McCall ↶ 1261
pub fn workspace_list(as_json: bool) -> Result<i32> {
4e88e774 Andy McCall ↶ 1262
    let repo = open()?;
1196b29b Andy McCall ↶ 1263
    if as_json {
1264
        println!(
1265
            "{}",
1266
            json::arr(repo.workspaces()?.iter().map(|w| {
1267
                json::obj([
1268
                    ("id", json::s(&w.id.to_hex())),
1269
                    ("path", json::s(&w.path.to_string_lossy())),
1270
                    ("current", json::b(w.current)),
75167672 Andy McCall 1271
                    (
1272
                        "working_copy",
1273
                        json::opt(w.working_copy, |h| json::s(&h.to_hex())),
1274
                    ),
1196b29b Andy McCall ↶ 1275
                ])
1276
            }))
1277
        );
1278
        return Ok(0);
1279
    }
4e88e774 Andy McCall ↶ 1280
    for w in repo.workspaces()? {
1281
        println!(
1282
            "{} {} {}{}",
75167672 Andy McCall 1283
            if w.current {
1284
                ui::ok(ui::glyph("●", "*"))
1285
            } else {
1286
                ui::dim(ui::glyph("○", "o"))
1287
            },
4e88e774 Andy McCall ↶ 1288
            ui::id(w.id.short(8)),
1289
            ui::path(w.path.display()),
75167672 Andy McCall 1290
            w.working_copy
1291
                .map(|h| ui::sep() + &ui::dim(format!("working copy #{}", h.short(12))))
1292
                .unwrap_or_else(|| ui::sep() + &ui::warn("not in view"))
4e88e774 Andy McCall ↶ 1293
        );
1294
    }
1295
    Ok(0)
1296
}
1297
1298
pub fn workspace_forget(spec: &str) -> Result<i32> {
1299
    let repo = open()?;
1300
    let all = repo.workspaces()?;
1301
    let target = std::fs::canonicalize(spec).ok();
75167672 Andy McCall 1302
    let matches: Vec<_> = all
1303
        .iter()
1304
        .filter(|w| w.id.starts_with_hex(spec) || target.as_ref().is_some_and(|t| *t == w.path))
1305
        .collect();
4e88e774 Andy McCall ↶ 1306
    let w = match matches.as_slice() {
1307
        [w] => *w,
1308
        [] => anyhow::bail!("no workspace matches {spec:?}"),
1309
        _ => anyhow::bail!("{spec:?} is ambiguous"),
1310
    };
1311
    repo.workspace_forget(&w.id)?;
75167672 Andy McCall 1312
    println!(
1313
        "{} workspace {} at {}; its files were left in place.",
1314
        ui::done("Forgot"),
1315
        ui::id(w.id.short(8)),
1316
        ui::path(w.path.display())
1317
    );
4e88e774 Andy McCall ↶ 1318
    Ok(0)
1319
}
cdb5beba Andy McCall ↶ 1320
1321
pub fn lock(path: &str) -> Result<i32> {
1322
    let repo = open()?;
1323
    repo.lock_path(path)?;
75167672 Andy McCall 1324
    println!(
1325
        "{} {} {}",
1326
        ui::done("Locked"),
1327
        ui::path(path),
1328
        ui::dim("(advisory, local)")
1329
    );
cdb5beba Andy McCall ↶ 1330
    Ok(0)
1331
}
1332
1333
pub fn unlock(path: &str) -> Result<i32> {
1334
    let repo = open()?;
1335
    repo.unlock_path(path)?;
94084087 Andy McCall ↶ 1336
    println!("{} {}", ui::done("Unlocked"), ui::path(path));
cdb5beba Andy McCall ↶ 1337
    Ok(0)
1338
}
23b217d7 Andy McCall ↶ 1339
1340
pub fn split(change: &str, paths: &[String]) -> Result<i32> {
1341
    let repo = open()?;
1342
    let h = repo.resolve_change(change)?;
1343
    let (h1, h2) = repo.split(&h, paths)?;
1344
    let c1 = repo.store().get_change(&h1)?;
1345
    let c2 = repo.store().get_change(&h2)?;
75167672 Andy McCall 1346
    println!(
1347
        "{} into {} {} and {} {}",
1348
        ui::done("Split"),
1349
        ui::id(short_id(&c1)),
1350
        ui::hash(format!("#{}", h1.short(12))),
1351
        ui::id(short_id(&c2)),
1352
        ui::hash(format!("#{}", h2.short(12)))
1353
    );
23b217d7 Andy McCall ↶ 1354
    Ok(0)
1355
}
7b9809e6 Andy McCall ↶ 1356
1357
fn heads_from(repo: &Repo, changes: &[String]) -> Result<Vec<oxy_core::hash::ChangeHash>> {
1358
    let mut heads = Vec::new();
1359
    for c in changes {
1360
        heads.extend(repo.resolve_heads(c)?);
1361
    }
1362
    Ok(heads)
1363
}
1364
1365
pub fn bookmark_create(name: &str, changes: &[String]) -> Result<i32> {
1366
    let repo = open()?;
1367
    repo.snapshot("oxy bookmark create")?;
75167672 Andy McCall 1368
    let heads = if changes.is_empty() {
1369
        None
1370
    } else {
1371
        Some(heads_from(&repo, changes)?)
1372
    };
7b9809e6 Andy McCall ↶ 1373
    let heads = repo.bookmark_create(name, heads.as_deref())?;
75167672 Andy McCall 1374
    println!(
1375
        "{} bookmark {} {} {}",
1376
        ui::done("Created"),
1377
        ui::bookmark(name),
1378
        ui::dim(ui::glyph("→", "->")),
1379
        ui::dim(plural(heads.len(), "head"))
1380
    );
1381
    println!(
1382
        "  {} {}",
1383
        ui::note(),
1384
        ui::dim(format!("switch to it with oxy bookmark switch {name}"))
1385
    );
7b9809e6 Andy McCall ↶ 1386
    Ok(0)
1387
}
1388
1389
pub fn bookmark_set(name: &str, changes: &[String]) -> Result<i32> {
1390
    let repo = open()?;
1391
    repo.snapshot("oxy bookmark set")?;
1392
    let heads = heads_from(&repo, changes)?;
1393
    let heads = repo.bookmark_set(name, &heads)?;
75167672 Andy McCall 1394
    println!(
1395
        "{} bookmark {} {} {}",
1396
        ui::done("Moved"),
1397
        ui::bookmark(name),
1398
        ui::dim(ui::glyph("→", "->")),
1399
        ui::dim(plural(heads.len(), "head"))
1400
    );
7b9809e6 Andy McCall ↶ 1401
    Ok(0)
1402
}
1403
1404
pub fn bookmark_delete(name: &str) -> Result<i32> {
1405
    let repo = open()?;
1406
    repo.bookmark_delete(name)?;
75167672 Andy McCall 1407
    println!(
1408
        "{} bookmark {} {}",
1409
        ui::done("Deleted"),
1410
        ui::bookmark(name),
1411
        ui::dim("(its changes stay until unreachable)")
1412
    );
7b9809e6 Andy McCall ↶ 1413
    Ok(0)
1414
}
1415
c6aa5bd9 Andy McCall ↶ 1416
pub fn bookmark_list(as_json: bool) -> Result<i32> {
7b9809e6 Andy McCall ↶ 1417
    let repo = open()?;
c6aa5bd9 Andy McCall ↶ 1418
    if as_json {
1419
        let items = repo.bookmarks()?.into_iter().map(|b| {
1420
            json::obj([
1421
                ("name", json::s(&b.name)),
1422
                ("heads", json::hashes(&b.heads)),
1423
                ("current", json::b(b.current)),
1424
                ("ahead", json::opt(b.ahead, json::n)),
1425
                ("behind", json::opt(b.behind, json::n)),
1426
            ])
1427
        });
1428
        println!("{}", json::arr(items));
1429
        return Ok(0);
1430
    }
7b9809e6 Andy McCall ↶ 1431
    for b in repo.bookmarks()? {
75167672 Andy McCall 1432
        let mark = if b.current {
1433
            ui::ok(ui::glyph("●", "*"))
1434
        } else {
1435
            ui::dim(ui::glyph("○", "o"))
1436
        };
7b9809e6 Andy McCall ↶ 1437
        let mut tail = String::new();
1438
        if let Some(n) = b.ahead.filter(|n| *n > 0) {
1439
            tail += &ui::ok(format!(" {}{n}", ui::glyph("↑", "+")));
1440
        }
1441
        if let Some(n) = b.behind.filter(|n| *n > 0) {
1442
            tail += &ui::warn(format!(" {}{n}", ui::glyph("↓", "-")));
1443
        }
75167672 Andy McCall 1444
        let head = b
1445
            .heads
1446
            .first()
1447
            .map(|h| {
1448
                repo.store()
1449
                    .get_change(h)
1450
                    .map(|c| ui::subject(subject_of(&c.message)))
1451
                    .unwrap_or_default()
1452
            })
1453
            .unwrap_or_else(|| ui::dim("(empty)"));
1454
        println!(
1455
            "{mark} {}{}{}{tail}  {head}",
1456
            ui::bookmark(&b.name),
1457
            ui::sep(),
1458
            ui::dim(plural(b.heads.len(), "head"))
1459
        );
7b9809e6 Andy McCall ↶ 1460
    }
1461
    Ok(0)
1462
}
1463
1464
pub fn bookmark_switch(name: &str, discard: bool) -> Result<i32> {
1465
    let mut repo = open()?;
1466
    let sp = ui::spinner(&format!("Switching to {name}…"));
1467
    let r = repo.bookmark_switch(name, discard)?;
75167672 Andy McCall 1468
    sp.done(&format!(
1469
        "{} to {}: {} written, {} removed",
1470
        ui::done("Switched"),
1471
        ui::bookmark(name),
1472
        plural(r.written, "file"),
1473
        r.removed
1474
    ));
7b9809e6 Andy McCall ↶ 1475
    if r.conflicted {
75167672 Andy McCall 1476
        println!(
1477
            "  {} {}",
1478
            ui::caution(),
1479
            ui::warn("this state has conflicts; see oxy status")
1480
        );
7b9809e6 Andy McCall ↶ 1481
    }
1482
    Ok(0)
1483
}
1484
1485
pub fn merge(bookmark: &str) -> Result<i32> {
1486
    let repo = open()?;
1487
    let sp = ui::spinner(&format!("Merging {bookmark}…"));
1488
    let r = repo.merge(bookmark)?;
1489
    if !r.changed {
75167672 Andy McCall 1490
        sp.done(&format!(
1491
            "{} {}",
1492
            ui::ok(ui::glyph("✔", "*")),
1493
            ui::dim(format!(
1494
                "{} already contains {bookmark}",
1495
                repo.config.bookmark
1496
            ))
1497
        ));
7b9809e6 Andy McCall ↶ 1498
        return Ok(0);
1499
    }
1500
    sp.done(&format!(
1501
        "{} {} into {}: now {}{}",
1502
        ui::done("Merged"),
1503
        ui::bookmark(bookmark),
1504
        ui::bookmark(&repo.config.bookmark),
1505
        plural(r.heads.len(), "head"),
75167672 Andy McCall 1506
        ui::dim(if r.checked_out {
1507
            "; working copy updated"
1508
        } else {
1509
            "; run oxy checkout to update the working copy"
1510
        })
7b9809e6 Andy McCall ↶ 1511
    ));
1512
    let snap = repo.snapshot("oxy merge")?;
1513
    if snap.base_snapshot.is_conflicted() {
75167672 Andy McCall 1514
        println!(
1515
            "  {} {}",
1516
            ui::caution(),
1517
            ui::warn("the result has conflicts; see oxy status")
1518
        );
7b9809e6 Andy McCall ↶ 1519
    }
1520
    Ok(0)
1521
}
1522
728da0f9 Andy McCall ↶ 1523
pub fn squash(change: &str, into: &str) -> Result<i32> {
1524
    let repo = open()?;
1525
    let c = repo.resolve_change(change)?;
1526
    let d = repo.resolve_change(into)?;
1527
    let sp = ui::spinner("Squashing…");
1528
    let h = repo.squash(&c, &d)?;
1529
    let new = repo.store().get_change(&h)?;
75167672 Andy McCall 1530
    sp.done(&format!(
1531
        "{} into {} {}  {}",
1532
        ui::done("Squashed"),
1533
        ui::id(short_id(&new)),
1534
        ui::hash(format!("#{}", h.short(12))),
1535
        ui::subject(subject_of(&new.message))
1536
    ));
728da0f9 Andy McCall ↶ 1537
    Ok(0)
1538
}
1539
1540
pub fn rebase(change: &str, onto: &[String]) -> Result<i32> {
1541
    let repo = open()?;
1542
    let c = repo.resolve_change(change)?;
1543
    let mut heads = Vec::new();
1544
    for o in onto {
1545
        heads.extend(repo.resolve_heads(o)?);
1546
    }
1547
    let sp = ui::spinner("Rebasing…");
1548
    let h = repo.rebase(&c, &heads)?;
1549
    let new = repo.store().get_change(&h)?;
75167672 Andy McCall 1550
    sp.done(&format!(
1551
        "{} {} {}  {}",
1552
        ui::done("Rebased"),
1553
        ui::id(short_id(&new)),
1554
        ui::hash(format!("#{}", h.short(12))),
1555
        ui::dim(format!(
1556
            "now depends on {}",
1557
            plural(new.deps.len(), "change")
1558
        ))
1559
    ));
728da0f9 Andy McCall ↶ 1560
    Ok(0)
1561
}