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