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