OXYGENHUB
# e4595038502a oxygen / src / cli / mod.rs
54.3 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
        /// Keep no past working-copy snapshots, only each workspace's current one, so files only they held go (core.snapshot-retention, default 7 days)
334
        #[arg(long)]
335
        expire_snapshots: bool,
336
        /// Instead: fold the bundles of a remote kept on a store into one, and remove the ones a gc superseded 7 days ago (or now, with --now)
337
        #[arg(long, value_name = "NAME")]
338
        remote: Option<String>,
339
    },
340
    /// List operations
341
    #[command(name = "op")]
342
    Op {
343
        #[command(subcommand)]
344
        cmd: OpCmd,
345
    },
346
    /// Take the advisory local lock on a lockable file, making it writable
347
    Lock {
348
        /// The lockable file
349
        path: String,
350
    },
351
    /// Release the local lock and make the file read-only again
352
    Unlock {
353
        /// The locked file
354
        path: String,
355
    },
356
    /// Workspaces: extra checkout directories sharing this repository
357
    Workspace {
358
        #[command(subcommand)]
359
        cmd: WorkspaceCmd,
360
    },
361
    /// Bookmarks: named states; each workspace works on one
362
    Bookmark {
363
        #[command(subcommand)]
364
        cmd: BookmarkCmd,
365
    },
366
    /// Union another bookmark's heads into the current one (no merge change)
367
    Merge {
368
        /// The bookmark whose heads to add
369
        bookmark: String,
370
    },
371
    /// Sign in to a hub once, for every repository on it
372
    Auth {
373
        #[command(subcommand)]
374
        cmd: AuthCmd,
375
    },
376
    /// Subrepositories: nested repositories pinned to a state
377
    Submodule {
378
        #[command(subcommand)]
379
        cmd: SubmoduleCmd,
380
    },
381
    /// Execution receipts: signed records of what a runner ran on a state
382
    Receipt {
383
        #[command(subcommand)]
384
        cmd: ReceiptCmd,
385
    },
386
    /// Tags: immutable named states
387
    Tag {
388
        #[command(subcommand)]
389
        cmd: TagCmd,
390
    },
391
    /// Manage remotes
392
    Remote {
393
        #[command(subcommand)]
394
        cmd: RemoteCmd,
395
    },
396
    /// Fetch every bookmark of a remote into its tracking references
397
    Fetch {
398
        /// Remote name (default: origin)
399
        remote: Option<String>,
400
        /// Machine-readable output: one JSON document on stdout
401
        #[arg(long)]
402
        json: bool,
403
    },
404
    /// Fetch, then union the remote bookmark into the local one (no merge change)
405
    Pull {
406
        /// Remote name (default: origin)
407
        remote: Option<String>,
408
        /// Machine-readable output: one JSON document on stdout
409
        #[arg(long)]
410
        json: bool,
411
    },
412
    /// Push the current bookmark to a remote
413
    Push {
414
        /// Remote name (default: origin)
415
        remote: Option<String>,
416
        /// Allow dropping heads the remote has
417
        #[arg(long)]
418
        force: bool,
419
        /// Push this bookmark instead of the workspace's current one
420
        #[arg(short = 'b', long)]
421
        bookmark: Option<String>,
422
        /// Delete this bookmark on the remote (never its default bookmark);
423
        /// the local bookmark is kept
424
        #[arg(long, value_name = "NAME", conflicts_with_all = ["bookmark", "force"])]
425
        delete: Option<String>,
426
        /// Machine-readable output: one JSON document on stdout
427
        #[arg(long)]
428
        json: bool,
429
    },
430
    /// Serve repositories under ROOT over HTTPS (with --tls-cert/--tls-key) or plain HTTP
431
    Serve {
432
        /// Directory with one repository per subdirectory
433
        #[arg(long, default_value = ".")]
434
        root: PathBuf,
435
        /// Address and port to listen on
436
        #[arg(long, default_value = "127.0.0.1:8890")]
437
        bind: String,
438
        /// Bearer token allowed to push (repeatable); none means open
439
        #[arg(long = "token")]
440
        tokens: Vec<String>,
441
        /// PEM certificate chain; enables HTTPS together with --tls-key
442
        #[arg(long, requires = "tls_key")]
443
        tls_cert: Option<PathBuf>,
444
        /// PEM private key
445
        #[arg(long, requires = "tls_cert")]
446
        tls_key: Option<PathBuf>,
447
    },
448
    /// Manage the signing identity
449
    Identity {
450
        #[command(subcommand)]
451
        cmd: IdentityCmd,
452
    },
453
    /// Seal changes with your key: named ones, or every change on the current bookmark you can authenticate but have not
454
    Seal {
455
        /// Changes to seal (default: every change on the bookmark you can authenticate and have not sealed)
456
        changes: Vec<String>,
457
        /// Seal every change of a hub proposal and push the seal (your approval)
458
        #[arg(long, conflicts_with = "changes")]
459
        proposal: Option<String>,
460
        /// Approve a job of a hub run that waits for a sealed approval: `--flow https://hub/OWNER/NAME/flow/N --job apply`
461
        #[arg(long, conflicts_with_all = ["changes", "proposal"], requires = "job")]
462
        flow: Option<String>,
463
        /// The job to approve, with --flow
464
        #[arg(long, requires = "flow")]
465
        job: Option<String>,
466
        /// Reject the job instead of approving it, with --flow
467
        #[arg(long, requires = "flow")]
468
        reject: bool,
469
        /// Machine-readable output: one JSON document on stdout
470
        #[arg(long)]
471
        json: bool,
472
    },
473
    /// Hub proposals: show one, or land it from this client
474
    Proposal {
475
        #[command(subcommand)]
476
        cmd: ProposalCmd,
477
    },
478
    /// Verify the signatures on a change (default: every change in the log)
479
    Verify {
480
        /// The change to verify (default: every change in the log)
481
        change: Option<String>,
482
        /// Verify every change a revset selects: `release..main & unsigned()`
483
        #[arg(short = 'r', long, value_name = "REVSET", conflicts_with = "change")]
484
        revset: Option<String>,
485
        /// Machine-readable output: one JSON document on stdout
486
        #[arg(long)]
487
        json: bool,
488
    },
489
    /// Git interoperability
490
    Git {
491
        #[command(subcommand)]
492
        cmd: GitCmd,
493
    },
494
    /// Manage the trust policy (who may update which bookmarks)
495
    Policy {
496
        #[command(subcommand)]
497
        cmd: PolicyCmd,
498
    },
499
    /// 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)
500
    Config {
501
        /// The key, such as author.name or remote.origin.token
502
        key: String,
503
        /// The value to set (none with --unset)
504
        #[arg(required_unless_present = "unset")]
505
        value: Option<String>,
506
        /// Write to the user file (~/.config/oxy/config.toml) instead of this repository
507
        #[arg(long)]
508
        user: bool,
509
        /// Remove the key from this repository's file (or the user file with --user)
510
        #[arg(long)]
511
        unset: bool,
512
    },
513
}
514
515
#[derive(Subcommand)]
516
enum OpCmd {
517
    /// List operations, newest first, with what each changed
518
    Log {
519
        /// Show only the latest N (snapshots folded together count as one)
520
        #[arg(short = 'n', long)]
521
        limit: Option<usize>,
522
        /// Machine-readable output: one JSON document on stdout
523
        #[arg(long)]
524
        json: bool,
525
    },
526
    /// Go back to the bookmarks and working copy as they were after OP (recorded as a new operation, so it can be undone)
527
    Restore {
528
        /// The operation: an ID prefix from oxy op log, @ or @-
529
        op: String,
530
        /// Throw away uncommitted working-copy changes
531
        #[arg(long)]
532
        discard: bool,
533
    },
534
    /// Undo OP alone, keeping every operation after it: the bookmarks it moved go back
535
    Revert {
536
        /// The operation: an ID prefix from oxy op log
537
        op: String,
538
    },
539
}
540
541
#[derive(Subcommand)]
542
enum WorkspaceCmd {
543
    /// Create a workspace at PATH checked out on CHANGE... (default: the bookmark heads)
544
    Add {
545
        /// Directory for the new workspace (must be empty or absent)
546
        path: PathBuf,
547
        /// Changes whose state to check out there
548
        changes: Vec<String>,
549
    },
550
    /// List workspaces and their working-copy changes
551
    List {
552
        /// Machine-readable output: one JSON document on stdout
553
        #[arg(long)]
554
        json: bool,
555
    },
556
    /// Stop tracking a workspace (by id prefix or path); its files stay
557
    Forget {
558
        /// Workspace id prefix or path
559
        workspace: String,
560
    },
561
}
562
563
#[derive(Subcommand)]
564
enum BisectCmd {
565
    /// Begin; remembers where the working copy was
566
    Start,
567
    /// Mark CHANGE... (or the state under test) as good
568
    Good {
569
        /// Changes known to be good (default: the state under test)
570
        changes: Vec<String>,
571
    },
572
    /// Mark CHANGE... (or the state under test) as bad
573
    Bad {
574
        /// Changes known to be bad (default: the state under test)
575
        changes: Vec<String>,
576
    },
577
    /// The state under test cannot be tested; try another
578
    Skip,
579
    /// Run a command for each step: exit 0 good, 125 skip, else bad
580
    Run {
581
        /// Command and arguments to run at each step
582
        #[arg(required = true, trailing_var_arg = true)]
583
        command: Vec<String>,
584
    },
585
    /// Where the search stands
586
    Status {
587
        /// Machine-readable output: one JSON document on stdout
588
        #[arg(long)]
589
        json: bool,
590
    },
591
    /// Restore the working copy and forget the search
592
    Reset,
593
}
594
595
#[derive(Subcommand)]
596
enum BookmarkCmd {
597
    /// Create a bookmark at CHANGE... (default: the working copy's base)
598
    Create {
599
        /// Name of the new bookmark
600
        name: String,
601
        /// Its heads (default: the working copy's base). A state is its
602
        /// heads and what they depend on: a change alone may leave out
603
        /// earlier changes of the current state, which is refused unless
604
        /// --upto or --only says which is meant
605
        changes: Vec<String>,
606
        /// Everything of the current state up to CHANGE..., as a Git
607
        /// branch at a commit would hold
608
        #[arg(long, conflicts_with = "only")]
609
        upto: bool,
610
        /// Just CHANGE... and what they depend on
611
        #[arg(long)]
612
        only: bool,
613
    },
614
    /// Point an existing bookmark at CHANGE...
615
    Set {
616
        /// The bookmark to move
617
        name: String,
618
        /// Its new heads. A change alone may leave out changes the
619
        /// bookmark now holds that were recorded before it, which is
620
        /// refused unless --upto or --only says which is meant
621
        changes: Vec<String>,
622
        /// Everything the bookmark holds up to CHANGE..., as a Git branch
623
        /// moved to a commit would hold
624
        #[arg(long, conflicts_with = "only")]
625
        upto: bool,
626
        /// Just CHANGE... and what they depend on
627
        #[arg(long)]
628
        only: bool,
629
    },
630
    /// Remove a bookmark; its changes stay
631
    Delete {
632
        /// The bookmark to remove
633
        name: String,
634
    },
635
    /// List bookmarks with their heads and difference from origin
636
    List {
637
        /// Also list remotes' bookmarks that have no local bookmark
638
        #[arg(long, short)]
639
        all: bool,
640
        /// Each head of every bookmark, as `bookmark show` prints them
641
        #[arg(long, short)]
642
        verbose: bool,
643
        /// Machine-readable output: one JSON document on stdout
644
        #[arg(long)]
645
        json: bool,
646
    },
647
    /// A bookmark's heads: each change nothing else on it depends on,
648
    /// newest first. A bookmark name is also a revset for its heads
649
    /// (`oxy log -r NAME`, or `bookmark(NAME)` to mean only the bookmark)
650
    Show {
651
        /// The bookmark, or REMOTE/NAME (default: the current one)
652
        name: Option<String>,
653
        /// Machine-readable output: one JSON document on stdout
654
        #[arg(long)]
655
        json: bool,
656
    },
657
    /// Make NAME this workspace's bookmark and check it out. Uncommitted work stops it; --carry takes the work along, --discard drops it
658
    Switch {
659
        /// The bookmark to work on; one only a remote has (NAME or REMOTE/NAME) is created from it
660
        name: String,
661
        /// Throw away uncommitted working-copy changes
662
        #[arg(long)]
663
        discard: bool,
664
        /// Take uncommitted changes along; refused when NAME has other
665
        /// versions of the files they touch
666
        #[arg(long, conflicts_with = "discard")]
667
        carry: bool,
668
    },
669
}
670
671
#[derive(Subcommand)]
672
enum AuthCmd {
673
    /// Sign in to HUB in the browser (device sign-in) and keep the token for
674
    /// every repository there
675
    Login {
676
        /// The hub, as https://oxygenhub.io or oxygenhub.io (default: this checkout's origin)
677
        hub: Option<String>,
678
        /// Read a token from standard input instead (for CI and scripts)
679
        #[arg(long)]
680
        with_token: bool,
681
        /// PEM file of extra roots to trust (a hub with a self-signed certificate)
682
        #[arg(long)]
683
        ca: Option<PathBuf>,
684
    },
685
    /// List the hubs you are signed in to, checking each token with its hub
686
    Status,
687
    /// Forget HUB's token and revoke it on the hub
688
    Logout {
689
        /// The hub (default: this checkout's origin, or the only one)
690
        hub: Option<String>,
691
    },
692
}
693
694
#[derive(Subcommand)]
695
enum SubmoduleCmd {
696
    /// Clone URL (Oxygen or Git) into PATH and register it in .oxymodules
697
    Add {
698
        /// URL or path of the Oxygen or Git repository
699
        url: String,
700
        /// Where to put it, relative to the repository root
701
        path: String,
702
        /// Bookmark (Oxygen) or branch (Git) to check out and track
703
        #[arg(long)]
704
        bookmark: Option<String>,
705
    },
706
    /// Bring nested repositories to their pins
707
    Update {
708
        /// Clone nested repositories that are absent
709
        #[arg(long)]
710
        init: bool,
711
        /// Subrepos to update (default: all)
712
        paths: Vec<String>,
713
    },
714
    /// List subrepos with their pins and on-disk state
715
    Status {
716
        /// Machine-readable output: one JSON document on stdout
717
        #[arg(long)]
718
        json: bool,
719
    },
720
    /// Unregister PATH; the directory stays, the node goes with the next commit
721
    Remove {
722
        /// The subrepo to unregister
723
        path: String,
724
    },
725
}
726
727
#[derive(Subcommand)]
728
enum ReceiptCmd {
729
    /// The receipts kept for a state (default: the bookmark heads)
730
    List {
731
        /// Change, bookmark or tag whose state to look at
732
        rev: Option<String>,
733
        /// Machine-readable output: one JSON document on stdout
734
        #[arg(long)]
735
        json: bool,
736
    },
737
    /// One receipt in full, and whether its signature verifies
738
    Show {
739
        /// The receipt (a prefix of its hash, as `list` shows it)
740
        receipt: String,
741
        /// Change, bookmark or tag whose state holds it
742
        #[arg(long)]
743
        rev: Option<String>,
744
        /// Machine-readable output: one JSON document on stdout
745
        #[arg(long)]
746
        json: bool,
747
    },
748
    /// Write a signed receipt to FILE
749
    Export {
750
        /// The receipt (a prefix of its hash, as `list` shows it)
751
        receipt: String,
752
        /// Where to write it
753
        file: String,
754
        /// Change, bookmark or tag whose state holds it
755
        #[arg(long)]
756
        rev: Option<String>,
757
        /// `oxygen`: the runner's signed receipt, as `verify` and `import`
758
        /// read it. `slsa`: SLSA provenance in a DSSE envelope, signed with
759
        /// your key, for in-toto and cosign (`oxy identity export --pem`
760
        /// gives the key they check it with)
761
        #[arg(long, default_value = "oxygen", value_parser = ["oxygen", "slsa"])]
762
        format: String,
763
    },
764
    /// Check a signed receipt in FILE without keeping it
765
    Verify {
766
        /// A signed receipt, as a runner or `export` writes it
767
        file: String,
768
        /// Machine-readable output: one JSON document on stdout
769
        #[arg(long)]
770
        json: bool,
771
    },
772
    /// Verify a signed receipt in FILE and keep it with its state
773
    Import {
774
        /// A signed receipt, as a runner or `export` writes it
775
        file: String,
776
    },
777
}
778
779
#[derive(Subcommand)]
780
enum TagCmd {
781
    /// Tag the state of CHANGE... (default: the bookmark heads)
782
    Create {
783
        /// Name of the tag; tags never move
784
        name: String,
785
        /// Changes whose state to tag (default: the bookmark heads)
786
        changes: Vec<String>,
787
        /// A message recorded with the tag
788
        #[arg(short, long, default_value = "")]
789
        message: String,
790
    },
791
    /// List tags and the states they name
792
    List {
793
        /// Machine-readable output: one JSON document on stdout
794
        #[arg(long)]
795
        json: bool,
796
    },
797
}
798
799
#[derive(Subcommand)]
800
enum RemoteCmd {
801
    /// Add a remote
802
    Add {
803
        /// Name to refer to the remote by, such as origin
804
        name: String,
805
        /// 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
806
        url: String,
807
        /// For an s3:// store: the AWS profile to use (default: AWS_PROFILE, else "default")
808
        #[arg(long)]
809
        profile: Option<String>,
810
        /// For an s3:// store: its region (default: the environment, the profile, else asked of S3)
811
        #[arg(long)]
812
        region: Option<String>,
813
        /// For an s3://, gs:// or az:// store: another endpoint, such as an S3-compatible service
814
        #[arg(long)]
815
        endpoint: Option<String>,
816
        /// For a gs:// store: a service account key file, or application default credentials
817
        #[arg(long)]
818
        credentials: Option<String>,
819
    },
820
    /// Check a remote: that it is reachable with the credentials in hand, what it holds, and (for a store) that it behaves
821
    Check {
822
        /// The remote to check
823
        name: String,
824
    },
825
    /// Remove a remote
826
    Remove {
827
        /// The remote to remove
828
        name: String,
829
    },
830
    /// List remotes and their URLs
831
    List {
832
        /// Machine-readable output: one JSON document on stdout
833
        #[arg(long)]
834
        json: bool,
835
    },
836
}
837
838
#[derive(Subcommand)]
839
enum ProposalCmd {
840
    /// Show a proposal by its hub URL
841
    Show {
842
        /// The proposal's URL on the hub
843
        url: String,
844
        /// Machine-readable output: one JSON document on stdout
845
        #[arg(long)]
846
        json: bool,
847
    },
848
    /// Fetch the proposal's changes, set the target bookmark to the projected state, and push with your key
849
    Land {
850
        /// The proposal's URL on the hub
851
        url: String,
852
        /// Land even when the hub reports blockers
853
        #[arg(long)]
854
        force: bool,
855
    },
856
}
857
858
#[derive(Subcommand)]
859
enum IdentityCmd {
860
    /// Generate a composite Ed25519 + ML-DSA-65 key pair and make it your author identity
861
    Create {
862
        /// Your name (default: author.name)
863
        #[arg(long)]
864
        name: Option<String>,
865
        /// Your email (default: author.email)
866
        #[arg(long)]
867
        email: Option<String>,
868
        /// Record the author in this repository only, not in the user config
869
        #[arg(long)]
870
        local: bool,
871
        /// Expire the identity this many days from now
872
        #[arg(long)]
873
        expires: Option<u64>,
874
    },
875
    /// Show the configured identity
876
    Show,
877
    /// Write your identity object to a file, to hand to a policy holder
878
    Export {
879
        /// File to write (default: <key>.identity, or <key>.pem with --pem, in the current directory)
880
        path: Option<PathBuf>,
881
        /// Write the Ed25519 public key as PEM instead, as cosign's --key and
882
        /// other DSSE verifiers take it
883
        #[arg(long)]
884
        pem: bool,
885
    },
886
    /// Sign a host's challenge (hex, at least 16 bytes) to prove you hold your key; prints the signature as hex
887
    SignChallenge {
888
        /// The host's challenge, as hex
889
        challenge: String,
890
        /// Machine-readable output: one JSON document on stdout
891
        #[arg(long)]
892
        json: bool,
893
    },
894
    /// Move to a fresh key pair; the policy follows if it names your key
895
    Rotate,
896
    /// Re-issue your identity with a new expiry (in days from now; 0 = never)
897
    Renew {
898
        /// Days from now until it expires; 0 for never
899
        #[arg(long)]
900
        expires: u64,
901
    },
902
    /// Revoke a key: yours by default, or any key if you hold a policy root
903
    Revoke {
904
        /// KeyId prefix (default: your own key)
905
        key: Option<String>,
906
        /// Why, recorded in the revocation
907
        #[arg(long, default_value = "")]
908
        reason: String,
909
    },
910
    /// Keys allowed to sign or seal on your behalf
911
    Delegate {
912
        #[command(subcommand)]
913
        cmd: DelegateCmd,
914
    },
915
}
916
917
#[derive(Subcommand)]
918
enum DelegateCmd {
919
    /// Add a delegate from an exported identity file
920
    Add {
921
        /// The delegates' exported identity files: one rotation for all of them
922
        #[arg(required = true)]
923
        identity_file: Vec<PathBuf>,
924
        /// What it may do for you: changes, refs, seal (comma-separated) or all.
925
        /// An agent gets `changes`; a host that lands for you needs `changes,refs`
926
        #[arg(long, default_value = "changes")]
927
        scope: String,
928
        /// How long for: 30m, 8h, 7d, or a number of days (default: until removed)
929
        #[arg(long)]
930
        expires: Option<String>,
931
    },
932
    /// Remove a delegate by KeyId prefix
933
    Remove {
934
        /// KeyId prefix of the delegate
935
        key: String,
936
    },
937
    /// List delegates
938
    List,
939
}
940
941
#[derive(Subcommand)]
942
enum GitCmd {
943
    /// Export the current bookmark to a Git repository (created bare if absent)
944
    Export {
945
        /// Git repository to write to (created bare if absent)
946
        git_dir: PathBuf,
947
        /// Git branch to write (default: the bookmark name)
948
        #[arg(long)]
949
        branch: Option<String>,
950
    },
951
    /// Fetch a branch from a Git remote (path or URL) into the current bookmark
952
    Fetch {
953
        /// Git remote: a path or URL
954
        url: String,
955
        /// Branch to fetch
956
        #[arg(long, default_value = "main")]
957
        branch: String,
958
        /// Author your own commits (Git author email = your identity's) with your key; sets git.claim
959
        #[arg(long)]
960
        claim: bool,
961
    },
962
    /// Push the current bookmark to a branch of a Git remote (fetch first)
963
    Push {
964
        /// Git remote: a path or URL
965
        url: String,
966
        /// Branch to push to
967
        #[arg(long, default_value = "main")]
968
        branch: String,
969
    },
970
    /// Recover an import that stopped before it moved the bookmark: point the bookmark at every imported commit's change in the store, so oxy git fetch carries on from there
971
    Recover,
972
    /// Check this repository's import of a Git branch: every commit's tree must be reproduced exactly
973
    Verify {
974
        /// The Git repository the import came from
975
        git_dir: PathBuf,
976
        /// Branch that was imported
977
        #[arg(long, default_value = "main")]
978
        branch: String,
979
    },
980
    /// Import a Git branch into a new Oxygen repository at DEST
981
    Import {
982
        /// Git repository to read
983
        git_dir: PathBuf,
984
        /// Directory for the new Oxygen repository
985
        dest: PathBuf,
986
        /// Branch to import
987
        #[arg(long, default_value = "main")]
988
        branch: String,
989
        /// Author your own commits (Git author email = your identity's) with your key; sets git.claim
990
        #[arg(long)]
991
        claim: bool,
992
    },
993
}
994
995
#[derive(Subcommand)]
996
enum PolicyCmd {
997
    /// Create the initial policy with your identity as the only root
998
    Init,
999
    /// Show the current policy
1000
    Show {
1001
        /// Machine-readable output: one JSON document on stdout
1002
        #[arg(long)]
1003
        json: bool,
1004
    },
1005
    /// Allow an identity (from `oxy identity export`) to update bookmarks
1006
    Grant {
1007
        /// The identity to grant, exported with `oxy identity export`
1008
        identity_file: PathBuf,
1009
        /// Reference pattern the grant applies to (default: every bookmark)
1010
        #[arg(long)]
1011
        pattern: Option<String>,
1012
        /// Where to write the proposal when more root signatures are needed
1013
        #[arg(long)]
1014
        out: Option<PathBuf>,
1015
    },
1016
    /// Allow holders of an issuer's certificates for SUBJECT to sign (keyless)
1017
    GrantSubject {
1018
        /// Who: `repo:OWNER/NAME:bookmark:main`, `agent:NAME@ACCOUNT`; `*` matches any run of characters
1019
        subject: String,
1020
        /// The issuer's identity file, e.g. a hub's /.well-known/oxyhub-key
1021
        #[arg(long)]
1022
        issuer: PathBuf,
1023
        /// What its keys may sign: changes, refs, seal
1024
        #[arg(long, default_value = "changes,refs")]
1025
        scope: String,
1026
        /// Reference pattern the grant applies to (default: every bookmark)
1027
        #[arg(long)]
1028
        pattern: Option<String>,
1029
        /// Where to write the proposal when more root signatures are needed
1030
        #[arg(long)]
1031
        out: Option<PathBuf>,
1032
    },
1033
    /// Revoke a key (KeyId prefix of an identity in the policy)
1034
    Revoke {
1035
        /// KeyId prefix of the identity
1036
        key: String,
1037
        /// Where to write the proposal when more root signatures are needed
1038
        #[arg(long)]
1039
        out: Option<PathBuf>,
1040
    },
1041
    /// Manage root keys and the signature threshold for policy updates
1042
    Root {
1043
        #[command(subcommand)]
1044
        cmd: RootCmd,
1045
    },
1046
    /// Add your root signature to a proposal file; applies it once the threshold is met
1047
    Sign {
1048
        /// The proposal file to sign
1049
        proposal: PathBuf,
1050
        /// Where to write the proposal if it still needs signatures (default: in place)
1051
        #[arg(long)]
1052
        out: Option<PathBuf>,
1053
    },
1054
}
1055
1056
#[derive(Subcommand)]
1057
enum RootCmd {
1058
    /// Make an exported identity a root key
1059
    Add {
1060
        /// The identity to make a root, exported with `oxy identity export`
1061
        identity_file: PathBuf,
1062
        /// Where to write the proposal when more root signatures are needed
1063
        #[arg(long)]
1064
        out: Option<PathBuf>,
1065
    },
1066
    /// Remove a root key by KeyId prefix
1067
    Remove {
1068
        /// KeyId prefix of the root key
1069
        key: String,
1070
        /// Where to write the proposal when more root signatures are needed
1071
        #[arg(long)]
1072
        out: Option<PathBuf>,
1073
    },
1074
    /// Require this many root signatures on policy updates
1075
    Threshold {
1076
        /// Number of root signatures
1077
        n: u32,
1078
        /// Where to write the proposal when more root signatures are needed
1079
        #[arg(long)]
1080
        out: Option<PathBuf>,
1081
    },
1082
}
1083
1084
/// Open the repository containing the current directory.
1085
fn open() -> Result<Repo> {
1086
    let repo = Repo::open(&std::env::current_dir()?).context("opening repository")?;
1087
    match AT_OP.get().and_then(|o| o.as_deref()) {
1088
        Some(op) => Ok(repo.at_op(op)?),
1089
        None => Ok(repo),
1090
    }
1091
}
1092
1093
/// `oxy man`: every page into `dir`, or the top-level page on stdout.
1094
fn man(dir: Option<PathBuf>) -> Result<i32> {
1095
    use clap::CommandFactory;
1096
    let cmd = Cli::command();
1097
    match dir {
1098
        Some(dir) => {
1099
            std::fs::create_dir_all(&dir)?;
1100
            clap_mangen::generate_to(cmd, &dir)?;
1101
            let pages = std::fs::read_dir(&dir)?
1102
                .filter(|e| {
1103
                    e.as_ref()
1104
                        .is_ok_and(|e| e.path().extension().is_some_and(|x| x == "1"))
1105
                })
1106
                .count();
1107
            println!(
1108
                "{}",
1109
                ui::done(format!("Wrote {pages} man pages to {}", dir.display()))
1110
            );
1111
        }
1112
        None => clap_mangen::Man::new(cmd).render(&mut std::io::stdout())?,
1113
    }
1114
    Ok(0)
1115
}
1116
1117
/// Parse arguments and run; returns the process exit code.
1118
pub fn run() -> Result<i32> {
1119
    // The cloud stores (s3://, gs://, az://) for remotes kept on them.
1120
    oxy_strata::register();
1121
    let cli = Cli::parse();
1122
    ui::init(cli.plain);
1123
    AT_OP.set(cli.at_op.clone()).ok();
1124
    match cli.cmd {
1125
        Cmd::Completions { shell } => {
1126
            use clap::CommandFactory;
1127
            clap_complete::generate(shell, &mut Cli::command(), "oxy", &mut std::io::stdout());
1128
            Ok(0)
1129
        }
1130
        Cmd::Man { dir } => man(dir),
1131
        Cmd::Init { path, bare, store } => workspace::init(path, bare, store.as_deref()),
1132
        Cmd::Status { json } => workspace::status(json),
1133
        Cmd::Prompt {
1134
            format,
1135
            glyphs,
1136
            color,
1137
        } => workspace::prompt(&format, glyphs, color.as_deref()),
1138
        Cmd::Commit {
1139
            message,
1140
            file,
1141
            depends_on,
1142
            paths,
1143
            interactive,
1144
            hunks,
1145
        } => {
1146
            let message = match (message, file) {
1147
                (Some(m), _) => m,
1148
                (None, Some(f)) if f.as_os_str() == "-" => {
1149
                    let mut s = String::new();
1150
                    std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
1151
                    s
1152
                }
1153
                (None, Some(f)) => std::fs::read_to_string(&f).map_err(|e| {
1154
                    anyhow::anyhow!("reading the message from {}: {e}", f.display())
1155
                })?,
1156
                (None, None) => anyhow::bail!("a commit message is required (-m or -F)"),
1157
            };
1158
            workspace::commit(&message, &depends_on, &paths, interactive, &hunks)
1159
        }
1160
        Cmd::Cat { path, change } => workspace::cat(&path, change.as_deref()),
1161
        Cmd::Root { json } => workspace::root(json),
1162
        Cmd::Version { json } => workspace::version(json),
1163
        Cmd::Discard { paths, hunks } => workspace::discard(&paths, &hunks),
1164
        Cmd::Hunks { json } => workspace::hunks(json),
1165
        Cmd::Squash { change, into } => workspace::squash(&change, &into),
1166
        Cmd::Rebase {
1167
            change,
1168
            onto,
1169
            into_working_copy,
1170
        } => workspace::rebase(&change, &onto, into_working_copy),
1171
        Cmd::Blame { path, json } => workspace::blame(&path, json),
1172
        Cmd::Bisect { cmd } => match cmd {
1173
            BisectCmd::Start => workspace::bisect_start(),
1174
            BisectCmd::Good { changes } => workspace::bisect_mark(Some(true), &changes),
1175
            BisectCmd::Bad { changes } => workspace::bisect_mark(Some(false), &changes),
1176
            BisectCmd::Skip => workspace::bisect_mark(None, &[]),
1177
            BisectCmd::Run { command } => workspace::bisect_run(&command),
1178
            BisectCmd::Status { json } => workspace::bisect_status(json),
1179
            BisectCmd::Reset => workspace::bisect_reset(),
1180
        },
1181
        Cmd::Log {
1182
            revset,
1183
            limit,
1184
            verbose,
1185
            path,
1186
            lines,
1187
            json,
1188
        } => workspace::log(
1189
            revset.as_deref(),
1190
            limit,
1191
            verbose,
1192
            path.as_deref(),
1193
            lines.as_deref(),
1194
            json,
1195
        ),
1196
        Cmd::Diff { change, json } => workspace::diff(change.as_deref(), json),
1197
        Cmd::Describe {
1198
            message,
1199
            change,
1200
            json,
1201
        } => match message {
1202
            Some(m) => workspace::describe(&m, change.as_deref()),
1203
            None if change.is_some() => {
1204
                anyhow::bail!(
1205
                    "naming works on the working copy; to change a head's message pass -m"
1206
                )
1207
            }
1208
            None => workspace::describe_name(json),
1209
        },
1210
        Cmd::Amend { message, into } => workspace::amend(message.as_deref(), into.as_deref()),
1211
        Cmd::Split { change, paths } => workspace::split(&change, &paths),
1212
        Cmd::Abandon {
1213
            change,
1214
            revset,
1215
            yes,
1216
        } => workspace::abandon(change.as_deref(), revset.as_deref(), yes),
1217
        Cmd::Show {
1218
            change,
1219
            revset,
1220
            json,
1221
        } => workspace::show(change.as_deref(), revset.as_deref(), json),
1222
        Cmd::Checkout {
1223
            changes,
1224
            discard,
1225
            carry,
1226
        } => workspace::checkout(&changes, discard, carry),
1227
        Cmd::Resolve { json } => workspace::resolve(json),
1228
        Cmd::Undo => workspace::undo(),
1229
        Cmd::Gc {
1230
            now,
1231
            expire_snapshots,
1232
            remote,
1233
        } => match remote {
1234
            Some(name) => workspace::gc_remote(&name, now),
1235
            None => workspace::gc(now, expire_snapshots),
1236
        },
1237
        Cmd::Fsck { json } => workspace::fsck(json),
1238
        Cmd::Doctor { offline, json } => workspace::doctor(offline, json),
1239
        Cmd::Checkpoint => workspace::checkpoint(),
1240
        Cmd::Op { cmd } => match cmd {
1241
            OpCmd::Log { limit, json } => workspace::op_log(limit, json),
1242
            OpCmd::Restore { op, discard } => workspace::op_restore(&op, discard),
1243
            OpCmd::Revert { op } => workspace::op_revert(&op),
1244
        },
1245
        Cmd::Clone {
1246
            url,
1247
            dest,
1248
            max_blob,
1249
            sparse,
1250
            depth,
1251
            recursive,
1252
        } => sync::clone(&url, dest, max_blob.as_deref(), &sparse, depth, recursive),
1253
        Cmd::Deepen { depth, remote } => sync::deepen(&remote, depth),
1254
        Cmd::Sparse { paths } => workspace::sparse(&paths),
1255
        Cmd::Lock { path } => workspace::lock(&path),
1256
        Cmd::Unlock { path } => workspace::unlock(&path),
1257
        Cmd::Workspace { cmd } => match cmd {
1258
            WorkspaceCmd::Add { path, changes } => workspace::workspace_add(&path, &changes),
1259
            WorkspaceCmd::List { json } => workspace::workspace_list(json),
1260
            WorkspaceCmd::Forget { workspace } => workspace::workspace_forget(&workspace),
1261
        },
1262
        Cmd::Bookmark { cmd } => match cmd {
1263
            BookmarkCmd::Create {
1264
                name,
1265
                changes,
1266
                upto,
1267
                only,
1268
            } => workspace::bookmark_create(&name, &changes, upto, only),
1269
            BookmarkCmd::Set {
1270
                name,
1271
                changes,
1272
                upto,
1273
                only,
1274
            } => workspace::bookmark_set(&name, &changes, upto, only),
1275
            BookmarkCmd::Delete { name } => workspace::bookmark_delete(&name),
1276
            BookmarkCmd::List { all, verbose, json } => {
1277
                workspace::bookmark_list(all, verbose, json)
1278
            }
1279
            BookmarkCmd::Show { name, json } => workspace::bookmark_show(name.as_deref(), json),
1280
            BookmarkCmd::Switch {
1281
                name,
1282
                discard,
1283
                carry,
1284
            } => workspace::bookmark_switch(&name, discard, carry),
1285
        },
1286
        Cmd::Merge { bookmark } => workspace::merge(&bookmark),
1287
        Cmd::Auth { cmd } => match cmd {
1288
            AuthCmd::Login {
1289
                hub,
1290
                with_token,
1291
                ca,
1292
            } => auth::login(hub.as_deref(), with_token, ca),
1293
            AuthCmd::Status => auth::status(),
1294
            AuthCmd::Logout { hub } => auth::logout(hub.as_deref()),
1295
        },
1296
        Cmd::Submodule { cmd } => match cmd {
1297
            SubmoduleCmd::Add {
1298
                url,
1299
                path,
1300
                bookmark,
1301
            } => sync::submodule_add(&url, &path, bookmark.as_deref()),
1302
            SubmoduleCmd::Update { init, paths } => sync::submodule_update(init, &paths),
1303
            SubmoduleCmd::Status { json } => sync::submodule_status(json),
1304
            SubmoduleCmd::Remove { path } => sync::submodule_remove(&path),
1305
        },
1306
        Cmd::Receipt { cmd } => match cmd {
1307
            ReceiptCmd::List { rev, json } => receipt::list(rev.as_deref(), json),
1308
            ReceiptCmd::Show {
1309
                receipt: r,
1310
                rev,
1311
                json,
1312
            } => receipt::show(&r, rev.as_deref(), json),
1313
            ReceiptCmd::Export {
1314
                receipt: r,
1315
                file,
1316
                rev,
1317
                format,
1318
            } => receipt::export(&r, &file, rev.as_deref(), &format),
1319
            ReceiptCmd::Verify { file, json } => receipt::verify(&file, json),
1320
            ReceiptCmd::Import { file } => receipt::import(&file),
1321
        },
1322
        Cmd::Tag { cmd } => match cmd {
1323
            TagCmd::Create {
1324
                name,
1325
                changes,
1326
                message,
1327
            } => workspace::tag_create(&name, &changes, &message),
1328
            TagCmd::List { json } => workspace::tag_list(json),
1329
        },
1330
        Cmd::Remote { cmd } => match cmd {
1331
            RemoteCmd::Add {
1332
                name,
1333
                url,
1334
                profile,
1335
                region,
1336
                endpoint,
1337
                credentials,
1338
            } => sync::remote_add(
1339
                &name,
1340
                &url,
1341
                &[
1342
                    ("profile", profile),
1343
                    ("region", region),
1344
                    ("endpoint", endpoint),
1345
                    ("credentials", credentials),
1346
                ],
1347
            ),
1348
            RemoteCmd::Check { name } => sync::remote_check(&name),
1349
            RemoteCmd::Remove { name } => sync::remote_remove(&name),
1350
            RemoteCmd::List { json } => sync::remote_list(json),
1351
        },
1352
        Cmd::Fetch { remote, json } => sync::fetch(remote.as_deref(), json),
1353
        Cmd::Pull { remote, json } => sync::pull(remote.as_deref(), json),
1354
        Cmd::Push {
1355
            remote,
1356
            force,
1357
            bookmark,
1358
            delete,
1359
            json,
1360
        } => match delete {
1361
            Some(name) => sync::push_delete(remote.as_deref(), &name, json),
1362
            None => sync::push(remote.as_deref(), force, bookmark.as_deref(), json),
1363
        },
1364
        Cmd::Serve {
1365
            root,
1366
            bind,
1367
            tokens,
1368
            tls_cert,
1369
            tls_key,
1370
        } => sync::serve(root, &bind, tokens, tls_cert.zip(tls_key)),
1371
        Cmd::Identity { cmd } => match cmd {
1372
            IdentityCmd::Create {
1373
                name,
1374
                email,
1375
                local,
1376
                expires,
1377
            } => identity::create(name, email, local, expires),
1378
            IdentityCmd::Show => identity::show(),
1379
            IdentityCmd::Export { path, pem } => identity::export(path, pem),
1380
            IdentityCmd::SignChallenge { challenge, json } => {
1381
                identity::sign_challenge(&challenge, json)
1382
            }
1383
            IdentityCmd::Rotate => identity::rotate(),
1384
            IdentityCmd::Renew { expires } => identity::renew(expires),
1385
            IdentityCmd::Revoke { key, reason } => identity::revoke(key.as_deref(), &reason),
1386
            IdentityCmd::Delegate { cmd } => match cmd {
1387
                DelegateCmd::Add {
1388
                    identity_file,
1389
                    scope,
1390
                    expires,
1391
                } => identity::delegate_add(&identity_file, &scope, expires.as_deref()),
1392
                DelegateCmd::Remove { key } => identity::delegate_remove(&key),
1393
                DelegateCmd::List => identity::delegate_list(),
1394
            },
1395
        },
1396
        Cmd::Git {
1397
            cmd: GitCmd::Export { git_dir, branch },
1398
        } => sync::git_export(&git_dir, branch.as_deref()),
1399
        Cmd::Git {
1400
            cmd: GitCmd::Fetch { url, branch, claim },
1401
        } => sync::git_fetch(&url, &branch, claim),
1402
        Cmd::Git {
1403
            cmd: GitCmd::Push { url, branch },
1404
        } => sync::git_push(&url, &branch),
1405
        Cmd::Git {
1406
            cmd: GitCmd::Recover,
1407
        } => sync::git_recover(),
1408
        Cmd::Git {
1409
            cmd:
1410
                GitCmd::Import {
1411
                    git_dir,
1412
                    dest,
1413
                    branch,
1414
                    claim,
1415
                },
1416
        } => sync::git_import(&git_dir, &dest, &branch, claim),
1417
        Cmd::Git {
1418
            cmd: GitCmd::Verify { git_dir, branch },
1419
        } => sync::git_verify(&git_dir, &branch),
1420
        Cmd::Policy { cmd } => match cmd {
1421
            PolicyCmd::Init => identity::policy_init(),
1422
            PolicyCmd::Show { json } => identity::policy_show(json),
1423
            PolicyCmd::Grant {
1424
                identity_file,
1425
                pattern,
1426
                out,
1427
            } => identity::policy_grant(&identity_file, pattern.as_deref(), out),
1428
            PolicyCmd::GrantSubject {
1429
                subject,
1430
                issuer,
1431
                scope,
1432
                pattern,
1433
                out,
1434
            } => identity::policy_grant_subject(&subject, &issuer, &scope, pattern.as_deref(), out),
1435
            PolicyCmd::Revoke { key, out } => identity::policy_revoke(&key, out),
1436
            PolicyCmd::Root { cmd } => match cmd {
1437
                RootCmd::Add { identity_file, out } => {
1438
                    identity::policy_root_add(&identity_file, out)
1439
                }
1440
                RootCmd::Remove { key, out } => identity::policy_root_remove(&key, out),
1441
                RootCmd::Threshold { n, out } => identity::policy_threshold(n, out),
1442
            },
1443
            PolicyCmd::Sign { proposal, out } => identity::policy_sign(&proposal, out),
1444
        },
1445
        Cmd::Seal {
1446
            flow: Some(url),
1447
            job: Some(job),
1448
            reject,
1449
            json,
1450
            ..
1451
        } => approve::seal(&url, &job, reject, json),
1452
        Cmd::Seal {
1453
            changes,
1454
            proposal: Some(url),
1455
            json,
1456
            ..
1457
        } if changes.is_empty() => proposal::seal(&url, json),
1458
        Cmd::Seal { changes, json, .. } => identity::seal(&changes, json),
1459
        Cmd::Proposal { cmd } => match cmd {
1460
            ProposalCmd::Show { url, json } => proposal::show(&url, json),
1461
            ProposalCmd::Land { url, force } => proposal::land(&url, force),
1462
        },
1463
        Cmd::Verify {
1464
            change,
1465
            revset,
1466
            json,
1467
        } => identity::verify(change.as_deref(), revset.as_deref(), json),
1468
        Cmd::Config {
1469
            key,
1470
            value,
1471
            user,
1472
            unset,
1473
        } => identity::config(&key, value.as_deref().unwrap_or(""), user, unset),
1474
    }
1475
}
1476
1477
#[cfg(test)]
1478
mod help_tests {
1479
    use super::Cli;
1480
    use clap::CommandFactory;
1481
1482
    /// Every command and every argument explains itself, so `--help`,
1483
    /// completions and the man pages are complete.
1484
    #[test]
1485
    fn every_command_and_argument_has_help() {
1486
        fn walk(cmd: &clap::Command, path: &str, missing: &mut Vec<String>) {
1487
            let here = format!("{path} {}", cmd.get_name()).trim().to_string();
1488
            if cmd.get_about().is_none() && path != "" {
1489
                missing.push(format!("{here} (command)"));
1490
            }
1491
            for a in cmd.get_arguments() {
1492
                let id = a.get_id().as_str();
1493
                if id == "help" || id == "version" || a.is_global_set() && path != "" {
1494
                    continue;
1495
                }
1496
                if a.get_help().is_none() && a.get_long_help().is_none() {
1497
                    missing.push(format!("{here} {id}"));
1498
                }
1499
            }
1500
            for sub in cmd.get_subcommands() {
1501
                walk(sub, &here, missing);
1502
            }
1503
        }
1504
        let mut missing = Vec::new();
1505
        walk(&Cli::command(), "", &mut missing);
1506
        assert!(
1507
            missing.is_empty(),
1508
            "{} without help:\n{}",
1509
            missing.len(),
1510
            missing.join("\n")
1511
        );
1512
    }
1513
}