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