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