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