OXYGENHUB
◆ v0.10.0 oxygen / src / cli / mod.rs
64.5 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) 3 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 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, git.claim, git.colocate, 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
    /// Keep a .git beside .oxy, up to date after every oxy command, so editors' Git features work here (one way: oxy to Git)
1121
    Colocate {
1122
        /// Stop updating it (the .git is left as it is)
1123
        #[arg(long)]
1124
        off: bool,
1125
    },
1126
    /// Export the current bookmark to a Git repository (created bare if absent)
1127
    Export {
1128
        /// Git repository to write to (created bare if absent)
1129
        git_dir: PathBuf,
1130
        /// Git branch to write (default: the bookmark name)
1131
        #[arg(long)]
1132
        branch: Option<String>,
1133
    },
1134
    /// Fetch a branch from a Git remote (path or URL) into the current bookmark
1135
    Fetch {
1136
        /// Git remote: a path or URL
1137
        url: String,
1138
        /// Branch to fetch
1139
        #[arg(long, default_value = "main")]
1140
        branch: String,
1141
        /// Author your own commits (Git author email = your identity's) with your key; sets git.claim
1142
        #[arg(long)]
1143
        claim: bool,
1144
    },
1145
    /// Push the current bookmark to a branch of a Git remote (fetch first)
1146
    Push {
1147
        /// Git remote: a path or URL
1148
        url: String,
1149
        /// Branch to push to
1150
        #[arg(long, default_value = "main")]
1151
        branch: String,
1152
    },
1153
    /// 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
1154
    Recover,
1155
    /// Check this repository's import of a Git branch: every commit's tree must be reproduced exactly
1156
    Verify {
1157
        /// The Git repository the import came from
1158
        git_dir: PathBuf,
1159
        /// Branch that was imported
1160
        #[arg(long, default_value = "main")]
1161
        branch: String,
1162
        /// Rebuild only the last N commits (the others are followed, not checked)
1163
        #[arg(long, value_name = "N")]
1164
        last: Option<usize>,
1165
        /// Stop after N differences (0: check every commit whatever it finds)
1166
        #[arg(long, value_name = "N", default_value_t = 50)]
1167
        max_differences: usize,
1168
    },
1169
    /// Import a Git branch into a new Oxygen repository at DEST
1170
    Import {
1171
        /// Git repository to read
1172
        git_dir: PathBuf,
1173
        /// Directory for the new Oxygen repository
1174
        dest: PathBuf,
1175
        /// Branch to import
1176
        #[arg(long, default_value = "main")]
1177
        branch: String,
1178
        /// Author your own commits (Git author email = your identity's) with your key; sets git.claim
1179
        #[arg(long)]
1180
        claim: bool,
1181
    },
1182
}
1183
1184
#[derive(Subcommand)]
1185
enum PolicyCmd {
1186
    /// Create the initial policy with your identity as the only root
1187
    Init,
1188
    /// Show the current policy
1189
    Show {
1190
        /// Machine-readable output: one JSON document on stdout
1191
        #[arg(long)]
1192
        json: bool,
1193
    },
1194
    /// Allow an identity (from `oxy identity export`) to update bookmarks
1195
    Grant {
1196
        /// The identity to grant, exported with `oxy identity export`
1197
        identity_file: PathBuf,
1198
        /// Reference pattern the grant applies to (default: every bookmark)
1199
        #[arg(long)]
1200
        pattern: Option<String>,
1201
        /// Where to write the proposal when more root signatures are needed
1202
        #[arg(long)]
1203
        out: Option<PathBuf>,
1204
    },
1205
    /// Allow holders of an issuer's certificates for SUBJECT to sign (keyless)
1206
    GrantSubject {
1207
        /// Who: `repo:OWNER/NAME:bookmark:main`, `agent:NAME@ACCOUNT`; `*` matches any run of characters
1208
        subject: String,
1209
        /// The issuer's identity file, e.g. a hub's /.well-known/oxyhub-key
1210
        #[arg(long)]
1211
        issuer: PathBuf,
1212
        /// What its keys may sign: changes, refs, seal
1213
        #[arg(long, default_value = "changes,refs")]
1214
        scope: String,
1215
        /// Reference pattern the grant applies to (default: every bookmark)
1216
        #[arg(long)]
1217
        pattern: Option<String>,
1218
        /// Where to write the proposal when more root signatures are needed
1219
        #[arg(long)]
1220
        out: Option<PathBuf>,
1221
    },
1222
    /// Revoke a key (KeyId prefix of an identity in the policy)
1223
    Revoke {
1224
        /// KeyId prefix of the identity
1225
        key: String,
1226
        /// Where to write the proposal when more root signatures are needed
1227
        #[arg(long)]
1228
        out: Option<PathBuf>,
1229
    },
1230
    /// Manage root keys and the signature threshold for policy updates
1231
    Root {
1232
        #[command(subcommand)]
1233
        cmd: RootCmd,
1234
    },
1235
    /// Add your root signature to a proposal file; applies it once the threshold is met
1236
    Sign {
1237
        /// The proposal file to sign
1238
        proposal: PathBuf,
1239
        /// Where to write the proposal if it still needs signatures (default: in place)
1240
        #[arg(long)]
1241
        out: Option<PathBuf>,
1242
    },
1243
}
1244
1245
#[derive(Subcommand)]
1246
enum RootCmd {
1247
    /// Make an exported identity a root key
1248
    Add {
1249
        /// The identity to make a root, exported with `oxy identity export`
1250
        identity_file: PathBuf,
1251
        /// Where to write the proposal when more root signatures are needed
1252
        #[arg(long)]
1253
        out: Option<PathBuf>,
1254
    },
1255
    /// Remove a root key by KeyId prefix
1256
    Remove {
1257
        /// KeyId prefix of the root key
1258
        key: String,
1259
        /// Where to write the proposal when more root signatures are needed
1260
        #[arg(long)]
1261
        out: Option<PathBuf>,
1262
    },
1263
    /// Require this many root signatures on policy updates
1264
    Threshold {
1265
        /// Number of root signatures
1266
        n: u32,
1267
        /// Where to write the proposal when more root signatures are needed
1268
        #[arg(long)]
1269
        out: Option<PathBuf>,
1270
    },
1271
}
1272
1273
/// After a command, bring the side-by-side `.git` up to date when this
1274
/// checkout keeps one (`git.colocate`). It never fails the command: a
1275
/// problem is a warning, and the next command tries again.
1276
pub fn after_command() {
1277
    if AT_OP.get().and_then(|o| o.as_deref()).is_some() {
1278
        return;
1279
    }
1280
    let Ok(dir) = std::env::current_dir() else {
1281
        return;
1282
    };
1283
    let Ok(repo) = Repo::open(&dir) else { return };
1284
    if !repo.config.git_colocate || repo.is_bare() {
1285
        return;
1286
    }
1287
    if let Err(e) = repo.git_colocate_sync() {
1288
        eprintln!(
1289
            "{} the .git beside this checkout was not updated: {e}",
1290
            ui::warn("!")
1291
        );
1292
    }
1293
}
1294
1295
/// Open the repository containing the current directory.
1296
fn open() -> Result<Repo> {
1297
    let repo = Repo::open(&std::env::current_dir()?).context("opening repository")?;
1298
    match AT_OP.get().and_then(|o| o.as_deref()) {
1299
        Some(op) => Ok(repo.at_op(op)?),
1300
        None => Ok(repo),
1301
    }
1302
}
1303
1304
/// `oxy man`: every page into `dir`, or the top-level page on stdout.
1305
fn man(dir: Option<PathBuf>) -> Result<i32> {
1306
    use clap::CommandFactory;
1307
    let cmd = Cli::command();
1308
    match dir {
1309
        Some(dir) => {
1310
            std::fs::create_dir_all(&dir)?;
1311
            clap_mangen::generate_to(cmd, &dir)?;
1312
            let pages = std::fs::read_dir(&dir)?
1313
                .filter(|e| {
1314
                    e.as_ref()
1315
                        .is_ok_and(|e| e.path().extension().is_some_and(|x| x == "1"))
1316
                })
1317
                .count();
1318
            println!(
1319
                "{}",
1320
                ui::done(format!("Wrote {pages} man pages to {}", dir.display()))
1321
            );
1322
        }
1323
        None => clap_mangen::Man::new(cmd).render(&mut std::io::stdout())?,
1324
    }
1325
    Ok(0)
1326
}
1327
1328
/// Parse arguments and run; returns the process exit code.
1329
pub fn run() -> Result<i32> {
1330
    // The cloud stores (s3://, gs://, az://) for remotes kept on them.
1331
    oxy_strata::register();
1332
    let cli = Cli::parse();
1333
    ui::init(cli.plain);
1334
    AT_OP.set(cli.at_op.clone()).ok();
1335
    match cli.cmd {
1336
        Cmd::Completions { shell } => {
1337
            use clap::CommandFactory;
1338
            clap_complete::generate(shell, &mut Cli::command(), "oxy", &mut std::io::stdout());
1339
            Ok(0)
1340
        }
1341
        Cmd::Man { dir } => man(dir),
1342
        Cmd::Init { path, bare, store } => workspace::init(path, bare, store.as_deref()),
1343
        Cmd::Status { json } => workspace::status(json),
1344
        Cmd::Prompt {
1345
            format,
1346
            glyphs,
1347
            color,
1348
        } => workspace::prompt(&format, glyphs, color.as_deref()),
1349
        Cmd::Commit {
1350
            message,
1351
            file,
1352
            depends_on,
1353
            paths,
1354
            interactive,
1355
            hunks,
1356
        } => {
1357
            let message = match (message, file) {
1358
                (Some(m), _) => m,
1359
                (None, Some(f)) if f.as_os_str() == "-" => {
1360
                    let mut s = String::new();
1361
                    std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
1362
                    s
1363
                }
1364
                (None, Some(f)) => std::fs::read_to_string(&f).map_err(|e| {
1365
                    anyhow::anyhow!("reading the message from {}: {e}", f.display())
1366
                })?,
1367
                (None, None) => anyhow::bail!("a commit message is required (-m or -F)"),
1368
            };
1369
            workspace::commit(&message, &depends_on, &paths, interactive, &hunks)
1370
        }
1371
        Cmd::Cat { path, change } => workspace::cat(&path, change.as_deref()),
1372
        Cmd::Root { json } => workspace::root(json),
1373
        Cmd::Mcp {
1374
            dir,
1375
            allow_destructive,
1376
        } => mcp::serve(dir, allow_destructive),
1377
        Cmd::Version { json } => workspace::version(json),
1378
        Cmd::Discard { paths, hunks } => workspace::discard(&paths, &hunks),
1379
        Cmd::Hunks { json } => workspace::hunks(json),
1380
        Cmd::Squash { change, into } => workspace::squash(&change, &into),
1381
        Cmd::Rebase {
1382
            change,
1383
            onto,
1384
            into_working_copy,
1385
        } => workspace::rebase(&change, &onto, into_working_copy),
1386
        Cmd::Blame { path, json } => workspace::blame(&path, json),
1387
        Cmd::Bisect { cmd } => match cmd {
1388
            BisectCmd::Start => workspace::bisect_start(),
1389
            BisectCmd::Good { changes } => workspace::bisect_mark(Some(true), &changes),
1390
            BisectCmd::Bad { changes } => workspace::bisect_mark(Some(false), &changes),
1391
            BisectCmd::Skip => workspace::bisect_mark(None, &[]),
1392
            BisectCmd::Run { command } => workspace::bisect_run(&command),
1393
            BisectCmd::Status { json } => workspace::bisect_status(json),
1394
            BisectCmd::Reset => workspace::bisect_reset(),
1395
        },
1396
        Cmd::Log {
1397
            revset,
1398
            limit,
1399
            verbose,
1400
            path,
1401
            lines,
1402
            json,
1403
        } => workspace::log(
1404
            revset.as_deref(),
1405
            limit,
1406
            verbose,
1407
            path.as_deref(),
1408
            lines.as_deref(),
1409
            json,
1410
        ),
1411
        Cmd::Diff { change, json } => workspace::diff(change.as_deref(), json),
1412
        Cmd::Describe {
1413
            message,
1414
            change,
1415
            json,
1416
        } => match message {
1417
            Some(m) => workspace::describe(&m, change.as_deref()),
1418
            None if change.is_some() => {
1419
                anyhow::bail!(
1420
                    "naming works on the working copy; to change a head's message pass -m"
1421
                )
1422
            }
1423
            None => workspace::describe_name(json),
1424
        },
1425
        Cmd::Amend {
1426
            message,
1427
            into,
1428
            paths,
1429
        } => workspace::amend(message.as_deref(), into.as_deref(), &paths),
1430
        Cmd::Split { change, paths } => workspace::split(&change, &paths),
1431
        Cmd::Abandon {
1432
            change,
1433
            revset,
1434
            yes,
1435
        } => workspace::abandon(change.as_deref(), revset.as_deref(), yes),
1436
        Cmd::Show {
1437
            change,
1438
            revset,
1439
            stat,
1440
            json,
1441
        } => workspace::show(change.as_deref(), revset.as_deref(), stat, json),
1442
        Cmd::Checkout {
1443
            changes,
1444
            discard,
1445
            carry,
1446
        } => workspace::checkout(&changes, discard, carry),
1447
        Cmd::Resolve {
1448
            paths,
1449
            both,
1450
            reverse,
1451
            json,
1452
        } => workspace::resolve(&paths, both, reverse, json),
1453
        Cmd::Undo => workspace::undo(),
1454
        Cmd::Gc {
1455
            now,
1456
            expire_snapshots,
1457
            remote,
1458
        } => match remote {
1459
            Some(name) => workspace::gc_remote(&name, now),
1460
            None => workspace::gc(now, expire_snapshots),
1461
        },
1462
        Cmd::Fsck { json } => workspace::fsck(json),
1463
        Cmd::Doctor { offline, json } => workspace::doctor(offline, json),
1464
        Cmd::Checkpoint => workspace::checkpoint(),
1465
        Cmd::Op { cmd } => match cmd {
1466
            OpCmd::Log { limit, json } => workspace::op_log(limit, json),
1467
            OpCmd::Restore { op, discard } => workspace::op_restore(&op, discard),
1468
            OpCmd::Revert { op } => workspace::op_revert(&op),
1469
        },
1470
        Cmd::Clone {
1471
            url,
1472
            dest,
1473
            max_blob,
1474
            sparse,
1475
            depth,
1476
            recursive,
1477
        } => sync::clone(&url, dest, max_blob.as_deref(), &sparse, depth, recursive),
1478
        Cmd::Deepen { depth, remote } => sync::deepen(&remote, depth),
1479
        Cmd::Sparse { paths } => workspace::sparse(&paths),
1480
        Cmd::Lock { path } => workspace::lock(&path),
1481
        Cmd::Unlock { path } => workspace::unlock(&path),
1482
        Cmd::Workspace { cmd } => match cmd {
1483
            WorkspaceCmd::Add { path, changes } => workspace::workspace_add(&path, &changes),
1484
            WorkspaceCmd::List { json } => workspace::workspace_list(json),
1485
            WorkspaceCmd::Forget { workspace } => workspace::workspace_forget(&workspace),
1486
        },
1487
        Cmd::Bookmark { cmd } => match cmd {
1488
            BookmarkCmd::Create {
1489
                name,
1490
                changes,
1491
                upto,
1492
                only,
1493
            } => workspace::bookmark_create(&name, &changes, upto, only),
1494
            BookmarkCmd::Set {
1495
                name,
1496
                changes,
1497
                upto,
1498
                only,
1499
            } => workspace::bookmark_set(&name, &changes, upto, only),
1500
            BookmarkCmd::Delete { name } => workspace::bookmark_delete(&name),
1501
            BookmarkCmd::List { all, verbose, json } => {
1502
                workspace::bookmark_list(all, verbose, json)
1503
            }
1504
            BookmarkCmd::Show { name, json } => workspace::bookmark_show(name.as_deref(), json),
1505
            BookmarkCmd::Switch {
1506
                name,
1507
                discard,
1508
                carry,
1509
            } => workspace::bookmark_switch(&name, discard, carry),
1510
        },
1511
        Cmd::Merge { bookmark } => workspace::merge(&bookmark),
1512
        Cmd::Auth { cmd } => match cmd {
1513
            AuthCmd::Login {
1514
                hub,
1515
                with_token,
1516
                ca,
1517
            } => auth::login(hub.as_deref(), with_token, ca),
1518
            AuthCmd::Status => auth::status(),
1519
            AuthCmd::Logout { hub } => auth::logout(hub.as_deref()),
1520
            AuthCmd::Grant { hub } => auth::grant(hub.as_deref()),
1521
        },
1522
        Cmd::Submodule { cmd } => match cmd {
1523
            SubmoduleCmd::Add {
1524
                url,
1525
                path,
1526
                bookmark,
1527
            } => sync::submodule_add(&url, &path, bookmark.as_deref()),
1528
            SubmoduleCmd::Update { init, paths } => sync::submodule_update(init, &paths),
1529
            SubmoduleCmd::Status { json } => sync::submodule_status(json),
1530
            SubmoduleCmd::Remove { path } => sync::submodule_remove(&path),
1531
        },
1532
        Cmd::Witness {
1533
            cmd:
1534
                WitnessCmd::Serve {
1535
                    name,
1536
                    logs,
1537
                    state,
1538
                    bind,
1539
                    tls_cert,
1540
                    tls_key,
1541
                },
1542
        } => tlog::witness_serve(&name, &logs, state, &bind, tls_cert.zip(tls_key)),
1543
        Cmd::Tlog { cmd } => match cmd {
1544
            TlogCmd::Verify {
1545
                hub,
1546
                key,
1547
                all,
1548
                json,
1549
            } => tlog::verify(hub.as_deref(), key.as_deref(), all, json),
1550
        },
1551
        Cmd::Artifact { cmd } => match cmd {
1552
            ArtifactCmd::Pack {
1553
                dir,
1554
                kind,
1555
                arch,
1556
                os,
1557
                entrypoint,
1558
                env,
1559
                labels,
1560
                json,
1561
            } => artifact::pack(&dir, &kind, arch, os, entrypoint, &env, &labels, json),
1562
            ArtifactCmd::List { json } => artifact::list(json),
1563
            ArtifactCmd::Show { name, json } => artifact::show(&name, json),
1564
            ArtifactCmd::Unpack { name, dest } => artifact::unpack(&name, &dest),
1565
            ArtifactCmd::Verify { name } => artifact::verify(&name),
1566
        },
1567
        Cmd::Receipt { cmd } => match cmd {
1568
            ReceiptCmd::List { rev, json } => receipt::list(rev.as_deref(), json),
1569
            ReceiptCmd::Show {
1570
                receipt: r,
1571
                rev,
1572
                json,
1573
            } => receipt::show(&r, rev.as_deref(), json),
1574
            ReceiptCmd::Export {
1575
                receipt: r,
1576
                file,
1577
                rev,
1578
                format,
1579
            } => receipt::export(&r, &file, rev.as_deref(), &format),
1580
            ReceiptCmd::Verify { file, json } => receipt::verify(&file, json),
1581
            ReceiptCmd::Import { file } => receipt::import(&file),
1582
        },
1583
        Cmd::Tag { cmd } => match cmd {
1584
            TagCmd::Create {
1585
                name,
1586
                changes,
1587
                message,
1588
            } => workspace::tag_create(&name, &changes, &message),
1589
            TagCmd::Delete { name, reason } => workspace::tag_delete(&name, &reason),
1590
            TagCmd::List { json } => workspace::tag_list(json),
1591
        },
1592
        Cmd::Remote { cmd } => match cmd {
1593
            RemoteCmd::Add {
1594
                name,
1595
                url,
1596
                profile,
1597
                region,
1598
                endpoint,
1599
                credentials,
1600
            } => sync::remote_add(
1601
                &name,
1602
                &url,
1603
                &[
1604
                    ("profile", profile),
1605
                    ("region", region),
1606
                    ("endpoint", endpoint),
1607
                    ("credentials", credentials),
1608
                ],
1609
            ),
1610
            RemoteCmd::Check { name } => sync::remote_check(&name),
1611
            RemoteCmd::Remove { name } => sync::remote_remove(&name),
1612
            RemoteCmd::List { json } => sync::remote_list(json),
1613
        },
1614
        Cmd::Fetch { remote, json } => sync::fetch(remote.as_deref(), json),
1615
        Cmd::Pull { remote, json } => sync::pull(remote.as_deref(), json),
1616
        Cmd::Push {
1617
            remote,
1618
            force,
1619
            bookmark,
1620
            delete,
1621
            json,
1622
        } => match delete {
1623
            Some(name) => sync::push_delete(remote.as_deref(), &name, json),
1624
            None => sync::push(remote.as_deref(), force, bookmark.as_deref(), json),
1625
        },
1626
        Cmd::Serve {
1627
            root,
1628
            bind,
1629
            tokens,
1630
            tls_cert,
1631
            tls_key,
1632
        } => sync::serve(root, &bind, tokens, tls_cert.zip(tls_key)),
1633
        Cmd::Identity { cmd } => match cmd {
1634
            IdentityCmd::Create {
1635
                name,
1636
                email,
1637
                local,
1638
                expires,
1639
            } => identity::create(name, email, local, expires),
1640
            IdentityCmd::Show => identity::show(),
1641
            IdentityCmd::Export { path, pem } => identity::export(path, pem),
1642
            IdentityCmd::SignChallenge { challenge, json } => {
1643
                identity::sign_challenge(&challenge, json)
1644
            }
1645
            IdentityCmd::Rotate => identity::rotate(),
1646
            IdentityCmd::Renew { expires } => identity::renew(expires),
1647
            IdentityCmd::Revoke { key, reason } => identity::revoke(key.as_deref(), &reason),
1648
            IdentityCmd::Delegate { cmd } => match cmd {
1649
                DelegateCmd::Add {
1650
                    identity_file,
1651
                    scope,
1652
                    expires,
1653
                } => identity::delegate_add(&identity_file, &scope, expires.as_deref()),
1654
                DelegateCmd::Remove { key } => identity::delegate_remove(&key),
1655
                DelegateCmd::List => identity::delegate_list(),
1656
            },
1657
        },
1658
        Cmd::Git {
1659
            cmd: GitCmd::Colocate { off },
1660
        } => sync::git_colocate(off),
1661
        Cmd::Git {
1662
            cmd: GitCmd::Export { git_dir, branch },
1663
        } => sync::git_export(&git_dir, branch.as_deref()),
1664
        Cmd::Git {
1665
            cmd: GitCmd::Fetch { url, branch, claim },
1666
        } => sync::git_fetch(&url, &branch, claim),
1667
        Cmd::Git {
1668
            cmd: GitCmd::Push { url, branch },
1669
        } => sync::git_push(&url, &branch),
1670
        Cmd::Git {
1671
            cmd: GitCmd::Recover,
1672
        } => sync::git_recover(),
1673
        Cmd::Git {
1674
            cmd:
1675
                GitCmd::Import {
1676
                    git_dir,
1677
                    dest,
1678
                    branch,
1679
                    claim,
1680
                },
1681
        } => sync::git_import(&git_dir, &dest, &branch, claim),
1682
        Cmd::Git {
1683
            cmd:
1684
                GitCmd::Verify {
1685
                    git_dir,
1686
                    branch,
1687
                    last,
1688
                    max_differences,
1689
                },
1690
        } => sync::git_verify(&git_dir, &branch, last, max_differences),
1691
        Cmd::Policy { cmd } => match cmd {
1692
            PolicyCmd::Init => identity::policy_init(),
1693
            PolicyCmd::Show { json } => identity::policy_show(json),
1694
            PolicyCmd::Grant {
1695
                identity_file,
1696
                pattern,
1697
                out,
1698
            } => identity::policy_grant(&identity_file, pattern.as_deref(), out),
1699
            PolicyCmd::GrantSubject {
1700
                subject,
1701
                issuer,
1702
                scope,
1703
                pattern,
1704
                out,
1705
            } => identity::policy_grant_subject(&subject, &issuer, &scope, pattern.as_deref(), out),
1706
            PolicyCmd::Revoke { key, out } => identity::policy_revoke(&key, out),
1707
            PolicyCmd::Root { cmd } => match cmd {
1708
                RootCmd::Add { identity_file, out } => {
1709
                    identity::policy_root_add(&identity_file, out)
1710
                }
1711
                RootCmd::Remove { key, out } => identity::policy_root_remove(&key, out),
1712
                RootCmd::Threshold { n, out } => identity::policy_threshold(n, out),
1713
            },
1714
            PolicyCmd::Sign { proposal, out } => identity::policy_sign(&proposal, out),
1715
        },
1716
        Cmd::Seal {
1717
            flow: Some(url),
1718
            job: Some(job),
1719
            reject,
1720
            json,
1721
            ..
1722
        } => approve::seal(&url, &job, reject, json),
1723
        Cmd::Seal {
1724
            changes,
1725
            proposal: Some(url),
1726
            json,
1727
            ..
1728
        } if changes.is_empty() => proposal::seal(&url, json),
1729
        Cmd::Seal { changes, json, .. } => identity::seal(&changes, json),
1730
        Cmd::Proposal { cmd } => match cmd {
1731
            ProposalCmd::Show { url, json } => proposal::show(&url, json),
1732
            ProposalCmd::Land { url, force } => proposal::land(&url, force),
1733
        },
1734
        Cmd::Verify {
1735
            change,
1736
            revset,
1737
            json,
1738
        } => identity::verify(change.as_deref(), revset.as_deref(), json),
1739
        Cmd::Config {
1740
            key,
1741
            value,
1742
            user,
1743
            unset,
1744
        } => identity::config(&key, value.as_deref().unwrap_or(""), user, unset),
1745
    }
1746
}
1747
1748
#[cfg(test)]
1749
mod help_tests {
1750
    use super::Cli;
1751
    use clap::CommandFactory;
1752
1753
    /// Every command and every argument explains itself, so `--help`,
1754
    /// completions and the man pages are complete.
1755
    #[test]
1756
    fn every_command_and_argument_has_help() {
1757
        fn walk(cmd: &clap::Command, path: &str, missing: &mut Vec<String>) {
1758
            let here = format!("{path} {}", cmd.get_name()).trim().to_string();
1759
            if cmd.get_about().is_none() && !path.is_empty() {
1760
                missing.push(format!("{here} (command)"));
1761
            }
1762
            for a in cmd.get_arguments() {
1763
                let id = a.get_id().as_str();
1764
                if id == "help" || id == "version" || (a.is_global_set() && !path.is_empty()) {
1765
                    continue;
1766
                }
1767
                if a.get_help().is_none() && a.get_long_help().is_none() {
1768
                    missing.push(format!("{here} {id}"));
1769
                }
1770
            }
1771
            for sub in cmd.get_subcommands() {
1772
                walk(sub, &here, missing);
1773
            }
1774
        }
1775
        let mut missing = Vec::new();
1776
        walk(&Cli::command(), "", &mut missing);
1777
        assert!(
1778
            missing.is_empty(),
1779
            "{} without help:\n{}",
1780
            missing.len(),
1781
            missing.join("\n")
1782
        );
1783
    }
1784
}