OXYGENHUB

Coverage / src/cli/mod.rs 60.6%

231 of 381 lines run, 9 of 18 functions · run #420 on main · run missed

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 mcp;
10
mod proposal;
11
mod receipt;
12
mod sync;
13
mod tlog;
14
pub mod ui;
15
mod workspace;
16
17
use anyhow::{Context, Result};
18
use clap::{Parser, Subcommand};
19
use oxy_core::repo::Repo;
20
use std::path::PathBuf;
21
22
#[derive(Parser)]
23
#[command(
24
    name = "oxy",
25
    version = env!("OXY_VERSION_LONG"),
26
    about = "Oxygen: breathing fresh air into version control"
27
)]
28
struct Cli {
29
    /// Plain output: no colour, no spinner (also implied by NO_COLOR or a non-terminal)
30
    #[arg(long, global = true)]
31
    plain: bool,
32
    /// Read the repository as it was after operation OP (an ID from oxy op log, @ or @-); commands that would change it are refused
33
    #[arg(long, global = true, value_name = "OP")]
34
    at_op: Option<String>,
35
    #[command(subcommand)]
36
    cmd: Cmd,
37
}
38
39
/// `--at-op`, for `open` to apply.
40
static AT_OP: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
41
42
#[derive(Subcommand)]
43
enum Cmd {
44
    /// Create a repository in PATH (default: current directory)
45
    Init {
46
        /// Directory to create the repository in (default: the current directory)
47
        path: Option<PathBuf>,
48
        /// No working copy: an object store and references only, for hosting
49
        #[arg(long)]
50
        bare: bool,
51
        /// Keep the objects and the operation log on this store
52
        /// (dir://PATH, s3://BUCKET/PREFIX, gs://…, az://…) instead of
53
        /// in .oxy, with a local cache in front (storage.cache, 2 GiB)
54
        #[arg(long, value_name = "URL")]
55
        store: Option<String>,
56
    },
57
    /// Clone a repository from a local path or an http(s) URL
58
    Clone {
59
        /// Local path or http(s) URL of the repository
60
        url: String,
61
        /// Directory to clone into (default: the last part of the URL)
62
        dest: Option<PathBuf>,
63
        /// Leave blobs larger than this (e.g. 1M) to be fetched on first read
64
        #[arg(long)]
65
        max_blob: Option<String>,
66
        /// Materialize only these paths (repeatable); implies lazy blobs
67
        #[arg(long = "sparse")]
68
        sparse: Vec<String>,
69
        /// Shallow clone: fetch only this many levels of history below the heads
70
        #[arg(long)]
71
        depth: Option<u32>,
72
        /// Clone the subrepos too (as oxy submodule update --init)
73
        #[arg(long)]
74
        recursive: bool,
75
    },
76
    /// Fetch more history below a shallow clone's boundary
77
    Deepen {
78
        /// Levels of history to add below the boundary
79
        #[arg(default_value_t = 10)]
80
        depth: u32,
81
        /// Remote to fetch the history from
82
        #[arg(long, default_value = "origin")]
83
        remote: String,
84
    },
85
    /// Show or set the sparse filter (paths to materialize); re-checks out the bookmark
86
    Sparse {
87
        /// Paths to materialize; none prints the current filter
88
        paths: Vec<String>,
89
    },
90
    /// Show the working copy: changed paths and conflicts
91
    Status {
92
        /// Machine-readable output: paths, and every conflict with its kind and contributing changes
93
        #[arg(long)]
94
        json: bool,
95
    },
96
    /// One-line summary for shell prompts; fast and records nothing
97
    Prompt {
98
        /// 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
99
        #[arg(long, default_value = oxy_core::repo::DEFAULT_PROMPT_FORMAT)]
100
        format: String,
101
        /// Glyph format (%i %b %c %s%U%O) instead of the plain default
102
        #[arg(long)]
103
        glyphs: bool,
104
        /// Colour by state (cyan clean, yellow dirty, red conflicted): raw escapes, or guarded for a bash or zsh PS1
105
        #[arg(long, value_parser = ["raw", "bash", "zsh"])]
106
        color: Option<String>,
107
    },
108
    /// Record the working copy as a change on the current bookmark
109
    Commit {
110
        /// The change's message: a subject line, then optionally a blank line and a body
111
        #[arg(short, long, required_unless_present = "file", conflicts_with = "file")]
112
        message: Option<String>,
113
        /// Read the message from FILE (`-` for standard input)
114
        #[arg(short = 'F', long, value_name = "FILE")]
115
        file: Option<PathBuf>,
116
        /// Extra explicit dependencies (ChangeId prefix, #hash prefix)
117
        #[arg(long = "depends-on")]
118
        depends_on: Vec<String>,
119
        /// Commit only these paths; the rest stays as uncommitted work
120
        paths: Vec<String>,
121
        /// Choose hunks one by one
122
        #[arg(short, long)]
123
        interactive: bool,
124
        /// Commit these hunks (as `oxy hunks` numbers them), comma separated
125
        #[arg(long, value_delimiter = ',')]
126
        hunks: Vec<usize>,
127
    },
128
    /// Fold CHANGE into one of its dependencies (keeps that change's id)
129
    Squash {
130
        /// The change to fold (ChangeId prefix, #hash prefix)
131
        change: String,
132
        /// The dependency that absorbs it
133
        #[arg(long)]
134
        into: String,
135
    },
136
    /// Re-express CHANGE against another base state
137
    Rebase {
138
        /// The change to re-express (ChangeId prefix, #hash prefix)
139
        change: String,
140
        /// The changes, bookmark or tag whose state becomes the new base
141
        #[arg(long, required = true, num_args = 1..)]
142
        onto: Vec<String>,
143
        /// Where the rebase would be conflicted, merge the target into the
144
        /// current bookmark instead, leaving the conflict in the working
145
        /// copy to fix and commit
146
        #[arg(long)]
147
        into_working_copy: bool,
148
    },
149
    /// Show which change introduced each line of a file
150
    Blame {
151
        /// File to annotate, relative to the repository root
152
        path: String,
153
        /// Machine-readable output: one JSON document on stdout
154
        #[arg(long)]
155
        json: bool,
156
    },
157
    /// Find the change that introduced a regression
158
    Bisect {
159
        #[command(subcommand)]
160
        cmd: BisectCmd,
161
    },
162
    /// List changes reachable from the bookmark and the working copy
163
    Log {
164
        /// Show the changes a revset selects: `main` (a bookmark name means its
165
        /// heads; `bookmark(main)` only ever the bookmark), `main..feature &
166
        /// author(andy)`, `touches("src/**") & date(-7d..)` (see
167
        /// docs/revset_query_language.md)
168
        #[arg(short = 'r', long, value_name = "REVSET", conflicts_with_all = ["path", "lines"])]
169
        revset: Option<String>,
170
        /// Show at most this many changes
171
        #[arg(short = 'n', long)]
172
        limit: Option<usize>,
173
        /// Show full messages, dependencies, and signatures
174
        #[arg(short, long)]
175
        verbose: bool,
176
        /// Only changes touching this path (renames followed)
177
        #[arg(long)]
178
        path: Option<String>,
179
        /// Only changes that wrote or deleted lines START to END of PATH
180
        /// (numbered as in the working copy's base), or deleted lines from
181
        /// between them: the history of a function
182
        #[arg(short = 'L', value_name = "START,END:PATH", conflicts_with = "path")]
183
        lines: Option<String>,
184
        /// Machine-readable output: one JSON document on stdout
185
        #[arg(long)]
186
        json: bool,
187
    },
188
    /// Show what the working copy changes against its base
189
    Diff {
190
        /// A change instead of the working copy
191
        change: Option<String>,
192
        /// Machine-readable output: one JSON document on stdout
193
        #[arg(long)]
194
        json: bool,
195
    },
196
    /// Print a file as it is in a state (default: the working copy's base)
197
    Cat {
198
        /// File to print, relative to the repository root
199
        path: String,
200
        /// A bookmark or tag (its state), or a change: a change means its
201
        /// dependency closure, the change and what it depends on, so files
202
        /// only later changes touched are absent or at older versions
203
        #[arg(short = 'r', long)]
204
        change: Option<String>,
205
    },
206
    /// Print the repository root, workspace, and bookmark
207
    Root {
208
        /// Machine-readable output: one JSON document on stdout
209
        #[arg(long)]
210
        json: bool,
211
    },
212
    /// Serve this repository to an AI agent over the Model Context Protocol (stdio), signing as this checkout's identity
213
    Mcp {
214
        /// The repository's root (default: the current directory)
215
        dir: Option<PathBuf>,
216
        /// Also offer tools that can lose work: undo, and a forced push
217
        #[arg(long)]
218
        allow_destructive: bool,
219
    },
220
    /// Print the version of oxy, its repository format, and protocol
221
    Version {
222
        /// Machine-readable output: one JSON document on stdout
223
        #[arg(long)]
224
        json: bool,
225
    },
226
    /// Restore paths to the working copy's base, or undo chosen hunks
227
    Discard {
228
        /// Paths to restore; none with --hunks, or everything with neither
229
        paths: Vec<String>,
230
        /// Hunk indices as `oxy hunks` numbers them, comma separated
231
        #[arg(long, value_delimiter = ',')]
232
        hunks: Vec<usize>,
233
    },
234
    /// List the working copy's hunks, numbered as commit --hunks expects
235
    Hunks {
236
        /// Machine-readable output: one JSON document on stdout
237
        #[arg(long)]
238
        json: bool,
239
    },
240
    /// With -m, change the message of a head; without, name the working
241
    /// copy for a build: its tag, or the nearest tag plus distance and
242
    /// change, or the bookmark and change, and -dirty
243
    Describe {
244
        /// The new message
245
        #[arg(short, long)]
246
        message: Option<String>,
247
        /// The head to describe (default: the one the working copy sits on)
248
        change: Option<String>,
249
        /// Machine-readable output (naming only)
250
        #[arg(long, conflicts_with = "message")]
251
        json: bool,
252
    },
253
    /// Fold the working copy into the head it sits on, or into CHANGE with --into
254
    Amend {
255
        /// Replace the message too
256
        #[arg(short, long)]
257
        message: Option<String>,
258
        /// Amend an older change; the edits must touch only lines it already knows
259
        #[arg(long, conflicts_with = "paths")]
260
        into: Option<String>,
261
        /// Fold in only these paths; the rest stays as uncommitted work
262
        paths: Vec<String>,
263
    },
264
    /// Split a head: the named paths become a separate first change
265
    Split {
266
        /// The head to split
267
        change: String,
268
        /// Paths whose edits become the first change
269
        paths: Vec<String>,
270
    },
271
    /// Drop a change from the bookmark; its content stays on disk as uncommitted work
272
    Abandon {
273
        /// The change to drop (ChangeId prefix, #hash prefix)
274
        #[arg(required_unless_present = "revset")]
275
        change: Option<String>,
276
        /// Drop every change a revset selects, newest first
277
        #[arg(short = 'r', long, value_name = "REVSET", conflicts_with = "change")]
278
        revset: Option<String>,
279
        /// Drop more than five changes without asking
280
        #[arg(long, short = 'y')]
281
        yes: bool,
282
    },
283
    /// Show one change (ChangeId prefix, #hash prefix, or @), or those a revset selects
284
    Show {
285
        /// ChangeId prefix, #hash prefix, or @ for the working copy
286
        #[arg(required_unless_present = "revset")]
287
        change: Option<String>,
288
        /// Show every change a revset selects
289
        #[arg(short = 'r', long, value_name = "REVSET", conflicts_with = "change")]
290
        revset: Option<String>,
291
        /// The files it touched with lines added and removed, instead of the diff
292
        #[arg(long)]
293
        stat: bool,
294
        /// Machine-readable output: one JSON document on stdout
295
        #[arg(long)]
296
        json: bool,
297
    },
298
    /// Move the working copy to the state formed by CHANGE... (default: the bookmark heads)
299
    Checkout {
300
        /// Changes whose state to check out (default: the bookmark heads)
301
        changes: Vec<String>,
302
        /// Throw away uncommitted working-copy changes
303
        #[arg(long)]
304
        discard: bool,
305
        /// Take uncommitted changes along; refused when the target has
306
        /// other versions of the files they touch
307
        #[arg(long, conflicts_with = "discard")]
308
        carry: bool,
309
    },
310
    /// Report which conflicts of the working copy's base are resolved by the current files;
311
    /// with paths, settle their replace conflicts (binary files, subrepo pins) with what the
312
    /// working copy holds there
313
    Resolve {
314
        /// Opaque files or subrepos whose replace conflict to settle with their current content;
315
        /// with --both, the text files whose conflicts to settle (all of them when none)
316
        paths: Vec<String>,
317
        /// Settle each adjacent insertion (two changes adding lines at the same place) by keeping
318
        /// every side, earliest change first; refused where the sides changed the same lines
319
        #[arg(long)]
320
        both: bool,
321
        /// With --both, the latest change first
322
        #[arg(long, requires = "both")]
323
        reverse: bool,
324
        /// Machine-readable output: one JSON document on stdout
325
        #[arg(long)]
326
        json: bool,
327
    },
328
    /// Undo the last operation
329
    Undo,
330
    /// Write a checkpoint of the current bookmark's state now
331
    Checkpoint,
332
    /// Print a shell completion script: `oxy completions bash > ~/.local/share/bash-completion/completions/oxy`
333
    Completions {
334
        /// bash, zsh, fish, elvish or powershell
335
        shell: clap_complete::Shell,
336
    },
337
    /// Write man pages (oxy.1 and one per command) into DIR, or print oxy.1
338
    Man {
339
        /// Directory to write every page into, e.g. ~/.local/share/man/man1
340
        #[arg(long)]
341
        dir: Option<PathBuf>,
342
    },
343
    /// Check the identity, configuration and remotes, and say what to do about any problem
344
    Doctor {
345
        /// Do not contact the remotes
346
        #[arg(long)]
347
        offline: bool,
348
        /// Machine-readable output: one JSON document on stdout
349
        #[arg(long)]
350
        json: bool,
351
    },
352
    /// Check the repository's integrity: objects, operation log, references, signatures, checkpoints
353
    Fsck {
354
        /// Machine-readable output: one JSON document on stdout
355
        #[arg(long)]
356
        json: bool,
357
    },
358
    /// Prune unreachable objects older than the grace period and repack everything into one pack
359
    Gc {
360
        /// Ignore the grace period (core.gc-grace) and prune immediately
361
        #[arg(long)]
362
        now: bool,
363
        /// Keep no past working-copy snapshots, only each workspace's current one, so files only they held go (core.snapshot-retention, default 7 days)
364
        #[arg(long)]
365
        expire_snapshots: bool,
366
        /// 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)
367
        #[arg(long, value_name = "NAME")]
368
        remote: Option<String>,
369
    },
370
    /// List operations
371
    #[command(name = "op")]
372
    Op {
373
        #[command(subcommand)]
374
        cmd: OpCmd,
375
    },
376
    /// Take the advisory local lock on a lockable file, making it writable
377
    Lock {
378
        /// The lockable file
379
        path: String,
380
    },
381
    /// Release the local lock and make the file read-only again
382
    Unlock {
383
        /// The locked file
384
        path: String,
385
    },
386
    /// Workspaces: extra checkout directories sharing this repository
387
    Workspace {
388
        #[command(subcommand)]
389
        cmd: WorkspaceCmd,
390
    },
391
    /// Bookmarks: named states; each workspace works on one
392
    Bookmark {
393
        #[command(subcommand)]
394
        cmd: BookmarkCmd,
395
    },
396
    /// Union another bookmark's heads into the current one (no merge change):
397
    /// a bookmark here, or a remote's (`origin/develop`) as last fetched
398
    Merge {
399
        /// The bookmark whose heads to add
400
        bookmark: String,
401
    },
402
    /// Sign in to a hub once, for every repository on it
403
    Auth {
404
        #[command(subcommand)]
405
        cmd: AuthCmd,
406
    },
407
    /// Subrepositories: nested repositories pinned to a state
408
    Submodule {
409
        #[command(subcommand)]
410
        cmd: SubmoduleCmd,
411
    },
412
    /// Witness hubs' transparency logs: cosign each checkpoint that extends
413
    /// the last one cosigned (spec §14.8)
414
    Witness {
415
        #[command(subcommand)]
416
        cmd: WitnessCmd,
417
    },
418
    /// Hubs' transparency logs: check that a hub shows everyone the same
419
    /// history (spec §14.8)
420
    Tlog {
421
        #[command(subcommand)]
422
        cmd: TlogCmd,
423
    },
424
    /// Artifacts: a directory packed into a tree of this repository's chunks (Cylinder, docs/cylinder.md)
425
    Artifact {
426
        #[command(subcommand)]
427
        cmd: ArtifactCmd,
428
    },
429
    /// Execution receipts: signed records of what a runner ran on a state
430
    Receipt {
431
        #[command(subcommand)]
432
        cmd: ReceiptCmd,
433
    },
434
    /// Tags: immutable named states
435
    Tag {
436
        #[command(subcommand)]
437
        cmd: TagCmd,
438
    },
439
    /// Manage remotes
440
    Remote {
441
        #[command(subcommand)]
442
        cmd: RemoteCmd,
443
    },
444
    /// Fetch every bookmark of a remote into its tracking references
445
    Fetch {
446
        /// Remote name (default: origin)
447
        remote: Option<String>,
448
        /// Machine-readable output: one JSON document on stdout
449
        #[arg(long)]
450
        json: bool,
451
    },
452
    /// Fetch, then union the remote bookmark into the local one (no merge change)
453
    Pull {
454
        /// Remote name (default: origin)
455
        remote: Option<String>,
456
        /// Machine-readable output: one JSON document on stdout
457
        #[arg(long)]
458
        json: bool,
459
    },
460
    /// Push the current bookmark to a remote
461
    Push {
462
        /// Remote name (default: origin)
463
        remote: Option<String>,
464
        /// Allow dropping heads the remote has
465
        #[arg(long)]
466
        force: bool,
467
        /// Push this bookmark instead of the workspace's current one
468
        #[arg(short = 'b', long)]
469
        bookmark: Option<String>,
470
        /// Delete this bookmark on the remote (never its default bookmark);
471
        /// the local bookmark is kept. `tags/NAME` withdraws a tag there
472
        /// (and here, as `oxy tag delete` does)
473
        #[arg(long, value_name = "NAME", conflicts_with_all = ["bookmark", "force"])]
474
        delete: Option<String>,
475
        /// Machine-readable output: one JSON document on stdout
476
        #[arg(long)]
477
        json: bool,
478
    },
479
    /// Serve repositories under ROOT over HTTPS (with --tls-cert/--tls-key) or plain HTTP
480
    Serve {
481
        /// Directory with one repository per subdirectory
482
        #[arg(long, default_value = ".")]
483
        root: PathBuf,
484
        /// Address and port to listen on
485
        #[arg(long, default_value = "127.0.0.1:8890")]
486
        bind: String,
487
        /// Bearer token allowed to push (repeatable); none means open
488
        #[arg(long = "token")]
489
        tokens: Vec<String>,
490
        /// PEM certificate chain; enables HTTPS together with --tls-key
491
        #[arg(long, requires = "tls_key")]
492
        tls_cert: Option<PathBuf>,
493
        /// PEM private key
494
        #[arg(long, requires = "tls_cert")]
495
        tls_key: Option<PathBuf>,
496
    },
497
    /// Manage the signing identity
498
    Identity {
499
        #[command(subcommand)]
500
        cmd: IdentityCmd,
501
    },
502
    /// Seal changes with your key: named ones, or every change on the current bookmark you can authenticate but have not
503
    Seal {
504
        /// Changes to seal (default: every change on the bookmark you can authenticate and have not sealed)
505
        changes: Vec<String>,
506
        /// Seal every change of a hub proposal and push the seal (your approval)
507
        #[arg(long, conflicts_with = "changes")]
508
        proposal: Option<String>,
509
        /// Approve a job of a hub run that waits for a sealed approval: `--flow https://hub/OWNER/NAME/flow/N --job apply`
510
        #[arg(long, conflicts_with_all = ["changes", "proposal"], requires = "job")]
511
        flow: Option<String>,
512
        /// The job to approve, with --flow
513
        #[arg(long, requires = "flow")]
514
        job: Option<String>,
515
        /// Reject the job instead of approving it, with --flow
516
        #[arg(long, requires = "flow")]
517
        reject: bool,
518
        /// Machine-readable output: one JSON document on stdout
519
        #[arg(long)]
520
        json: bool,
521
    },
522
    /// Hub proposals: show one, or land it from this client
523
    Proposal {
524
        #[command(subcommand)]
525
        cmd: ProposalCmd,
526
    },
527
    /// Verify the signatures on a change (default: every change in the log)
528
    Verify {
529
        /// The change to verify (default: every change in the log)
530
        change: Option<String>,
531
        /// Verify every change a revset selects: `release..main & unsigned()`
532
        #[arg(short = 'r', long, value_name = "REVSET", conflicts_with = "change")]
533
        revset: Option<String>,
534
        /// Machine-readable output: one JSON document on stdout
535
        #[arg(long)]
536
        json: bool,
537
    },
538
    /// Git interoperability
539
    Git {
540
        #[command(subcommand)]
541
        cmd: GitCmd,
542
    },
543
    /// Manage the trust policy (who may update which bookmarks)
544
    Policy {
545
        #[command(subcommand)]
546
        cmd: PolicyCmd,
547
    },
548
    /// Set a configuration key (author.*, core.sign, core.op-retention, core.gc-grace, core.checkpoint-interval, filter.max-blob, filter.paths, storage.cache, workspace.bookmark, remote.<name>.url|token|ca, auth.helper with --user)
549
    Config {
550
        /// The key, such as author.name or remote.origin.token
551
        key: String,
552
        /// The value to set (none with --unset); `-` reads it from standard input, out of the shell's history
553
        #[arg(required_unless_present = "unset")]
554
        value: Option<String>,
555
        /// Write to the user file (~/.config/oxy/config.toml) instead of this repository
556
        #[arg(long)]
557
        user: bool,
558
        /// Remove the key from this repository's file (or the user file with --user)
559
        #[arg(long)]
560
        unset: bool,
561
    },
562
}
563
564
#[derive(Subcommand)]
565
enum OpCmd {
566
    /// List operations, newest first, with what each changed
567
    Log {
568
        /// Show only the latest N (snapshots folded together count as one)
569
        #[arg(short = 'n', long)]
570
        limit: Option<usize>,
571
        /// Machine-readable output: one JSON document on stdout
572
        #[arg(long)]
573
        json: bool,
574
    },
575
    /// Go back to the bookmarks and working copy as they were after OP (recorded as a new operation, so it can be undone)
576
    Restore {
577
        /// The operation: an ID prefix from oxy op log, @ or @-
578
        op: String,
579
        /// Throw away uncommitted working-copy changes
580
        #[arg(long)]
581
        discard: bool,
582
    },
583
    /// Undo OP alone, keeping every operation after it: the bookmarks it moved go back
584
    Revert {
585
        /// The operation: an ID prefix from oxy op log
586
        op: String,
587
    },
588
}
589
590
#[derive(Subcommand)]
591
enum WorkspaceCmd {
592
    /// Create a workspace at PATH checked out on CHANGE... (default: the bookmark heads)
593
    Add {
594
        /// Directory for the new workspace (must be empty or absent)
595
        path: PathBuf,
596
        /// Changes whose state to check out there
597
        changes: Vec<String>,
598
    },
599
    /// List workspaces and their working-copy changes
600
    List {
601
        /// Machine-readable output: one JSON document on stdout
602
        #[arg(long)]
603
        json: bool,
604
    },
605
    /// Stop tracking a workspace (by id prefix or path); its files stay
606
    Forget {
607
        /// Workspace id prefix or path
608
        workspace: String,
609
    },
610
}
611
612
#[derive(Subcommand)]
613
enum BisectCmd {
614
    /// Begin; remembers where the working copy was
615
    Start,
616
    /// Mark CHANGE... (or the state under test) as good
617
    Good {
618
        /// Changes known to be good (default: the state under test)
619
        changes: Vec<String>,
620
    },
621
    /// Mark CHANGE... (or the state under test) as bad
622
    Bad {
623
        /// Changes known to be bad (default: the state under test)
624
        changes: Vec<String>,
625
    },
626
    /// The state under test cannot be tested; try another
627
    Skip,
628
    /// Run a command for each step: exit 0 good, 125 skip, else bad
629
    Run {
630
        /// Command and arguments to run at each step
631
        #[arg(required = true, trailing_var_arg = true)]
632
        command: Vec<String>,
633
    },
634
    /// Where the search stands
635
    Status {
636
        /// Machine-readable output: one JSON document on stdout
637
        #[arg(long)]
638
        json: bool,
639
    },
640
    /// Restore the working copy and forget the search
641
    Reset,
642
}
643
644
#[derive(Subcommand)]
645
enum BookmarkCmd {
646
    /// Create a bookmark at CHANGE... (default: the working copy's base)
647
    Create {
648
        /// Name of the new bookmark
649
        name: String,
650
        /// Its heads (default: the working copy's base). A state is its
651
        /// heads and what they depend on: a change alone may leave out
652
        /// earlier changes of the current state, which is refused unless
653
        /// --upto or --only says which is meant
654
        changes: Vec<String>,
655
        /// Everything of the current state up to CHANGE..., as a Git
656
        /// branch at a commit would hold
657
        #[arg(long, conflicts_with = "only")]
658
        upto: bool,
659
        /// Just CHANGE... and what they depend on. Other changes to the
660
        /// same files are left out, so a file can come out partly edited;
661
        /// to add one change to a bookmark's work, give the bookmark's
662
        /// heads with it instead: `bookmark set NAME <its heads> CHANGE`
663
        #[arg(long)]
664
        only: bool,
665
    },
666
    /// Point an existing bookmark at CHANGE...
667
    Set {
668
        /// The bookmark to move
669
        name: String,
670
        /// Its new heads. A change alone may leave out changes the
671
        /// bookmark now holds that were recorded before it, which is
672
        /// refused unless --upto or --only says which is meant
673
        changes: Vec<String>,
674
        /// Everything the bookmark holds up to CHANGE..., as a Git branch
675
        /// moved to a commit would hold
676
        #[arg(long, conflicts_with = "only")]
677
        upto: bool,
678
        /// Just CHANGE... and what they depend on. Other changes to the
679
        /// same files are left out, so a file can come out partly edited;
680
        /// to add one change to a bookmark's work, give the bookmark's
681
        /// heads with it instead: `bookmark set NAME <its heads> CHANGE`
682
        #[arg(long)]
683
        only: bool,
684
    },
685
    /// Remove a bookmark; its changes stay
686
    Delete {
687
        /// The bookmark to remove
688
        name: String,
689
    },
690
    /// List bookmarks with their heads and difference from origin
691
    List {
692
        /// Also list remotes' bookmarks that have no local bookmark
693
        #[arg(long, short)]
694
        all: bool,
695
        /// Each head of every bookmark, as `bookmark show` prints them
696
        #[arg(long, short)]
697
        verbose: bool,
698
        /// Machine-readable output: one JSON document on stdout
699
        #[arg(long)]
700
        json: bool,
701
    },
702
    /// A bookmark's heads: each change nothing else on it depends on,
703
    /// newest first. A bookmark name is also a revset for its heads
704
    /// (`oxy log -r NAME`, or `bookmark(NAME)` to mean only the bookmark)
705
    Show {
706
        /// The bookmark, or REMOTE/NAME (default: the current one)
707
        name: Option<String>,
708
        /// Machine-readable output: one JSON document on stdout
709
        #[arg(long)]
710
        json: bool,
711
    },
712
    /// Make NAME this workspace's bookmark and check it out. Uncommitted work stops it; --carry takes the work along, --discard drops it
713
    Switch {
714
        /// The bookmark to work on; one only a remote has (NAME or REMOTE/NAME) is created from it
715
        name: String,
716
        /// Throw away uncommitted working-copy changes
717
        #[arg(long)]
718
        discard: bool,
719
        /// Take uncommitted changes along; refused when NAME has other
720
        /// versions of the files they touch
721
        #[arg(long, conflicts_with = "discard")]
722
        carry: bool,
723
    },
724
}
725
726
#[derive(Subcommand)]
727
enum WitnessCmd {
728
    /// Serve a witness (C2SP tlog-witness: POST /add-checkpoint), signing
729
    /// with this oxy home's key (author.key)
730
    Serve {
731
        /// The witness's name in cosignatures: a host name
732
        #[arg(long)]
733
        name: String,
734
        /// A log to witness, as ORIGIN=FILE: its origin (HOST/log) and its
735
        /// key's identity file (a hub's /.well-known/oxyhub-key); repeatable
736
        #[arg(long = "log", required = true)]
737
        logs: Vec<String>,
738
        /// Where to keep what it cosigned
739
        #[arg(long, default_value = "witness-state")]
740
        state: PathBuf,
741
        /// Address and port to listen on
742
        #[arg(long, default_value = "127.0.0.1:8891")]
743
        bind: String,
744
        /// PEM certificate chain; enables HTTPS together with --tls-key
745
        #[arg(long, requires = "tls_key")]
746
        tls_cert: Option<PathBuf>,
747
        /// PEM private key for --tls-cert
748
        #[arg(long, requires = "tls_cert")]
749
        tls_key: Option<PathBuf>,
750
    },
751
}
752
753
#[derive(Subcommand)]
754
enum TlogCmd {
755
    /// Check a hub's whole log: its checkpoint against the log key and the
756
    /// last checkpoint seen, and every entry against the root it signed;
757
    /// then list this repository's entries (or a key's, or all)
758
    Verify {
759
        /// The hub, as https://oxygenhub.io (default: this checkout's remote)
760
        hub: Option<String>,
761
        /// List the entries a key signed (a KeyId) instead
762
        #[arg(long, conflicts_with = "all")]
763
        key: Option<String>,
764
        /// List every entry
765
        #[arg(long)]
766
        all: bool,
767
        /// Machine-readable output
768
        #[arg(long)]
769
        json: bool,
770
    },
771
}
772
773
#[derive(Subcommand)]
774
enum AuthCmd {
775
    /// Sign in to HUB in the browser (device sign-in) and keep the token for
776
    /// every repository there
777
    Login {
778
        /// The hub, as https://oxygenhub.io or oxygenhub.io (default: this checkout's origin)
779
        hub: Option<String>,
780
        /// Read a token from standard input instead (for CI and scripts)
781
        #[arg(long)]
782
        with_token: bool,
783
        /// PEM file of extra roots to trust (a hub with a self-signed certificate)
784
        #[arg(long)]
785
        ca: Option<PathBuf>,
786
    },
787
    /// List the hubs you are signed in to, checking each token with its hub
788
    Status,
789
    /// Forget HUB's token and revoke it on the hub
790
    Logout {
791
        /// The hub (default: this checkout's origin, or the only one)
792
        hub: Option<String>,
793
    },
794
    /// Keep an agent grant token (from `oh agent grant`) for keyless
795
    /// signing: with `author.signer = keyless`, commits and pushes are
796
    /// signed by fresh keys the hub certifies, in the grantor's name
797
    /// (the token is read from standard input, so it stays out of the
798
    /// shell's history)
799
    Grant {
800
        /// The hub (default: this checkout's origin)
801
        hub: Option<String>,
802
    },
803
}
804
805
#[derive(Subcommand)]
806
enum SubmoduleCmd {
807
    /// Clone URL (Oxygen or Git) into PATH and register it in .oxymodules
808
    Add {
809
        /// URL or path of the Oxygen or Git repository
810
        url: String,
811
        /// Where to put it, relative to the repository root
812
        path: String,
813
        /// Bookmark (Oxygen) or branch (Git) to check out and track
814
        #[arg(long)]
815
        bookmark: Option<String>,
816
    },
817
    /// Bring nested repositories to their pins
818
    Update {
819
        /// Clone nested repositories that are absent
820
        #[arg(long)]
821
        init: bool,
822
        /// Subrepos to update (default: all)
823
        paths: Vec<String>,
824
    },
825
    /// List subrepos with their pins and on-disk state
826
    Status {
827
        /// Machine-readable output: one JSON document on stdout
828
        #[arg(long)]
829
        json: bool,
830
    },
831
    /// Unregister PATH; the directory stays, the node goes with the next commit
832
    Remove {
833
        /// The subrepo to unregister
834
        path: String,
835
    },
836
}
837
838
#[derive(Subcommand)]
839
enum ArtifactCmd {
840
    /// Pack DIR into an artifact: each file a blob of this repository's store, so files and chunks it holds cost nothing
841
    Pack {
842
        /// The directory whose files make the artifact
843
        dir: std::path::PathBuf,
844
        /// container, runner-image, package, archive or report
845
        #[arg(long, default_value = "archive")]
846
        kind: String,
847
        /// x86_64, riscv64, aarch64…
848
        #[arg(long)]
849
        arch: Option<String>,
850
        /// linux, darwin, none…
851
        #[arg(long)]
852
        os: Option<String>,
853
        /// The default command, one word per flag
854
        #[arg(long = "entrypoint", value_name = "WORD")]
855
        entrypoint: Vec<String>,
856
        /// KEY=VALUE for the environment (repeatable)
857
        #[arg(long = "env", value_name = "KEY=VALUE")]
858
        env: Vec<String>,
859
        /// KEY=VALUE metadata (repeatable)
860
        #[arg(long = "label", value_name = "KEY=VALUE")]
861
        labels: Vec<String>,
862
        /// Machine-readable output: one JSON document on stdout
863
        #[arg(long)]
864
        json: bool,
865
    },
866
    /// The artifacts kept here
867
    List {
868
        /// Machine-readable output: one JSON document on stdout
869
        #[arg(long)]
870
        json: bool,
871
    },
872
    /// One artifact and its files
873
    Show {
874
        /// Its name, or a unique prefix of at least six characters
875
        name: String,
876
        /// Machine-readable output: one JSON document on stdout
877
        #[arg(long)]
878
        json: bool,
879
    },
880
    /// Write an artifact's files into DEST (missing or empty)
881
    Unpack {
882
        /// Its name, or a unique prefix of at least six characters
883
        name: String,
884
        /// Where to write its files
885
        dest: std::path::PathBuf,
886
    },
887
    /// Check an artifact's name, tree and every file against the store
888
    Verify {
889
        /// Its name, or a unique prefix of at least six characters
890
        name: String,
891
    },
892
}
893
894
#[derive(Subcommand)]
895
enum ReceiptCmd {
896
    /// The receipts kept for a state (default: the bookmark heads)
897
    List {
898
        /// Change, bookmark or tag whose state to look at
899
        rev: Option<String>,
900
        /// Machine-readable output: one JSON document on stdout
901
        #[arg(long)]
902
        json: bool,
903
    },
904
    /// One receipt in full, and whether its signature verifies
905
    Show {
906
        /// The receipt (a prefix of its hash, as `list` shows it)
907
        receipt: String,
908
        /// Change, bookmark or tag whose state holds it
909
        #[arg(long)]
910
        rev: Option<String>,
911
        /// Machine-readable output: one JSON document on stdout
912
        #[arg(long)]
913
        json: bool,
914
    },
915
    /// Write a signed receipt to FILE
916
    Export {
917
        /// The receipt (a prefix of its hash, as `list` shows it)
918
        receipt: String,
919
        /// Where to write it
920
        file: String,
921
        /// Change, bookmark or tag whose state holds it
922
        #[arg(long)]
923
        rev: Option<String>,
924
        /// `oxygen`: the runner's signed receipt, as `verify` and `import`
925
        /// read it. `slsa`: SLSA provenance in a DSSE envelope, signed with
926
        /// your key, for in-toto and cosign (`oxy identity export --pem`
927
        /// gives the key they check it with)
928
        #[arg(long, default_value = "oxygen", value_parser = ["oxygen", "slsa"])]
929
        format: String,
930
    },
931
    /// Check a signed receipt in FILE without keeping it
932
    Verify {
933
        /// A signed receipt, as a runner or `export` writes it
934
        file: String,
935
        /// Machine-readable output: one JSON document on stdout
936
        #[arg(long)]
937
        json: bool,
938
    },
939
    /// Verify a signed receipt in FILE and keep it with its state
940
    Import {
941
        /// A signed receipt, as a runner or `export` writes it
942
        file: String,
943
    },
944
}
945
946
#[derive(Subcommand)]
947
enum TagCmd {
948
    /// Tag the state of CHANGE... (default: the bookmark heads)
949
    Create {
950
        /// Name of the tag; tags never move
951
        name: String,
952
        /// Changes whose state to tag (default: the bookmark heads)
953
        changes: Vec<String>,
954
        /// A message recorded with the tag
955
        #[arg(short, long, default_value = "")]
956
        message: String,
957
    },
958
    /// Withdraw a tag: a signed withdrawal, kept beside the tag's creation;
959
    /// `oxy push` sends it to a remote that has the tag (the name is never
960
    /// used again)
961
    Delete {
962
        /// Name of the tag
963
        name: String,
964
        /// Why it is withdrawn, recorded with the withdrawal
965
        #[arg(short, long, default_value = "")]
966
        reason: String,
967
    },
968
    /// List tags and the states they name
969
    List {
970
        /// Machine-readable output: one JSON document on stdout
971
        #[arg(long)]
972
        json: bool,
973
    },
974
}
975
976
#[derive(Subcommand)]
977
enum RemoteCmd {
978
    /// Add a remote
979
    Add {
980
        /// Name to refer to the remote by, such as origin
981
        name: String,
982
        /// 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
983
        url: String,
984
        /// For an s3:// store: the AWS profile to use (default: AWS_PROFILE, else "default")
985
        #[arg(long)]
986
        profile: Option<String>,
987
        /// For an s3:// store: its region (default: the environment, the profile, else asked of S3)
988
        #[arg(long)]
989
        region: Option<String>,
990
        /// For an s3://, gs:// or az:// store: another endpoint, such as an S3-compatible service
991
        #[arg(long)]
992
        endpoint: Option<String>,
993
        /// For a gs:// store: a service account key file, or application default credentials
994
        #[arg(long)]
995
        credentials: Option<String>,
996
    },
997
    /// Check a remote: that it is reachable with the credentials in hand, what it holds, and (for a store) that it behaves
998
    Check {
999
        /// The remote to check
1000
        name: String,
1001
    },
1002
    /// Remove a remote
1003
    Remove {
1004
        /// The remote to remove
1005
        name: String,
1006
    },
1007
    /// List remotes and their URLs
1008
    List {
1009
        /// Machine-readable output: one JSON document on stdout
1010
        #[arg(long)]
1011
        json: bool,
1012
    },
1013
}
1014
1015
#[derive(Subcommand)]
1016
enum ProposalCmd {
1017
    /// Show a proposal by its hub URL
1018
    Show {
1019
        /// The proposal's URL on the hub
1020
        url: String,
1021
        /// Machine-readable output: one JSON document on stdout
1022
        #[arg(long)]
1023
        json: bool,
1024
    },
1025
    /// Fetch the proposal's changes, set the target bookmark to the projected state, and push with your key
1026
    Land {
1027
        /// The proposal's URL on the hub
1028
        url: String,
1029
        /// Land even when the hub reports blockers
1030
        #[arg(long)]
1031
        force: bool,
1032
    },
1033
}
1034
1035
#[derive(Subcommand)]
1036
enum IdentityCmd {
1037
    /// Generate a composite Ed25519 + ML-DSA-65 key pair and make it your author identity
1038
    Create {
1039
        /// Your name (default: author.name)
1040
        #[arg(long)]
1041
        name: Option<String>,
1042
        /// Your email (default: author.email)
1043
        #[arg(long)]
1044
        email: Option<String>,
1045
        /// Record the author in this repository only, not in the user config
1046
        #[arg(long)]
1047
        local: bool,
1048
        /// Expire the identity this many days from now
1049
        #[arg(long)]
1050
        expires: Option<u64>,
1051
    },
1052
    /// Show the configured identity
1053
    Show,
1054
    /// Write your identity object to a file, to hand to a policy holder
1055
    Export {
1056
        /// File to write (default: <key>.identity, or <key>.pem with --pem, in the current directory)
1057
        path: Option<PathBuf>,
1058
        /// Write the Ed25519 public key as PEM instead, as cosign's --key and
1059
        /// other DSSE verifiers take it
1060
        #[arg(long)]
1061
        pem: bool,
1062
    },
1063
    /// Sign a host's challenge (hex, at least 16 bytes) to prove you hold your key; prints the signature as hex
1064
    SignChallenge {
1065
        /// The host's challenge, as hex
1066
        challenge: String,
1067
        /// Machine-readable output: one JSON document on stdout
1068
        #[arg(long)]
1069
        json: bool,
1070
    },
1071
    /// Move to a fresh key pair; the policy follows if it names your key
1072
    Rotate,
1073
    /// Re-issue your identity with a new expiry (in days from now; 0 = never)
1074
    Renew {
1075
        /// Days from now until it expires; 0 for never
1076
        #[arg(long)]
1077
        expires: u64,
1078
    },
1079
    /// Revoke a key: yours by default, or any key if you hold a policy root
1080
    Revoke {
1081
        /// KeyId prefix (default: your own key)
1082
        key: Option<String>,
1083
        /// Why, recorded in the revocation
1084
        #[arg(long, default_value = "")]
1085
        reason: String,
1086
    },
1087
    /// Keys allowed to sign or seal on your behalf
1088
    Delegate {
1089
        #[command(subcommand)]
1090
        cmd: DelegateCmd,
1091
    },
1092
}
1093
1094
#[derive(Subcommand)]
1095
enum DelegateCmd {
1096
    /// Add a delegate from an exported identity file
1097
    Add {
1098
        /// The delegates' exported identity files: one rotation for all of them
1099
        #[arg(required = true)]
1100
        identity_file: Vec<PathBuf>,
1101
        /// What it may do for you: changes, refs, seal (comma-separated) or all.
1102
        /// An agent gets `changes`; a host that lands for you needs `changes,refs`
1103
        #[arg(long, default_value = "changes")]
1104
        scope: String,
1105
        /// How long for: 30m, 8h, 7d, or a number of days (default: until removed)
1106
        #[arg(long)]
1107
        expires: Option<String>,
1108
    },
1109
    /// Remove a delegate by KeyId prefix
1110
    Remove {
1111
        /// KeyId prefix of the delegate
1112
        key: String,
1113
    },
1114
    /// List delegates
1115
    List,
1116
}
1117
1118
#[derive(Subcommand)]
1119
enum GitCmd {
1120
    /// Export the current bookmark to a Git repository (created bare if absent)
1121
    Export {
1122
        /// Git repository to write to (created bare if absent)
1123
        git_dir: PathBuf,
1124
        /// Git branch to write (default: the bookmark name)
1125
        #[arg(long)]
1126
        branch: Option<String>,
1127
    },
1128
    /// Fetch a branch from a Git remote (path or URL) into the current bookmark
1129
    Fetch {
1130
        /// Git remote: a path or URL
1131
        url: String,
1132
        /// Branch to fetch
1133
        #[arg(long, default_value = "main")]
1134
        branch: String,
1135
        /// Author your own commits (Git author email = your identity's) with your key; sets git.claim
1136
        #[arg(long)]
1137
        claim: bool,
1138
    },
1139
    /// Push the current bookmark to a branch of a Git remote (fetch first)
1140
    Push {
1141
        /// Git remote: a path or URL
1142
        url: String,
1143
        /// Branch to push to
1144
        #[arg(long, default_value = "main")]
1145
        branch: String,
1146
    },
1147
    /// 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
1148
    Recover,
1149
    /// Check this repository's import of a Git branch: every commit's tree must be reproduced exactly
1150
    Verify {
1151
        /// The Git repository the import came from
1152
        git_dir: PathBuf,
1153
        /// Branch that was imported
1154
        #[arg(long, default_value = "main")]
1155
        branch: String,
1156
        /// Rebuild only the last N commits (the others are followed, not checked)
1157
        #[arg(long, value_name = "N")]
1158
        last: Option<usize>,
1159
        /// Stop after N differences (0: check every commit whatever it finds)
1160
        #[arg(long, value_name = "N", default_value_t = 50)]
1161
        max_differences: usize,
1162
    },
1163
    /// Import a Git branch into a new Oxygen repository at DEST
1164
    Import {
1165
        /// Git repository to read
1166
        git_dir: PathBuf,
1167
        /// Directory for the new Oxygen repository
1168
        dest: PathBuf,
1169
        /// Branch to import
1170
        #[arg(long, default_value = "main")]
1171
        branch: String,
1172
        /// Author your own commits (Git author email = your identity's) with your key; sets git.claim
1173
        #[arg(long)]
1174
        claim: bool,
1175
    },
1176
}
1177
1178
#[derive(Subcommand)]
1179
enum PolicyCmd {
1180
    /// Create the initial policy with your identity as the only root
1181
    Init,
1182
    /// Show the current policy
1183
    Show {
1184
        /// Machine-readable output: one JSON document on stdout
1185
        #[arg(long)]
1186
        json: bool,
1187
    },
1188
    /// Allow an identity (from `oxy identity export`) to update bookmarks
1189
    Grant {
1190
        /// The identity to grant, exported with `oxy identity export`
1191
        identity_file: PathBuf,
1192
        /// Reference pattern the grant applies to (default: every bookmark)
1193
        #[arg(long)]
1194
        pattern: Option<String>,
1195
        /// Where to write the proposal when more root signatures are needed
1196
        #[arg(long)]
1197
        out: Option<PathBuf>,
1198
    },
1199
    /// Allow holders of an issuer's certificates for SUBJECT to sign (keyless)
1200
    GrantSubject {
1201
        /// Who: `repo:OWNER/NAME:bookmark:main`, `agent:NAME@ACCOUNT`; `*` matches any run of characters
1202
        subject: String,
1203
        /// The issuer's identity file, e.g. a hub's /.well-known/oxyhub-key
1204
        #[arg(long)]
1205
        issuer: PathBuf,
1206
        /// What its keys may sign: changes, refs, seal
1207
        #[arg(long, default_value = "changes,refs")]
1208
        scope: String,
1209
        /// Reference pattern the grant applies to (default: every bookmark)
1210
        #[arg(long)]
1211
        pattern: Option<String>,
1212
        /// Where to write the proposal when more root signatures are needed
1213
        #[arg(long)]
1214
        out: Option<PathBuf>,
1215
    },
1216
    /// Revoke a key (KeyId prefix of an identity in the policy)
1217
    Revoke {
1218
        /// KeyId prefix of the identity
1219
        key: String,
1220
        /// Where to write the proposal when more root signatures are needed
1221
        #[arg(long)]
1222
        out: Option<PathBuf>,
1223
    },
1224
    /// Manage root keys and the signature threshold for policy updates
1225
    Root {
1226
        #[command(subcommand)]
1227
        cmd: RootCmd,
1228
    },
1229
    /// Add your root signature to a proposal file; applies it once the threshold is met
1230
    Sign {
1231
        /// The proposal file to sign
1232
        proposal: PathBuf,
1233
        /// Where to write the proposal if it still needs signatures (default: in place)
1234
        #[arg(long)]
1235
        out: Option<PathBuf>,
1236
    },
1237
}
1238
1239
#[derive(Subcommand)]
1240
enum RootCmd {
1241
    /// Make an exported identity a root key
1242
    Add {
1243
        /// The identity to make a root, exported with `oxy identity export`
1244
        identity_file: PathBuf,
1245
        /// Where to write the proposal when more root signatures are needed
1246
        #[arg(long)]
1247
        out: Option<PathBuf>,
1248
    },
1249
    /// Remove a root key by KeyId prefix
1250
    Remove {
1251
        /// KeyId prefix of the root key
1252
        key: String,
1253
        /// Where to write the proposal when more root signatures are needed
1254
        #[arg(long)]
1255
        out: Option<PathBuf>,
1256
    },
1257
    /// Require this many root signatures on policy updates
1258
    Threshold {
1259
        /// Number of root signatures
1260
        n: u32,
1261
        /// Where to write the proposal when more root signatures are needed
1262
        #[arg(long)]
1263
        out: Option<PathBuf>,
1264
    },
1265
}
1266
1267
/// Open the repository containing the current directory.
1268141×
fn open() -> Result<Repo> {
1269141×
    let repo = Repo::open(&std::env::current_dir()?).context("opening repository")?;
1270139×
    match AT_OP.get().and_then(|o| o.as_deref()) {
12710×
        Some(op) => Ok(repo.at_op(op)?),
1272139×
        None => Ok(repo),
1273
    }
1274141×
}
1275
1276
/// `oxy man`: every page into `dir`, or the top-level page on stdout.
12772×
fn man(dir: Option<PathBuf>) -> Result<i32> {
1278
    use clap::CommandFactory;
12792×
    let cmd = Cli::command();
12802×
    match dir {
12811×
        Some(dir) => {
12821×
            std::fs::create_dir_all(&dir)?;
12831×
            clap_mangen::generate_to(cmd, &dir)?;
12841×
            let pages = std::fs::read_dir(&dir)?
1285134×
                .filter(|e| {
1286134×
                    e.as_ref()
1287134×
                        .is_ok_and(|e| e.path().extension().is_some_and(|x| x == "1"))
1288134×
                })
12891×
                .count();
12901×
            println!(
1291
                "{}",
12921×
                ui::done(format!("Wrote {pages} man pages to {}", dir.display()))
1293
            );
1294
        }
12951×
        None => clap_mangen::Man::new(cmd).render(&mut std::io::stdout())?,
1296
    }
12972×
    Ok(0)
12982×
}
1299
1300
/// Parse arguments and run; returns the process exit code.
1301179×
pub fn run() -> Result<i32> {
1302
    // The cloud stores (s3://, gs://, az://) for remotes kept on them.
1303179×
    oxy_strata::register();
1304179×
    let cli = Cli::parse();
1305179×
    ui::init(cli.plain);
1306179×
    AT_OP.set(cli.at_op.clone()).ok();
13070×
    match cli.cmd {
13084×
        Cmd::Completions { shell } => {
1309
            use clap::CommandFactory;
13104×
            clap_complete::generate(shell, &mut Cli::command(), "oxy", &mut std::io::stdout());
13114×
            Ok(0)
1312
        }
13132×
        Cmd::Man { dir } => man(dir),
131418×
        Cmd::Init { path, bare, store } => workspace::init(path, bare, store.as_deref()),
131510×
        Cmd::Status { json } => workspace::status(json),
1316
        Cmd::Prompt {
13170×
            format,
13180×
            glyphs,
13190×
            color,
13200×
        } => workspace::prompt(&format, glyphs, color.as_deref()),
1321
        Cmd::Commit {
132228×
            message,
132328×
            file,
132428×
            depends_on,
132528×
            paths,
132628×
            interactive,
132728×
            hunks,
1328
        } => {
132928×
            let message = match (message, file) {
133027×
                (Some(m), _) => m,
13311×
                (None, Some(f)) if f.as_os_str() == "-" => {
13320×
                    let mut s = String::new();
13330×
                    std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
13340×
                    s
1335
                }
13361×
                (None, Some(f)) => std::fs::read_to_string(&f).map_err(|e| {
13370×
                    anyhow::anyhow!("reading the message from {}: {e}", f.display())
13380×
                })?,
13390×
                (None, None) => anyhow::bail!("a commit message is required (-m or -F)"),
1340
            };
134128×
            workspace::commit(&message, &depends_on, &paths, interactive, &hunks)
1342
        }
13433×
        Cmd::Cat { path, change } => workspace::cat(&path, change.as_deref()),
13441×
        Cmd::Root { json } => workspace::root(json),
1345
        Cmd::Mcp {
13463×
            dir,
13473×
            allow_destructive,
13483×
        } => mcp::serve(dir, allow_destructive),
13491×
        Cmd::Version { json } => workspace::version(json),
13502×
        Cmd::Discard { paths, hunks } => workspace::discard(&paths, &hunks),
13512×
        Cmd::Hunks { json } => workspace::hunks(json),
13520×
        Cmd::Squash { change, into } => workspace::squash(&change, &into),
1353
        Cmd::Rebase {
13540×
            change,
13550×
            onto,
13560×
            into_working_copy,
13570×
        } => workspace::rebase(&change, &onto, into_working_copy),
13580×
        Cmd::Blame { path, json } => workspace::blame(&path, json),
13591×
        Cmd::Bisect { cmd } => match cmd {
13600×
            BisectCmd::Start => workspace::bisect_start(),
13610×
            BisectCmd::Good { changes } => workspace::bisect_mark(Some(true), &changes),
13620×
            BisectCmd::Bad { changes } => workspace::bisect_mark(Some(false), &changes),
13630×
            BisectCmd::Skip => workspace::bisect_mark(None, &[]),
13640×
            BisectCmd::Run { command } => workspace::bisect_run(&command),
13651×
            BisectCmd::Status { json } => workspace::bisect_status(json),
13660×
            BisectCmd::Reset => workspace::bisect_reset(),
1367
        },
1368
        Cmd::Log {
136910×
            revset,
137010×
            limit,
137110×
            verbose,
137210×
            path,
137310×
            lines,
137410×
            json,
137510×
        } => workspace::log(
137610×
            revset.as_deref(),
137710×
            limit,
137810×
            verbose,
137910×
            path.as_deref(),
138010×
            lines.as_deref(),
138110×
            json,
1382
        ),
13831×
        Cmd::Diff { change, json } => workspace::diff(change.as_deref(), json),
1384
        Cmd::Describe {
13854×
            message,
13864×
            change,
13874×
            json,
13884×
        } => match message {
13890×
            Some(m) => workspace::describe(&m, change.as_deref()),
13904×
            None if change.is_some() => {
13910×
                anyhow::bail!(
1392
                    "naming works on the working copy; to change a head's message pass -m"
1393
                )
1394
            }
13954×
            None => workspace::describe_name(json),
1396
        },
1397
        Cmd::Amend {
13980×
            message,
13990×
            into,
14000×
            paths,
14010×
        } => workspace::amend(message.as_deref(), into.as_deref(), &paths),
14020×
        Cmd::Split { change, paths } => workspace::split(&change, &paths),
1403
        Cmd::Abandon {
14040×
            change,
14050×
            revset,
14060×
            yes,
14070×
        } => workspace::abandon(change.as_deref(), revset.as_deref(), yes),
1408
        Cmd::Show {
14093×
            change,
14103×
            revset,
14113×
            stat,
14123×
            json,
14133×
        } => workspace::show(change.as_deref(), revset.as_deref(), stat, json),
1414
        Cmd::Checkout {
14150×
            changes,
14160×
            discard,
14170×
            carry,
14180×
        } => workspace::checkout(&changes, discard, carry),
1419
        Cmd::Resolve {
14201×
            paths,
14211×
            both,
14221×
            reverse,
14231×
            json,
14241×
        } => workspace::resolve(&paths, both, reverse, json),
14250×
        Cmd::Undo => workspace::undo(),
1426
        Cmd::Gc {
14273×
            now,
14283×
            expire_snapshots,
14293×
            remote,
14303×
        } => match remote {
14312×
            Some(name) => workspace::gc_remote(&name, now),
14321×
            None => workspace::gc(now, expire_snapshots),
1433
        },
14340×
        Cmd::Fsck { json } => workspace::fsck(json),
14350×
        Cmd::Doctor { offline, json } => workspace::doctor(offline, json),
14360×
        Cmd::Checkpoint => workspace::checkpoint(),
14371×
        Cmd::Op { cmd } => match cmd {
14381×
            OpCmd::Log { limit, json } => workspace::op_log(limit, json),
14390×
            OpCmd::Restore { op, discard } => workspace::op_restore(&op, discard),
14400×
            OpCmd::Revert { op } => workspace::op_revert(&op),
1441
        },
1442
        Cmd::Clone {
14435×
            url,
14445×
            dest,
14455×
            max_blob,
14465×
            sparse,
14475×
            depth,
14485×
            recursive,
14495×
        } => sync::clone(&url, dest, max_blob.as_deref(), &sparse, depth, recursive),
14500×
        Cmd::Deepen { depth, remote } => sync::deepen(&remote, depth),
14510×
        Cmd::Sparse { paths } => workspace::sparse(&paths),
14520×
        Cmd::Lock { path } => workspace::lock(&path),
14530×
        Cmd::Unlock { path } => workspace::unlock(&path),
14541×
        Cmd::Workspace { cmd } => match cmd {
14550×
            WorkspaceCmd::Add { path, changes } => workspace::workspace_add(&path, &changes),
14561×
            WorkspaceCmd::List { json } => workspace::workspace_list(json),
14570×
            WorkspaceCmd::Forget { workspace } => workspace::workspace_forget(&workspace),
1458
        },
145917×
        Cmd::Bookmark { cmd } => match cmd {
1460
            BookmarkCmd::Create {
14616×
                name,
14626×
                changes,
14636×
                upto,
14646×
                only,
14656×
            } => workspace::bookmark_create(&name, &changes, upto, only),
1466
            BookmarkCmd::Set {
14673×
                name,
14683×
                changes,
14693×
                upto,
14703×
                only,
14713×
            } => workspace::bookmark_set(&name, &changes, upto, only),
14720×
            BookmarkCmd::Delete { name } => workspace::bookmark_delete(&name),
14735×
            BookmarkCmd::List { all, verbose, json } => {
14745×
                workspace::bookmark_list(all, verbose, json)
1475
            }
14760×
            BookmarkCmd::Show { name, json } => workspace::bookmark_show(name.as_deref(), json),
1477
            BookmarkCmd::Switch {
14783×
                name,
14793×
                discard,
14803×
                carry,
14813×
            } => workspace::bookmark_switch(&name, discard, carry),
1482
        },
14830×
        Cmd::Merge { bookmark } => workspace::merge(&bookmark),
14840×
        Cmd::Auth { cmd } => match cmd {
1485
            AuthCmd::Login {
14860×
                hub,
14870×
                with_token,
14880×
                ca,
14890×
            } => auth::login(hub.as_deref(), with_token, ca),
14900×
            AuthCmd::Status => auth::status(),
14910×
            AuthCmd::Logout { hub } => auth::logout(hub.as_deref()),
14920×
            AuthCmd::Grant { hub } => auth::grant(hub.as_deref()),
1493
        },
14941×
        Cmd::Submodule { cmd } => match cmd {
1495
            SubmoduleCmd::Add {
14960×
                url,
14970×
                path,
14980×
                bookmark,
14990×
            } => sync::submodule_add(&url, &path, bookmark.as_deref()),
15000×
            SubmoduleCmd::Update { init, paths } => sync::submodule_update(init, &paths),
15011×
            SubmoduleCmd::Status { json } => sync::submodule_status(json),
15020×
            SubmoduleCmd::Remove { path } => sync::submodule_remove(&path),
1503
        },
1504
        Cmd::Witness {
1505
            cmd:
1506
                WitnessCmd::Serve {
15070×
                    name,
15080×
                    logs,
15090×
                    state,
15100×
                    bind,
15110×
                    tls_cert,
15120×
                    tls_key,
1513
                },
15140×
        } => tlog::witness_serve(&name, &logs, state, &bind, tls_cert.zip(tls_key)),
15150×
        Cmd::Tlog { cmd } => match cmd {
1516
            TlogCmd::Verify {
15170×
                hub,
15180×
                key,
15190×
                all,
15200×
                json,
15210×
            } => tlog::verify(hub.as_deref(), key.as_deref(), all, json),
1522
        },
15235×
        Cmd::Artifact { cmd } => match cmd {
1524
            ArtifactCmd::Pack {
15252×
                dir,
15262×
                kind,
15272×
                arch,
15282×
                os,
15292×
                entrypoint,
15302×
                env,
15312×
                labels,
15322×
                json,
15332×
            } => artifact::pack(&dir, &kind, arch, os, entrypoint, &env, &labels, json),
15341×
            ArtifactCmd::List { json } => artifact::list(json),
15350×
            ArtifactCmd::Show { name, json } => artifact::show(&name, json),
15361×
            ArtifactCmd::Unpack { name, dest } => artifact::unpack(&name, &dest),
15371×
            ArtifactCmd::Verify { name } => artifact::verify(&name),
1538
        },
153910×
        Cmd::Receipt { cmd } => match cmd {
15402×
            ReceiptCmd::List { rev, json } => receipt::list(rev.as_deref(), json),
1541
            ReceiptCmd::Show {
15421×
                receipt: r,
15431×
                rev,
15441×
                json,
15451×
            } => receipt::show(&r, rev.as_deref(), json),
1546
            ReceiptCmd::Export {
15473×
                receipt: r,
15483×
                file,
15493×
                rev,
15503×
                format,
15513×
            } => receipt::export(&r, &file, rev.as_deref(), &format),
15522×
            ReceiptCmd::Verify { file, json } => receipt::verify(&file, json),
15532×
            ReceiptCmd::Import { file } => receipt::import(&file),
1554
        },
15553×
        Cmd::Tag { cmd } => match cmd {
1556
            TagCmd::Create {
15572×
                name,
15582×
                changes,
15592×
                message,
15602×
            } => workspace::tag_create(&name, &changes, &message),
15610×
            TagCmd::Delete { name, reason } => workspace::tag_delete(&name, &reason),
15621×
            TagCmd::List { json } => workspace::tag_list(json),
1563
        },
156410×
        Cmd::Remote { cmd } => match cmd {
1565
            RemoteCmd::Add {
15664×
                name,
15674×
                url,
15684×
                profile,
15694×
                region,
15704×
                endpoint,
15714×
                credentials,
15724×
            } => sync::remote_add(
15734×
                &name,
15744×
                &url,
15754×
                &[
15764×
                    ("profile", profile),
15774×
                    ("region", region),
15784×
                    ("endpoint", endpoint),
15794×
                    ("credentials", credentials),
15804×
                ],
1581
            ),
15823×
            RemoteCmd::Check { name } => sync::remote_check(&name),
15831×
            RemoteCmd::Remove { name } => sync::remote_remove(&name),
15842×
            RemoteCmd::List { json } => sync::remote_list(json),
1585
        },
15861×
        Cmd::Fetch { remote, json } => sync::fetch(remote.as_deref(), json),
15874×
        Cmd::Pull { remote, json } => sync::pull(remote.as_deref(), json),
1588
        Cmd::Push {
15897×
            remote,
15907×
            force,
15917×
            bookmark,
15927×
            delete,
15937×
            json,
15947×
        } => match delete {
15950×
            Some(name) => sync::push_delete(remote.as_deref(), &name, json),
15967×
            None => sync::push(remote.as_deref(), force, bookmark.as_deref(), json),
1597
        },
1598
        Cmd::Serve {
15990×
            root,
16000×
            bind,
16010×
            tokens,
16020×
            tls_cert,
16030×
            tls_key,
16040×
        } => sync::serve(root, &bind, tokens, tls_cert.zip(tls_key)),
16058×
        Cmd::Identity { cmd } => match cmd {
1606
            IdentityCmd::Create {
16075×
                name,
16085×
                email,
16095×
                local,
16105×
                expires,
16115×
            } => identity::create(name, email, local, expires),
16122×
            IdentityCmd::Show => identity::show(),
16131×
            IdentityCmd::Export { path, pem } => identity::export(path, pem),
16140×
            IdentityCmd::SignChallenge { challenge, json } => {
16150×
                identity::sign_challenge(&challenge, json)
1616
            }
16170×
            IdentityCmd::Rotate => identity::rotate(),
16180×
            IdentityCmd::Renew { expires } => identity::renew(expires),
16190×
            IdentityCmd::Revoke { key, reason } => identity::revoke(key.as_deref(), &reason),
16200×
            IdentityCmd::Delegate { cmd } => match cmd {
1621
                DelegateCmd::Add {
16220×
                    identity_file,
16230×
                    scope,
16240×
                    expires,
16250×
                } => identity::delegate_add(&identity_file, &scope, expires.as_deref()),
16260×
                DelegateCmd::Remove { key } => identity::delegate_remove(&key),
16270×
                DelegateCmd::List => identity::delegate_list(),
1628
            },
1629
        },
1630
        Cmd::Git {
16310×
            cmd: GitCmd::Export { git_dir, branch },
16320×
        } => sync::git_export(&git_dir, branch.as_deref()),
1633
        Cmd::Git {
16340×
            cmd: GitCmd::Fetch { url, branch, claim },
16350×
        } => sync::git_fetch(&url, &branch, claim),
1636
        Cmd::Git {
16370×
            cmd: GitCmd::Push { url, branch },
16380×
        } => sync::git_push(&url, &branch),
1639
        Cmd::Git {
1640
            cmd: GitCmd::Recover,
16410×
        } => sync::git_recover(),
1642
        Cmd::Git {
1643
            cmd:
1644
                GitCmd::Import {
16450×
                    git_dir,
16460×
                    dest,
16470×
                    branch,
16480×
                    claim,
1649
                },
16500×
        } => sync::git_import(&git_dir, &dest, &branch, claim),
1651
        Cmd::Git {
1652
            cmd:
1653
                GitCmd::Verify {
16540×
                    git_dir,
16550×
                    branch,
16560×
                    last,
16570×
                    max_differences,
1658
                },
16590×
        } => sync::git_verify(&git_dir, &branch, last, max_differences),
16605×
        Cmd::Policy { cmd } => match cmd {
16611×
            PolicyCmd::Init => identity::policy_init(),
16623×
            PolicyCmd::Show { json } => identity::policy_show(json),
1663
            PolicyCmd::Grant {
16640×
                identity_file,
16650×
                pattern,
16660×
                out,
16670×
            } => identity::policy_grant(&identity_file, pattern.as_deref(), out),
1668
            PolicyCmd::GrantSubject {
16691×
                subject,
16701×
                issuer,
16711×
                scope,
16721×
                pattern,
16731×
                out,
16741×
            } => identity::policy_grant_subject(&subject, &issuer, &scope, pattern.as_deref(), out),
16750×
            PolicyCmd::Revoke { key, out } => identity::policy_revoke(&key, out),
16760×
            PolicyCmd::Root { cmd } => match cmd {
16770×
                RootCmd::Add { identity_file, out } => {
16780×
                    identity::policy_root_add(&identity_file, out)
1679
                }
16800×
                RootCmd::Remove { key, out } => identity::policy_root_remove(&key, out),
16810×
                RootCmd::Threshold { n, out } => identity::policy_threshold(n, out),
1682
            },
16830×
            PolicyCmd::Sign { proposal, out } => identity::policy_sign(&proposal, out),
1684
        },
1685
        Cmd::Seal {
16860×
            flow: Some(url),
16870×
            job: Some(job),
16880×
            reject,
16890×
            json,
1690
            ..
16910×
        } => approve::seal(&url, &job, reject, json),
1692
        Cmd::Seal {
16930×
            changes,
16940×
            proposal: Some(url),
16950×
            json,
1696
            ..
16970×
        } if changes.is_empty() => proposal::seal(&url, json),
16980×
        Cmd::Seal { changes, json, .. } => identity::seal(&changes, json),
16990×
        Cmd::Proposal { cmd } => match cmd {
17000×
            ProposalCmd::Show { url, json } => proposal::show(&url, json),
17010×
            ProposalCmd::Land { url, force } => proposal::land(&url, force),
1702
        },
1703
        Cmd::Verify {
17041×
            change,
17051×
            revset,
17061×
            json,
17071×
        } => identity::verify(change.as_deref(), revset.as_deref(), json),
1708
        Cmd::Config {
17093×
            key,
17103×
            value,
17113×
            user,
17123×
            unset,
17133×
        } => identity::config(&key, value.as_deref().unwrap_or(""), user, unset),
1714
    }
1715179×
}
1716
1717
#[cfg(test)]
1718
mod help_tests {
1719
    use super::Cli;
1720
    use clap::CommandFactory;
1721
1722
    /// Every command and every argument explains itself, so `--help`,
1723
    /// completions and the man pages are complete.
1724
    #[test]
17251×
    fn every_command_and_argument_has_help() {
1726134×
        fn walk(cmd: &clap::Command, path: &str, missing: &mut Vec<String>) {
1727134×
            let here = format!("{path} {}", cmd.get_name()).trim().to_string();
1728134×
            if cmd.get_about().is_none() && !path.is_empty() {
17290×
                missing.push(format!("{here} (command)"));
1730134×
            }
1731254×
            for a in cmd.get_arguments() {
1732254×
                let id = a.get_id().as_str();
1733254×
                if id == "help" || id == "version" || (a.is_global_set() && !path.is_empty()) {
17340×
                    continue;
1735254×
                }
1736254×
                if a.get_help().is_none() && a.get_long_help().is_none() {
17370×
                    missing.push(format!("{here} {id}"));
1738254×
                }
1739
            }
1740134×
            for sub in cmd.get_subcommands() {
1741133×
                walk(sub, &here, missing);
1742133×
            }
1743134×
        }
17441×
        let mut missing = Vec::new();
17451×
        walk(&Cli::command(), "", &mut missing);
17461×
        assert!(
17471×
            missing.is_empty(),
1748
            "{} without help:\n{}",
17490×
            missing.len(),
17500×
            missing.join("\n")
1751
        );
17521×
    }
1753
}