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