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