OXYGENHUB
# c3d2ef6104c2 oxygen / src / cli / mod.rs
43.1 KiB · Rust · last changed Rebase: --into-working-copy resolves a conflicted rebase in the working copy (closes #42) 1 month ago source blame history raw
1
//! Command-line definitions and dispatch.
2
3
mod format;
4
mod identity;
5
mod json;
6
mod proposal;
7
mod receipt;
8
mod sync;
9
pub mod ui;
10
mod workspace;
11
12
use anyhow::{Context, Result};
13
use clap::{Parser, Subcommand};
14
use oxy_core::repo::Repo;
15
use std::path::PathBuf;
16
17
#[derive(Parser)]
18
#[command(
19
    name = "oxy",
20
    version,
21
    about = "Oxygen: breathing fresh air into version control"
22
)]
23
struct Cli {
24
    /// Plain output: no colour, no spinner (also implied by NO_COLOR or a non-terminal)
25
    #[arg(long, global = true)]
26
    plain: bool,
27
    #[command(subcommand)]
28
    cmd: Cmd,
29
}
30
31
#[derive(Subcommand)]
32
enum Cmd {
33
    /// Create a repository in PATH (default: current directory)
34
    Init {
35
        /// Directory to create the repository in (default: the current directory)
36
        path: Option<PathBuf>,
37
        /// No working copy: an object store and references only, for hosting
38
        #[arg(long)]
39
        bare: bool,
40
    },
41
    /// Clone a repository from a local path or an http(s) URL
42
    Clone {
43
        /// Local path or http(s) URL of the repository
44
        url: String,
45
        /// Directory to clone into (default: the last part of the URL)
46
        dest: Option<PathBuf>,
47
        /// Leave blobs larger than this (e.g. 1M) to be fetched on first read
48
        #[arg(long)]
49
        max_blob: Option<String>,
50
        /// Materialize only these paths (repeatable); implies lazy blobs
51
        #[arg(long = "sparse")]
52
        sparse: Vec<String>,
53
        /// Shallow clone: fetch only this many levels of history below the heads
54
        #[arg(long)]
55
        depth: Option<u32>,
56
    },
57
    /// Fetch more history below a shallow clone's boundary
58
    Deepen {
59
        /// Levels of history to add below the boundary
60
        #[arg(default_value_t = 10)]
61
        depth: u32,
62
        /// Remote to fetch the history from
63
        #[arg(long, default_value = "origin")]
64
        remote: String,
65
    },
66
    /// Show or set the sparse filter (paths to materialize); re-checks out the bookmark
67
    Sparse {
68
        /// Paths to materialize; none prints the current filter
69
        paths: Vec<String>,
70
    },
71
    /// Show the working copy: changed paths and conflicts
72
    Status {
73
        /// Machine-readable output: paths, and every conflict with its kind and contributing changes
74
        #[arg(long)]
75
        json: bool,
76
    },
77
    /// One-line summary for shell prompts; fast and records nothing
78
    Prompt {
79
        /// Placeholders: %b bookmark, %c change id, %h heads, %d dirty (*), %x conflict (!), %A/%D ahead/behind (+n/-n), %a/%B raw counts, %s state glyph, %U/%O ahead/behind arrows, %i icon
80
        #[arg(long, default_value = oxy_core::repo::DEFAULT_PROMPT_FORMAT)]
81
        format: String,
82
        /// Glyph format (%i %b %c %s%U%O) instead of the plain default
83
        #[arg(long)]
84
        glyphs: bool,
85
        /// Colour by state (cyan clean, yellow dirty, red conflicted): raw escapes, or guarded for a bash or zsh PS1
86
        #[arg(long, value_parser = ["raw", "bash", "zsh"])]
87
        color: Option<String>,
88
    },
89
    /// Record the working copy as a change on the current bookmark
90
    Commit {
91
        /// The change's message: a subject line, then optionally a blank line and a body
92
        #[arg(short, long, required_unless_present = "file", conflicts_with = "file")]
93
        message: Option<String>,
94
        /// Read the message from FILE (`-` for standard input)
95
        #[arg(short = 'F', long, value_name = "FILE")]
96
        file: Option<PathBuf>,
97
        /// Extra explicit dependencies (ChangeId prefix, #hash prefix)
98
        #[arg(long = "depends-on")]
99
        depends_on: Vec<String>,
100
        /// Commit only these paths; the rest stays as uncommitted work
101
        paths: Vec<String>,
102
        /// Choose hunks one by one
103
        #[arg(short, long)]
104
        interactive: bool,
105
        /// Commit these hunks (as `oxy hunks` numbers them), comma separated
106
        #[arg(long, value_delimiter = ',')]
107
        hunks: Vec<usize>,
108
    },
109
    /// Fold CHANGE into one of its dependencies (keeps that change's id)
110
    Squash {
111
        /// The change to fold (ChangeId prefix, #hash prefix)
112
        change: String,
113
        /// The dependency that absorbs it
114
        #[arg(long)]
115
        into: String,
116
    },
117
    /// Re-express CHANGE against another base state
118
    Rebase {
119
        /// The change to re-express (ChangeId prefix, #hash prefix)
120
        change: String,
121
        /// The changes, bookmark or tag whose state becomes the new base
122
        #[arg(long, required = true, num_args = 1..)]
123
        onto: Vec<String>,
124
        /// Where the rebase would be conflicted, merge the target into the
125
        /// current bookmark instead, leaving the conflict in the working
126
        /// copy to fix and commit
127
        #[arg(long)]
128
        into_working_copy: bool,
129
    },
130
    /// Show which change introduced each line of a file
131
    Blame {
132
        /// File to annotate, relative to the repository root
133
        path: String,
134
        /// Machine-readable output: one JSON document on stdout
135
        #[arg(long)]
136
        json: bool,
137
    },
138
    /// Find the change that introduced a regression
139
    Bisect {
140
        #[command(subcommand)]
141
        cmd: BisectCmd,
142
    },
143
    /// List changes reachable from the bookmark and the working copy
144
    Log {
145
        /// Show at most this many changes
146
        #[arg(short = 'n', long)]
147
        limit: Option<usize>,
148
        /// Show full messages, dependencies, and signatures
149
        #[arg(short, long)]
150
        verbose: bool,
151
        /// Only changes touching this path (renames followed)
152
        #[arg(long)]
153
        path: Option<String>,
154
        /// Only changes that wrote or deleted lines START to END of PATH
155
        /// (numbered as in the working copy's base), or deleted lines from
156
        /// between them: the history of a function
157
        #[arg(short = 'L', value_name = "START,END:PATH", conflicts_with = "path")]
158
        lines: Option<String>,
159
        /// Machine-readable output: one JSON document on stdout
160
        #[arg(long)]
161
        json: bool,
162
    },
163
    /// Show what the working copy changes against its base
164
    Diff {
165
        /// A change instead of the working copy
166
        change: Option<String>,
167
        /// Machine-readable output: one JSON document on stdout
168
        #[arg(long)]
169
        json: bool,
170
    },
171
    /// Print a file as it is in a state (default: the working copy's base)
172
    Cat {
173
        /// File to print, relative to the repository root
174
        path: String,
175
        /// A change, bookmark, or tag
176
        #[arg(short = 'r', long)]
177
        change: Option<String>,
178
    },
179
    /// Print the repository root, workspace, and bookmark
180
    Root {
181
        /// Machine-readable output: one JSON document on stdout
182
        #[arg(long)]
183
        json: bool,
184
    },
185
    /// Print the version of oxy, its repository format, and protocol
186
    Version {
187
        /// Machine-readable output: one JSON document on stdout
188
        #[arg(long)]
189
        json: bool,
190
    },
191
    /// Restore paths to the working copy's base, or undo chosen hunks
192
    Discard {
193
        /// Paths to restore; none with --hunks, or everything with neither
194
        paths: Vec<String>,
195
        /// Hunk indices as `oxy hunks` numbers them, comma separated
196
        #[arg(long, value_delimiter = ',')]
197
        hunks: Vec<usize>,
198
    },
199
    /// List the working copy's hunks, numbered as commit --hunks expects
200
    Hunks {
201
        /// Machine-readable output: one JSON document on stdout
202
        #[arg(long)]
203
        json: bool,
204
    },
205
    /// With -m, change the message of a head; without, name the working
206
    /// copy for a build: its tag, or the nearest tag plus distance and
207
    /// change, or the bookmark and change, and -dirty
208
    Describe {
209
        /// The new message
210
        #[arg(short, long)]
211
        message: Option<String>,
212
        /// The head to describe (default: the one the working copy sits on)
213
        change: Option<String>,
214
        /// Machine-readable output (naming only)
215
        #[arg(long, conflicts_with = "message")]
216
        json: bool,
217
    },
218
    /// Fold the working copy into the head it sits on, or into CHANGE with --into
219
    Amend {
220
        /// Replace the message too
221
        #[arg(short, long)]
222
        message: Option<String>,
223
        /// Amend an older change; the edits must touch only lines it already knows
224
        #[arg(long)]
225
        into: Option<String>,
226
    },
227
    /// Split a head: the named paths become a separate first change
228
    Split {
229
        /// The head to split
230
        change: String,
231
        /// Paths whose edits become the first change
232
        paths: Vec<String>,
233
    },
234
    /// Drop a head from the bookmark; its content stays on disk as uncommitted work
235
    Abandon {
236
        /// The head to drop (ChangeId prefix, #hash prefix)
237
        change: String,
238
    },
239
    /// Show one change (ChangeId prefix, #hash prefix, or @)
240
    Show {
241
        /// ChangeId prefix, #hash prefix, or @ for the working copy
242
        change: String,
243
        /// Machine-readable output: one JSON document on stdout
244
        #[arg(long)]
245
        json: bool,
246
    },
247
    /// Move the working copy to the state formed by CHANGE... (default: the bookmark heads)
248
    Checkout {
249
        /// Changes whose state to check out (default: the bookmark heads)
250
        changes: Vec<String>,
251
        /// Throw away uncommitted working-copy changes
252
        #[arg(long)]
253
        discard: bool,
254
        /// Take uncommitted changes along; refused when the target has
255
        /// other versions of the files they touch
256
        #[arg(long, conflicts_with = "discard")]
257
        carry: bool,
258
    },
259
    /// Report which conflicts of the working copy's base are resolved by the current files
260
    Resolve {
261
        /// Machine-readable output: one JSON document on stdout
262
        #[arg(long)]
263
        json: bool,
264
    },
265
    /// Undo the last operation
266
    Undo,
267
    /// Write a checkpoint of the current bookmark's state now
268
    Checkpoint,
269
    /// Print a shell completion script: `oxy completions bash > ~/.local/share/bash-completion/completions/oxy`
270
    Completions {
271
        /// bash, zsh, fish, elvish or powershell
272
        shell: clap_complete::Shell,
273
    },
274
    /// Write man pages (oxy.1 and one per command) into DIR, or print oxy.1
275
    Man {
276
        /// Directory to write every page into, e.g. ~/.local/share/man/man1
277
        #[arg(long)]
278
        dir: Option<PathBuf>,
279
    },
280
    /// Check the identity, configuration and remotes, and say what to do about any problem
281
    Doctor {
282
        /// Do not contact the remotes
283
        #[arg(long)]
284
        offline: bool,
285
        /// Machine-readable output: one JSON document on stdout
286
        #[arg(long)]
287
        json: bool,
288
    },
289
    /// Check the repository's integrity: objects, operation log, references, signatures, checkpoints
290
    Fsck {
291
        /// Machine-readable output: one JSON document on stdout
292
        #[arg(long)]
293
        json: bool,
294
    },
295
    /// Prune unreachable objects older than the grace period and repack everything into one pack
296
    Gc {
297
        /// Ignore the grace period (core.gc-grace) and prune immediately
298
        #[arg(long)]
299
        now: bool,
300
    },
301
    /// List operations
302
    #[command(name = "op")]
303
    Op {
304
        #[command(subcommand)]
305
        cmd: OpCmd,
306
    },
307
    /// Take the advisory local lock on a lockable file, making it writable
308
    Lock {
309
        /// The lockable file
310
        path: String,
311
    },
312
    /// Release the local lock and make the file read-only again
313
    Unlock {
314
        /// The locked file
315
        path: String,
316
    },
317
    /// Workspaces: extra checkout directories sharing this repository
318
    Workspace {
319
        #[command(subcommand)]
320
        cmd: WorkspaceCmd,
321
    },
322
    /// Bookmarks: named states; each workspace works on one
323
    Bookmark {
324
        #[command(subcommand)]
325
        cmd: BookmarkCmd,
326
    },
327
    /// Union another bookmark's heads into the current one (no merge change)
328
    Merge {
329
        /// The bookmark whose heads to add
330
        bookmark: String,
331
    },
332
    /// Subrepositories: nested repositories pinned to a state
333
    Submodule {
334
        #[command(subcommand)]
335
        cmd: SubmoduleCmd,
336
    },
337
    /// Execution receipts: signed records of what a runner ran on a state
338
    Receipt {
339
        #[command(subcommand)]
340
        cmd: ReceiptCmd,
341
    },
342
    /// Tags: immutable named states
343
    Tag {
344
        #[command(subcommand)]
345
        cmd: TagCmd,
346
    },
347
    /// Manage remotes
348
    Remote {
349
        #[command(subcommand)]
350
        cmd: RemoteCmd,
351
    },
352
    /// Fetch every bookmark of a remote into its tracking references
353
    Fetch {
354
        /// Remote name (default: origin)
355
        remote: Option<String>,
356
        /// Machine-readable output: one JSON document on stdout
357
        #[arg(long)]
358
        json: bool,
359
    },
360
    /// Fetch, then union the remote bookmark into the local one (no merge change)
361
    Pull {
362
        /// Remote name (default: origin)
363
        remote: Option<String>,
364
        /// Machine-readable output: one JSON document on stdout
365
        #[arg(long)]
366
        json: bool,
367
    },
368
    /// Push the current bookmark to a remote
369
    Push {
370
        /// Remote name (default: origin)
371
        remote: Option<String>,
372
        /// Allow dropping heads the remote has
373
        #[arg(long)]
374
        force: bool,
375
        /// Push this bookmark instead of the workspace's current one
376
        #[arg(short = 'b', long)]
377
        bookmark: Option<String>,
378
        /// Delete this bookmark on the remote (never its default bookmark);
379
        /// the local bookmark is kept
380
        #[arg(long, value_name = "NAME", conflicts_with_all = ["bookmark", "force"])]
381
        delete: Option<String>,
382
        /// Machine-readable output: one JSON document on stdout
383
        #[arg(long)]
384
        json: bool,
385
    },
386
    /// Serve repositories under ROOT over HTTPS (with --tls-cert/--tls-key) or plain HTTP
387
    Serve {
388
        /// Directory with one repository per subdirectory
389
        #[arg(long, default_value = ".")]
390
        root: PathBuf,
391
        /// Address and port to listen on
392
        #[arg(long, default_value = "127.0.0.1:8890")]
393
        bind: String,
394
        /// Bearer token allowed to push (repeatable); none means open
395
        #[arg(long = "token")]
396
        tokens: Vec<String>,
397
        /// PEM certificate chain; enables HTTPS together with --tls-key
398
        #[arg(long, requires = "tls_key")]
399
        tls_cert: Option<PathBuf>,
400
        /// PEM private key
401
        #[arg(long, requires = "tls_cert")]
402
        tls_key: Option<PathBuf>,
403
    },
404
    /// Manage the signing identity
405
    Identity {
406
        #[command(subcommand)]
407
        cmd: IdentityCmd,
408
    },
409
    /// Seal changes with your key: named ones, or every change on the current bookmark you can authenticate but have not
410
    Seal {
411
        /// Changes to seal (default: every change on the bookmark you can authenticate and have not sealed)
412
        changes: Vec<String>,
413
        /// Seal every change of a hub proposal and push the seal (your approval)
414
        #[arg(long, conflicts_with = "changes")]
415
        proposal: Option<String>,
416
        /// Machine-readable output: one JSON document on stdout
417
        #[arg(long)]
418
        json: bool,
419
    },
420
    /// Hub proposals: show one, or land it from this client
421
    Proposal {
422
        #[command(subcommand)]
423
        cmd: ProposalCmd,
424
    },
425
    /// Verify the signatures on a change (default: every change in the log)
426
    Verify {
427
        /// The change to verify (default: every change in the log)
428
        change: Option<String>,
429
        /// Machine-readable output: one JSON document on stdout
430
        #[arg(long)]
431
        json: bool,
432
    },
433
    /// Git interoperability
434
    Git {
435
        #[command(subcommand)]
436
        cmd: GitCmd,
437
    },
438
    /// Manage the trust policy (who may update which bookmarks)
439
    Policy {
440
        #[command(subcommand)]
441
        cmd: PolicyCmd,
442
    },
443
    /// Set a configuration key (author.*, core.sign, core.op-retention, core.gc-grace, core.checkpoint-interval, filter.max-blob, filter.paths, workspace.bookmark, remote.<name>.url|token|ca)
444
    Config {
445
        /// The key, such as author.name or remote.origin.token
446
        key: String,
447
        /// The value to set
448
        value: String,
449
        /// Write to the user file (~/.config/oxy/config.toml) instead of this repository
450
        #[arg(long)]
451
        user: bool,
452
    },
453
}
454
455
#[derive(Subcommand)]
456
enum OpCmd {
457
    /// List operations, newest first
458
    Log {
459
        /// Machine-readable output: one JSON document on stdout
460
        #[arg(long)]
461
        json: bool,
462
    },
463
}
464
465
#[derive(Subcommand)]
466
enum WorkspaceCmd {
467
    /// Create a workspace at PATH checked out on CHANGE... (default: the bookmark heads)
468
    Add {
469
        /// Directory for the new workspace (must be empty or absent)
470
        path: PathBuf,
471
        /// Changes whose state to check out there
472
        changes: Vec<String>,
473
    },
474
    /// List workspaces and their working-copy changes
475
    List {
476
        /// Machine-readable output: one JSON document on stdout
477
        #[arg(long)]
478
        json: bool,
479
    },
480
    /// Stop tracking a workspace (by id prefix or path); its files stay
481
    Forget {
482
        /// Workspace id prefix or path
483
        workspace: String,
484
    },
485
}
486
487
#[derive(Subcommand)]
488
enum BisectCmd {
489
    /// Begin; remembers where the working copy was
490
    Start,
491
    /// Mark CHANGE... (or the state under test) as good
492
    Good {
493
        /// Changes known to be good (default: the state under test)
494
        changes: Vec<String>,
495
    },
496
    /// Mark CHANGE... (or the state under test) as bad
497
    Bad {
498
        /// Changes known to be bad (default: the state under test)
499
        changes: Vec<String>,
500
    },
501
    /// The state under test cannot be tested; try another
502
    Skip,
503
    /// Run a command for each step: exit 0 good, 125 skip, else bad
504
    Run {
505
        /// Command and arguments to run at each step
506
        #[arg(required = true, trailing_var_arg = true)]
507
        command: Vec<String>,
508
    },
509
    /// Where the search stands
510
    Status {
511
        /// Machine-readable output: one JSON document on stdout
512
        #[arg(long)]
513
        json: bool,
514
    },
515
    /// Restore the working copy and forget the search
516
    Reset,
517
}
518
519
#[derive(Subcommand)]
520
enum BookmarkCmd {
521
    /// Create a bookmark at CHANGE... (default: the working copy's base)
522
    Create {
523
        /// Name of the new bookmark
524
        name: String,
525
        /// Its heads (default: the working copy's base). A state is its
526
        /// heads and what they depend on: a change alone may leave out
527
        /// earlier changes of the current state, which is refused unless
528
        /// --upto or --only says which is meant
529
        changes: Vec<String>,
530
        /// Everything of the current state up to CHANGE..., as a Git
531
        /// branch at a commit would hold
532
        #[arg(long, conflicts_with = "only")]
533
        upto: bool,
534
        /// Just CHANGE... and what they depend on
535
        #[arg(long)]
536
        only: bool,
537
    },
538
    /// Point an existing bookmark at CHANGE...
539
    Set {
540
        /// The bookmark to move
541
        name: String,
542
        /// Its new heads. A change alone may leave out changes the
543
        /// bookmark now holds that were recorded before it, which is
544
        /// refused unless --upto or --only says which is meant
545
        changes: Vec<String>,
546
        /// Everything the bookmark holds up to CHANGE..., as a Git branch
547
        /// moved to a commit would hold
548
        #[arg(long, conflicts_with = "only")]
549
        upto: bool,
550
        /// Just CHANGE... and what they depend on
551
        #[arg(long)]
552
        only: bool,
553
    },
554
    /// Remove a bookmark; its changes stay
555
    Delete {
556
        /// The bookmark to remove
557
        name: String,
558
    },
559
    /// List bookmarks with their heads and difference from origin
560
    List {
561
        /// Machine-readable output: one JSON document on stdout
562
        #[arg(long)]
563
        json: bool,
564
    },
565
    /// Make NAME this workspace's bookmark and check it out. Uncommitted work stops it; --carry takes the work along, --discard drops it
566
    Switch {
567
        /// The bookmark to work on
568
        name: String,
569
        /// Throw away uncommitted working-copy changes
570
        #[arg(long)]
571
        discard: bool,
572
        /// Take uncommitted changes along; refused when NAME has other
573
        /// versions of the files they touch
574
        #[arg(long, conflicts_with = "discard")]
575
        carry: bool,
576
    },
577
}
578
579
#[derive(Subcommand)]
580
enum SubmoduleCmd {
581
    /// Clone URL (Oxygen or Git) into PATH and register it in .oxymodules
582
    Add {
583
        /// URL or path of the Oxygen or Git repository
584
        url: String,
585
        /// Where to put it, relative to the repository root
586
        path: String,
587
        /// Bookmark (Oxygen) or branch (Git) to check out and track
588
        #[arg(long)]
589
        bookmark: Option<String>,
590
    },
591
    /// Bring nested repositories to their pins
592
    Update {
593
        /// Clone nested repositories that are absent
594
        #[arg(long)]
595
        init: bool,
596
        /// Subrepos to update (default: all)
597
        paths: Vec<String>,
598
    },
599
    /// List subrepos with their pins and on-disk state
600
    Status {
601
        /// Machine-readable output: one JSON document on stdout
602
        #[arg(long)]
603
        json: bool,
604
    },
605
    /// Unregister PATH; the directory stays, the node goes with the next commit
606
    Remove {
607
        /// The subrepo to unregister
608
        path: String,
609
    },
610
}
611
612
#[derive(Subcommand)]
613
enum ReceiptCmd {
614
    /// The receipts kept for a state (default: the bookmark heads)
615
    List {
616
        /// Change, bookmark or tag whose state to look at
617
        rev: Option<String>,
618
        /// Machine-readable output: one JSON document on stdout
619
        #[arg(long)]
620
        json: bool,
621
    },
622
    /// One receipt in full, and whether its signature verifies
623
    Show {
624
        /// The receipt (a prefix of its hash, as `list` shows it)
625
        receipt: String,
626
        /// Change, bookmark or tag whose state holds it
627
        #[arg(long)]
628
        rev: Option<String>,
629
        /// Machine-readable output: one JSON document on stdout
630
        #[arg(long)]
631
        json: bool,
632
    },
633
    /// Write a signed receipt to FILE
634
    Export {
635
        /// The receipt (a prefix of its hash, as `list` shows it)
636
        receipt: String,
637
        /// Where to write it
638
        file: String,
639
        /// Change, bookmark or tag whose state holds it
640
        #[arg(long)]
641
        rev: Option<String>,
642
    },
643
    /// Check a signed receipt in FILE without keeping it
644
    Verify {
645
        /// A signed receipt, as a runner or `export` writes it
646
        file: String,
647
        /// Machine-readable output: one JSON document on stdout
648
        #[arg(long)]
649
        json: bool,
650
    },
651
    /// Verify a signed receipt in FILE and keep it with its state
652
    Import {
653
        /// A signed receipt, as a runner or `export` writes it
654
        file: String,
655
    },
656
}
657
658
#[derive(Subcommand)]
659
enum TagCmd {
660
    /// Tag the state of CHANGE... (default: the bookmark heads)
661
    Create {
662
        /// Name of the tag; tags never move
663
        name: String,
664
        /// Changes whose state to tag (default: the bookmark heads)
665
        changes: Vec<String>,
666
        /// A message recorded with the tag
667
        #[arg(short, long, default_value = "")]
668
        message: String,
669
    },
670
    /// List tags and the states they name
671
    List {
672
        /// Machine-readable output: one JSON document on stdout
673
        #[arg(long)]
674
        json: bool,
675
    },
676
}
677
678
#[derive(Subcommand)]
679
enum RemoteCmd {
680
    /// Add a remote
681
    Add {
682
        /// Name to refer to the remote by, such as origin
683
        name: String,
684
        /// Local path or http(s) URL of the repository
685
        url: String,
686
    },
687
    /// Remove a remote
688
    Remove {
689
        /// The remote to remove
690
        name: String,
691
    },
692
    /// List remotes and their URLs
693
    List {
694
        /// Machine-readable output: one JSON document on stdout
695
        #[arg(long)]
696
        json: bool,
697
    },
698
}
699
700
#[derive(Subcommand)]
701
enum ProposalCmd {
702
    /// Show a proposal by its hub URL
703
    Show {
704
        /// The proposal's URL on the hub
705
        url: String,
706
        /// Machine-readable output: one JSON document on stdout
707
        #[arg(long)]
708
        json: bool,
709
    },
710
    /// Fetch the proposal's changes, set the target bookmark to the projected state, and push with your key
711
    Land {
712
        /// The proposal's URL on the hub
713
        url: String,
714
        /// Land even when the hub reports blockers
715
        #[arg(long)]
716
        force: bool,
717
    },
718
}
719
720
#[derive(Subcommand)]
721
enum IdentityCmd {
722
    /// Generate a composite Ed25519 + ML-DSA-65 key pair and make it your author identity
723
    Create {
724
        /// Your name (default: author.name)
725
        #[arg(long)]
726
        name: Option<String>,
727
        /// Your email (default: author.email)
728
        #[arg(long)]
729
        email: Option<String>,
730
        /// Record the author in this repository only, not in the user config
731
        #[arg(long)]
732
        local: bool,
733
        /// Expire the identity this many days from now
734
        #[arg(long)]
735
        expires: Option<u64>,
736
    },
737
    /// Show the configured identity
738
    Show,
739
    /// Write your identity object to a file, to hand to a policy holder
740
    Export {
741
        /// File to write (default: <key>.identity in the current directory)
742
        path: Option<PathBuf>,
743
    },
744
    /// Sign a host's challenge (hex, at least 16 bytes) to prove you hold your key; prints the signature as hex
745
    SignChallenge {
746
        /// The host's challenge, as hex
747
        challenge: String,
748
        /// Machine-readable output: one JSON document on stdout
749
        #[arg(long)]
750
        json: bool,
751
    },
752
    /// Move to a fresh key pair; the policy follows if it names your key
753
    Rotate,
754
    /// Re-issue your identity with a new expiry (in days from now; 0 = never)
755
    Renew {
756
        /// Days from now until it expires; 0 for never
757
        #[arg(long)]
758
        expires: u64,
759
    },
760
    /// Revoke a key: yours by default, or any key if you hold a policy root
761
    Revoke {
762
        /// KeyId prefix (default: your own key)
763
        key: Option<String>,
764
        /// Why, recorded in the revocation
765
        #[arg(long, default_value = "")]
766
        reason: String,
767
    },
768
    /// Keys allowed to sign or seal on your behalf
769
    Delegate {
770
        #[command(subcommand)]
771
        cmd: DelegateCmd,
772
    },
773
}
774
775
#[derive(Subcommand)]
776
enum DelegateCmd {
777
    /// Add a delegate from an exported identity file
778
    Add {
779
        /// The delegate's exported identity file
780
        identity_file: PathBuf,
781
    },
782
    /// Remove a delegate by KeyId prefix
783
    Remove {
784
        /// KeyId prefix of the delegate
785
        key: String,
786
    },
787
    /// List delegates
788
    List,
789
}
790
791
#[derive(Subcommand)]
792
enum GitCmd {
793
    /// Export the current bookmark to a Git repository (created bare if absent)
794
    Export {
795
        /// Git repository to write to (created bare if absent)
796
        git_dir: PathBuf,
797
        /// Git branch to write (default: the bookmark name)
798
        #[arg(long)]
799
        branch: Option<String>,
800
    },
801
    /// Fetch a branch from a Git remote (path or URL) into the current bookmark
802
    Fetch {
803
        /// Git remote: a path or URL
804
        url: String,
805
        /// Branch to fetch
806
        #[arg(long, default_value = "main")]
807
        branch: String,
808
    },
809
    /// Push the current bookmark to a branch of a Git remote (fetch first)
810
    Push {
811
        /// Git remote: a path or URL
812
        url: String,
813
        /// Branch to push to
814
        #[arg(long, default_value = "main")]
815
        branch: String,
816
    },
817
    /// Check this repository's import of a Git branch: every commit's tree must be reproduced exactly
818
    Verify {
819
        /// The Git repository the import came from
820
        git_dir: PathBuf,
821
        /// Branch that was imported
822
        #[arg(long, default_value = "main")]
823
        branch: String,
824
    },
825
    /// Import a Git branch into a new Oxygen repository at DEST
826
    Import {
827
        /// Git repository to read
828
        git_dir: PathBuf,
829
        /// Directory for the new Oxygen repository
830
        dest: PathBuf,
831
        /// Branch to import
832
        #[arg(long, default_value = "main")]
833
        branch: String,
834
    },
835
}
836
837
#[derive(Subcommand)]
838
enum PolicyCmd {
839
    /// Create the initial policy with your identity as the only root
840
    Init,
841
    /// Show the current policy
842
    Show {
843
        /// Machine-readable output: one JSON document on stdout
844
        #[arg(long)]
845
        json: bool,
846
    },
847
    /// Allow an identity (from `oxy identity export`) to update bookmarks
848
    Grant {
849
        /// The identity to grant, exported with `oxy identity export`
850
        identity_file: PathBuf,
851
        /// Reference pattern the grant applies to (default: every bookmark)
852
        #[arg(long)]
853
        pattern: Option<String>,
854
        /// Where to write the proposal when more root signatures are needed
855
        #[arg(long)]
856
        out: Option<PathBuf>,
857
    },
858
    /// Revoke a key (KeyId prefix of an identity in the policy)
859
    Revoke {
860
        /// KeyId prefix of the identity
861
        key: String,
862
        /// Where to write the proposal when more root signatures are needed
863
        #[arg(long)]
864
        out: Option<PathBuf>,
865
    },
866
    /// Manage root keys and the signature threshold for policy updates
867
    Root {
868
        #[command(subcommand)]
869
        cmd: RootCmd,
870
    },
871
    /// Add your root signature to a proposal file; applies it once the threshold is met
872
    Sign {
873
        /// The proposal file to sign
874
        proposal: PathBuf,
875
        /// Where to write the proposal if it still needs signatures (default: in place)
876
        #[arg(long)]
877
        out: Option<PathBuf>,
878
    },
879
}
880
881
#[derive(Subcommand)]
882
enum RootCmd {
883
    /// Make an exported identity a root key
884
    Add {
885
        /// The identity to make a root, exported with `oxy identity export`
886
        identity_file: PathBuf,
887
        /// Where to write the proposal when more root signatures are needed
888
        #[arg(long)]
889
        out: Option<PathBuf>,
890
    },
891
    /// Remove a root key by KeyId prefix
892
    Remove {
893
        /// KeyId prefix of the root key
894
        key: String,
895
        /// Where to write the proposal when more root signatures are needed
896
        #[arg(long)]
897
        out: Option<PathBuf>,
898
    },
899
    /// Require this many root signatures on policy updates
900
    Threshold {
901
        /// Number of root signatures
902
        n: u32,
903
        /// Where to write the proposal when more root signatures are needed
904
        #[arg(long)]
905
        out: Option<PathBuf>,
906
    },
907
}
908
909
/// Open the repository containing the current directory.
910
fn open() -> Result<Repo> {
911
    Repo::open(&std::env::current_dir()?).context("opening repository")
912
}
913
914
/// `oxy man`: every page into `dir`, or the top-level page on stdout.
915
fn man(dir: Option<PathBuf>) -> Result<i32> {
916
    use clap::CommandFactory;
917
    let cmd = Cli::command();
918
    match dir {
919
        Some(dir) => {
920
            std::fs::create_dir_all(&dir)?;
921
            clap_mangen::generate_to(cmd, &dir)?;
922
            let pages = std::fs::read_dir(&dir)?
923
                .filter(|e| {
924
                    e.as_ref()
925
                        .is_ok_and(|e| e.path().extension().is_some_and(|x| x == "1"))
926
                })
927
                .count();
928
            println!(
929
                "{}",
930
                ui::done(format!("Wrote {pages} man pages to {}", dir.display()))
931
            );
932
        }
933
        None => clap_mangen::Man::new(cmd).render(&mut std::io::stdout())?,
934
    }
935
    Ok(0)
936
}
937
938
/// Parse arguments and run; returns the process exit code.
939
pub fn run() -> Result<i32> {
940
    let cli = Cli::parse();
941
    ui::init(cli.plain);
942
    match cli.cmd {
943
        Cmd::Completions { shell } => {
944
            use clap::CommandFactory;
945
            clap_complete::generate(shell, &mut Cli::command(), "oxy", &mut std::io::stdout());
946
            Ok(0)
947
        }
948
        Cmd::Man { dir } => man(dir),
949
        Cmd::Init { path, bare } => workspace::init(path, bare),
950
        Cmd::Status { json } => workspace::status(json),
951
        Cmd::Prompt {
952
            format,
953
            glyphs,
954
            color,
955
        } => workspace::prompt(&format, glyphs, color.as_deref()),
956
        Cmd::Commit {
957
            message,
958
            file,
959
            depends_on,
960
            paths,
961
            interactive,
962
            hunks,
963
        } => {
964
            let message = match (message, file) {
965
                (Some(m), _) => m,
966
                (None, Some(f)) if f.as_os_str() == "-" => {
967
                    let mut s = String::new();
968
                    std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
969
                    s
970
                }
971
                (None, Some(f)) => std::fs::read_to_string(&f).map_err(|e| {
972
                    anyhow::anyhow!("reading the message from {}: {e}", f.display())
973
                })?,
974
                (None, None) => anyhow::bail!("a commit message is required (-m or -F)"),
975
            };
976
            workspace::commit(&message, &depends_on, &paths, interactive, &hunks)
977
        }
978
        Cmd::Cat { path, change } => workspace::cat(&path, change.as_deref()),
979
        Cmd::Root { json } => workspace::root(json),
980
        Cmd::Version { json } => workspace::version(json),
981
        Cmd::Discard { paths, hunks } => workspace::discard(&paths, &hunks),
982
        Cmd::Hunks { json } => workspace::hunks(json),
983
        Cmd::Squash { change, into } => workspace::squash(&change, &into),
984
        Cmd::Rebase {
985
            change,
986
            onto,
987
            into_working_copy,
988
        } => workspace::rebase(&change, &onto, into_working_copy),
989
        Cmd::Blame { path, json } => workspace::blame(&path, json),
990
        Cmd::Bisect { cmd } => match cmd {
991
            BisectCmd::Start => workspace::bisect_start(),
992
            BisectCmd::Good { changes } => workspace::bisect_mark(Some(true), &changes),
993
            BisectCmd::Bad { changes } => workspace::bisect_mark(Some(false), &changes),
994
            BisectCmd::Skip => workspace::bisect_mark(None, &[]),
995
            BisectCmd::Run { command } => workspace::bisect_run(&command),
996
            BisectCmd::Status { json } => workspace::bisect_status(json),
997
            BisectCmd::Reset => workspace::bisect_reset(),
998
        },
999
        Cmd::Log {
1000
            limit,
1001
            verbose,
1002
            path,
1003
            lines,
1004
            json,
1005
        } => workspace::log(limit, verbose, path.as_deref(), lines.as_deref(), json),
1006
        Cmd::Diff { change, json } => workspace::diff(change.as_deref(), json),
1007
        Cmd::Describe {
1008
            message,
1009
            change,
1010
            json,
1011
        } => match message {
1012
            Some(m) => workspace::describe(&m, change.as_deref()),
1013
            None if change.is_some() => {
1014
                anyhow::bail!(
1015
                    "naming works on the working copy; to change a head's message pass -m"
1016
                )
1017
            }
1018
            None => workspace::describe_name(json),
1019
        },
1020
        Cmd::Amend { message, into } => workspace::amend(message.as_deref(), into.as_deref()),
1021
        Cmd::Split { change, paths } => workspace::split(&change, &paths),
1022
        Cmd::Abandon { change } => workspace::abandon(&change),
1023
        Cmd::Show { change, json } => workspace::show(&change, json),
1024
        Cmd::Checkout {
1025
            changes,
1026
            discard,
1027
            carry,
1028
        } => workspace::checkout(&changes, discard, carry),
1029
        Cmd::Resolve { json } => workspace::resolve(json),
1030
        Cmd::Undo => workspace::undo(),
1031
        Cmd::Gc { now } => workspace::gc(now),
1032
        Cmd::Fsck { json } => workspace::fsck(json),
1033
        Cmd::Doctor { offline, json } => workspace::doctor(offline, json),
1034
        Cmd::Checkpoint => workspace::checkpoint(),
1035
        Cmd::Op {
1036
            cmd: OpCmd::Log { json },
1037
        } => workspace::op_log(json),
1038
        Cmd::Clone {
1039
            url,
1040
            dest,
1041
            max_blob,
1042
            sparse,
1043
            depth,
1044
        } => sync::clone(&url, dest, max_blob.as_deref(), &sparse, depth),
1045
        Cmd::Deepen { depth, remote } => sync::deepen(&remote, depth),
1046
        Cmd::Sparse { paths } => workspace::sparse(&paths),
1047
        Cmd::Lock { path } => workspace::lock(&path),
1048
        Cmd::Unlock { path } => workspace::unlock(&path),
1049
        Cmd::Workspace { cmd } => match cmd {
1050
            WorkspaceCmd::Add { path, changes } => workspace::workspace_add(&path, &changes),
1051
            WorkspaceCmd::List { json } => workspace::workspace_list(json),
1052
            WorkspaceCmd::Forget { workspace } => workspace::workspace_forget(&workspace),
1053
        },
1054
        Cmd::Bookmark { cmd } => match cmd {
1055
            BookmarkCmd::Create {
1056
                name,
1057
                changes,
1058
                upto,
1059
                only,
1060
            } => workspace::bookmark_create(&name, &changes, upto, only),
1061
            BookmarkCmd::Set {
1062
                name,
1063
                changes,
1064
                upto,
1065
                only,
1066
            } => workspace::bookmark_set(&name, &changes, upto, only),
1067
            BookmarkCmd::Delete { name } => workspace::bookmark_delete(&name),
1068
            BookmarkCmd::List { json } => workspace::bookmark_list(json),
1069
            BookmarkCmd::Switch {
1070
                name,
1071
                discard,
1072
                carry,
1073
            } => workspace::bookmark_switch(&name, discard, carry),
1074
        },
1075
        Cmd::Merge { bookmark } => workspace::merge(&bookmark),
1076
        Cmd::Submodule { cmd } => match cmd {
1077
            SubmoduleCmd::Add {
1078
                url,
1079
                path,
1080
                bookmark,
1081
            } => sync::submodule_add(&url, &path, bookmark.as_deref()),
1082
            SubmoduleCmd::Update { init, paths } => sync::submodule_update(init, &paths),
1083
            SubmoduleCmd::Status { json } => sync::submodule_status(json),
1084
            SubmoduleCmd::Remove { path } => sync::submodule_remove(&path),
1085
        },
1086
        Cmd::Receipt { cmd } => match cmd {
1087
            ReceiptCmd::List { rev, json } => receipt::list(rev.as_deref(), json),
1088
            ReceiptCmd::Show {
1089
                receipt: r,
1090
                rev,
1091
                json,
1092
            } => receipt::show(&r, rev.as_deref(), json),
1093
            ReceiptCmd::Export {
1094
                receipt: r,
1095
                file,
1096
                rev,
1097
            } => receipt::export(&r, &file, rev.as_deref()),
1098
            ReceiptCmd::Verify { file, json } => receipt::verify(&file, json),
1099
            ReceiptCmd::Import { file } => receipt::import(&file),
1100
        },
1101
        Cmd::Tag { cmd } => match cmd {
1102
            TagCmd::Create {
1103
                name,
1104
                changes,
1105
                message,
1106
            } => workspace::tag_create(&name, &changes, &message),
1107
            TagCmd::List { json } => workspace::tag_list(json),
1108
        },
1109
        Cmd::Remote { cmd } => match cmd {
1110
            RemoteCmd::Add { name, url } => sync::remote_add(&name, &url),
1111
            RemoteCmd::Remove { name } => sync::remote_remove(&name),
1112
            RemoteCmd::List { json } => sync::remote_list(json),
1113
        },
1114
        Cmd::Fetch { remote, json } => sync::fetch(remote.as_deref(), json),
1115
        Cmd::Pull { remote, json } => sync::pull(remote.as_deref(), json),
1116
        Cmd::Push {
1117
            remote,
1118
            force,
1119
            bookmark,
1120
            delete,
1121
            json,
1122
        } => match delete {
1123
            Some(name) => sync::push_delete(remote.as_deref(), &name, json),
1124
            None => sync::push(remote.as_deref(), force, bookmark.as_deref(), json),
1125
        },
1126
        Cmd::Serve {
1127
            root,
1128
            bind,
1129
            tokens,
1130
            tls_cert,
1131
            tls_key,
1132
        } => sync::serve(root, &bind, tokens, tls_cert.zip(tls_key)),
1133
        Cmd::Identity { cmd } => match cmd {
1134
            IdentityCmd::Create {
1135
                name,
1136
                email,
1137
                local,
1138
                expires,
1139
            } => identity::create(name, email, local, expires),
1140
            IdentityCmd::Show => identity::show(),
1141
            IdentityCmd::Export { path } => identity::export(path),
1142
            IdentityCmd::SignChallenge { challenge, json } => {
1143
                identity::sign_challenge(&challenge, json)
1144
            }
1145
            IdentityCmd::Rotate => identity::rotate(),
1146
            IdentityCmd::Renew { expires } => identity::renew(expires),
1147
            IdentityCmd::Revoke { key, reason } => identity::revoke(key.as_deref(), &reason),
1148
            IdentityCmd::Delegate { cmd } => match cmd {
1149
                DelegateCmd::Add { identity_file } => identity::delegate_add(&identity_file),
1150
                DelegateCmd::Remove { key } => identity::delegate_remove(&key),
1151
                DelegateCmd::List => identity::delegate_list(),
1152
            },
1153
        },
1154
        Cmd::Git {
1155
            cmd: GitCmd::Export { git_dir, branch },
1156
        } => sync::git_export(&git_dir, branch.as_deref()),
1157
        Cmd::Git {
1158
            cmd: GitCmd::Fetch { url, branch },
1159
        } => sync::git_fetch(&url, &branch),
1160
        Cmd::Git {
1161
            cmd: GitCmd::Push { url, branch },
1162
        } => sync::git_push(&url, &branch),
1163
        Cmd::Git {
1164
            cmd:
1165
                GitCmd::Import {
1166
                    git_dir,
1167
                    dest,
1168
                    branch,
1169
                },
1170
        } => sync::git_import(&git_dir, &dest, &branch),
1171
        Cmd::Git {
1172
            cmd: GitCmd::Verify { git_dir, branch },
1173
        } => sync::git_verify(&git_dir, &branch),
1174
        Cmd::Policy { cmd } => match cmd {
1175
            PolicyCmd::Init => identity::policy_init(),
1176
            PolicyCmd::Show { json } => identity::policy_show(json),
1177
            PolicyCmd::Grant {
1178
                identity_file,
1179
                pattern,
1180
                out,
1181
            } => identity::policy_grant(&identity_file, pattern.as_deref(), out),
1182
            PolicyCmd::Revoke { key, out } => identity::policy_revoke(&key, out),
1183
            PolicyCmd::Root { cmd } => match cmd {
1184
                RootCmd::Add { identity_file, out } => {
1185
                    identity::policy_root_add(&identity_file, out)
1186
                }
1187
                RootCmd::Remove { key, out } => identity::policy_root_remove(&key, out),
1188
                RootCmd::Threshold { n, out } => identity::policy_threshold(n, out),
1189
            },
1190
            PolicyCmd::Sign { proposal, out } => identity::policy_sign(&proposal, out),
1191
        },
1192
        Cmd::Seal {
1193
            changes,
1194
            proposal: Some(url),
1195
            json,
1196
        } if changes.is_empty() => proposal::seal(&url, json),
1197
        Cmd::Seal { changes, json, .. } => identity::seal(&changes, json),
1198
        Cmd::Proposal { cmd } => match cmd {
1199
            ProposalCmd::Show { url, json } => proposal::show(&url, json),
1200
            ProposalCmd::Land { url, force } => proposal::land(&url, force),
1201
        },
1202
        Cmd::Verify { change, json } => identity::verify(change.as_deref(), json),
1203
        Cmd::Config { key, value, user } => identity::config(&key, &value, user),
1204
    }
1205
}
1206
1207
#[cfg(test)]
1208
mod help_tests {
1209
    use super::Cli;
1210
    use clap::CommandFactory;
1211
1212
    /// Every command and every argument explains itself, so `--help`,
1213
    /// completions and the man pages are complete.
1214
    #[test]
1215
    fn every_command_and_argument_has_help() {
1216
        fn walk(cmd: &clap::Command, path: &str, missing: &mut Vec<String>) {
1217
            let here = format!("{path} {}", cmd.get_name()).trim().to_string();
1218
            if cmd.get_about().is_none() && path != "" {
1219
                missing.push(format!("{here} (command)"));
1220
            }
1221
            for a in cmd.get_arguments() {
1222
                let id = a.get_id().as_str();
1223
                if id == "help" || id == "version" || a.is_global_set() && path != "" {
1224
                    continue;
1225
                }
1226
                if a.get_help().is_none() && a.get_long_help().is_none() {
1227
                    missing.push(format!("{here} {id}"));
1228
                }
1229
            }
1230
            for sub in cmd.get_subcommands() {
1231
                walk(sub, &here, missing);
1232
            }
1233
        }
1234
        let mut missing = Vec::new();
1235
        walk(&Cli::command(), "", &mut missing);
1236
        assert!(
1237
            missing.is_empty(),
1238
            "{} without help:\n{}",
1239
            missing.len(),
1240
            missing.join("\n")
1241
        );
1242
    }
1243
}