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