OXYGENHUB
# b582948f1912 oxygen / src / cli / mod.rs
44.2 KiB · Rust · last changed Sealed approvals: the approval attestation and oxy seal --flow 21 days ago source blame history raw
1
//! Command-line definitions and dispatch.
2
3
mod approve;
4
mod auth;
5
mod format;
6
mod identity;
7
mod json;
8
mod proposal;
9
mod receipt;
10
mod sync;
11
pub mod ui;
12
mod workspace;
13
14
use anyhow::{Context, Result};
15
use clap::{Parser, Subcommand};
16
use oxy_core::repo::Repo;
17
use std::path::PathBuf;
18
19
#[derive(Parser)]
20
#[command(
21
    name = "oxy",
22
    version = env!("OXY_VERSION_LONG"),
23
    about = "Oxygen: breathing fresh air into version control"
24
)]
25
struct Cli {
26
    /// Plain output: no colour, no spinner (also implied by NO_COLOR or a non-terminal)
27
    #[arg(long, global = true)]
28
    plain: bool,
29
    #[command(subcommand)]
30
    cmd: Cmd,
31
}
32
33
#[derive(Subcommand)]
34
enum Cmd {
35
    /// Create a repository in PATH (default: current directory)
36
    Init {
37
        /// Directory to create the repository in (default: the current directory)
38
        path: Option<PathBuf>,
39
        /// No working copy: an object store and references only, for hosting
40
        #[arg(long)]
41
        bare: bool,
42
    },
43
    /// Clone a repository from a local path or an http(s) URL
44
    Clone {
45
        /// Local path or http(s) URL of the repository
46
        url: String,
47
        /// Directory to clone into (default: the last part of the URL)
48
        dest: Option<PathBuf>,
49
        /// Leave blobs larger than this (e.g. 1M) to be fetched on first read
50
        #[arg(long)]
51
        max_blob: Option<String>,
52
        /// Materialize only these paths (repeatable); implies lazy blobs
53
        #[arg(long = "sparse")]
54
        sparse: Vec<String>,
55
        /// Shallow clone: fetch only this many levels of history below the heads
56
        #[arg(long)]
57
        depth: Option<u32>,
58
    },
59
    /// Fetch more history below a shallow clone's boundary
60
    Deepen {
61
        /// Levels of history to add below the boundary
62
        #[arg(default_value_t = 10)]
63
        depth: u32,
64
        /// Remote to fetch the history from
65
        #[arg(long, default_value = "origin")]
66
        remote: String,
67
    },
68
    /// Show or set the sparse filter (paths to materialize); re-checks out the bookmark
69
    Sparse {
70
        /// Paths to materialize; none prints the current filter
71
        paths: Vec<String>,
72
    },
73
    /// Show the working copy: changed paths and conflicts
74
    Status {
75
        /// Machine-readable output: paths, and every conflict with its kind and contributing changes
76
        #[arg(long)]
77
        json: bool,
78
    },
79
    /// One-line summary for shell prompts; fast and records nothing
80
    Prompt {
81
        /// 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
82
        #[arg(long, default_value = oxy_core::repo::DEFAULT_PROMPT_FORMAT)]
83
        format: String,
84
        /// Glyph format (%i %b %c %s%U%O) instead of the plain default
85
        #[arg(long)]
86
        glyphs: bool,
87
        /// Colour by state (cyan clean, yellow dirty, red conflicted): raw escapes, or guarded for a bash or zsh PS1
88
        #[arg(long, value_parser = ["raw", "bash", "zsh"])]
89
        color: Option<String>,
90
    },
91
    /// Record the working copy as a change on the current bookmark
92
    Commit {
93
        /// The change's message: a subject line, then optionally a blank line and a body
94
        #[arg(short, long, required_unless_present = "file", conflicts_with = "file")]
95
        message: Option<String>,
96
        /// Read the message from FILE (`-` for standard input)
97
        #[arg(short = 'F', long, value_name = "FILE")]
98
        file: Option<PathBuf>,
99
        /// Extra explicit dependencies (ChangeId prefix, #hash prefix)
100
        #[arg(long = "depends-on")]
101
        depends_on: Vec<String>,
102
        /// Commit only these paths; the rest stays as uncommitted work
103
        paths: Vec<String>,
104
        /// Choose hunks one by one
105
        #[arg(short, long)]
106
        interactive: bool,
107
        /// Commit these hunks (as `oxy hunks` numbers them), comma separated
108
        #[arg(long, value_delimiter = ',')]
109
        hunks: Vec<usize>,
110
    },
111
    /// Fold CHANGE into one of its dependencies (keeps that change's id)
112
    Squash {
113
        /// The change to fold (ChangeId prefix, #hash prefix)
114
        change: String,
115
        /// The dependency that absorbs it
116
        #[arg(long)]
117
        into: String,
118
    },
119
    /// Re-express CHANGE against another base state
120
    Rebase {
121
        /// The change to re-express (ChangeId prefix, #hash prefix)
122
        change: String,
123
        /// The changes, bookmark or tag whose state becomes the new base
124
        #[arg(long, required = true, num_args = 1..)]
125
        onto: Vec<String>,
126
    },
127
    /// Show which change introduced each line of a file
128
    Blame {
129
        /// File to annotate, relative to the repository root
130
        path: String,
131
        /// Machine-readable output: one JSON document on stdout
132
        #[arg(long)]
133
        json: bool,
134
    },
135
    /// Find the change that introduced a regression
136
    Bisect {
137
        #[command(subcommand)]
138
        cmd: BisectCmd,
139
    },
140
    /// List changes reachable from the bookmark and the working copy
141
    Log {
142
        /// Show at most this many changes
143
        #[arg(short = 'n', long)]
144
        limit: Option<usize>,
145
        /// Show full messages, dependencies, and signatures
146
        #[arg(short, long)]
147
        verbose: bool,
148
        /// Only changes touching this path (renames followed)
149
        #[arg(long)]
150
        path: Option<String>,
151
        /// Only changes that wrote or deleted lines START to END of PATH
152
        /// (numbered as in the working copy's base), or deleted lines from
153
        /// between them: the history of a function
154
        #[arg(short = 'L', value_name = "START,END:PATH", conflicts_with = "path")]
155
        lines: Option<String>,
156
        /// Machine-readable output: one JSON document on stdout
157
        #[arg(long)]
158
        json: bool,
159
    },
160
    /// Show what the working copy changes against its base
161
    Diff {
162
        /// A change instead of the working copy
163
        change: Option<String>,
164
        /// Machine-readable output: one JSON document on stdout
165
        #[arg(long)]
166
        json: bool,
167
    },
168
    /// Print a file as it is in a state (default: the working copy's base)
169
    Cat {
170
        /// File to print, relative to the repository root
171
        path: String,
172
        /// A change, bookmark, or tag
173
        #[arg(short = 'r', long)]
174
        change: Option<String>,
175
    },
176
    /// Print the repository root, workspace, and bookmark
177
    Root {
178
        /// Machine-readable output: one JSON document on stdout
179
        #[arg(long)]
180
        json: bool,
181
    },
182
    /// Print the version of oxy, its repository format, and protocol
183
    Version {
184
        /// Machine-readable output: one JSON document on stdout
185
        #[arg(long)]
186
        json: bool,
187
    },
188
    /// Restore paths to the working copy's base, or undo chosen hunks
189
    Discard {
190
        /// Paths to restore; none with --hunks, or everything with neither
191
        paths: Vec<String>,
192
        /// Hunk indices as `oxy hunks` numbers them, comma separated
193
        #[arg(long, value_delimiter = ',')]
194
        hunks: Vec<usize>,
195
    },
196
    /// List the working copy's hunks, numbered as commit --hunks expects
197
    Hunks {
198
        /// Machine-readable output: one JSON document on stdout
199
        #[arg(long)]
200
        json: bool,
201
    },
202
    /// With -m, change the message of a head; without, name the working
203
    /// copy for a build: its tag, or the nearest tag plus distance and
204
    /// change, or the bookmark and change, and -dirty
205
    Describe {
206
        /// The new message
207
        #[arg(short, long)]
208
        message: Option<String>,
209
        /// The head to describe (default: the one the working copy sits on)
210
        change: Option<String>,
211
        /// Machine-readable output (naming only)
212
        #[arg(long, conflicts_with = "message")]
213
        json: bool,
214
    },
215
    /// Fold the working copy into the head it sits on, or into CHANGE with --into
216
    Amend {
217
        /// Replace the message too
218
        #[arg(short, long)]
219
        message: Option<String>,
220
        /// Amend an older change; the edits must touch only lines it already knows
221
        #[arg(long)]
222
        into: Option<String>,
223
    },
224
    /// Split a head: the named paths become a separate first change
225
    Split {
226
        /// The head to split
227
        change: String,
228
        /// Paths whose edits become the first change
229
        paths: Vec<String>,
230
    },
231
    /// Drop a head from the bookmark; its content stays on disk as uncommitted work
232
    Abandon {
233
        /// The head to drop (ChangeId prefix, #hash prefix)
234
        change: String,
235
    },
236
    /// Show one change (ChangeId prefix, #hash prefix, or @)
237
    Show {
238
        /// ChangeId prefix, #hash prefix, or @ for the working copy
239
        change: String,
240
        /// Machine-readable output: one JSON document on stdout
241
        #[arg(long)]
242
        json: bool,
243
    },
244
    /// Move the working copy to the state formed by CHANGE... (default: the bookmark heads)
245
    Checkout {
246
        /// Changes whose state to check out (default: the bookmark heads)
247
        changes: Vec<String>,
248
        /// Throw away uncommitted working-copy changes
249
        #[arg(long)]
250
        discard: bool,
251
        /// Take uncommitted changes along; refused when the target has
252
        /// other versions of the files they touch
253
        #[arg(long, conflicts_with = "discard")]
254
        carry: bool,
255
    },
256
    /// Report which conflicts of the working copy's base are resolved by the current files
257
    Resolve {
258
        /// Machine-readable output: one JSON document on stdout
259
        #[arg(long)]
260
        json: bool,
261
    },
262
    /// Undo the last operation
263
    Undo,
264
    /// Write a checkpoint of the current bookmark's state now
265
    Checkpoint,
266
    /// Print a shell completion script: `oxy completions bash > ~/.local/share/bash-completion/completions/oxy`
267
    Completions {
268
        /// bash, zsh, fish, elvish or powershell
269
        shell: clap_complete::Shell,
270
    },
271
    /// Write man pages (oxy.1 and one per command) into DIR, or print oxy.1
272
    Man {
273
        /// Directory to write every page into, e.g. ~/.local/share/man/man1
274
        #[arg(long)]
275
        dir: Option<PathBuf>,
276
    },
277
    /// Check the identity, configuration and remotes, and say what to do about any problem
278
    Doctor {
279
        /// Do not contact the remotes
280
        #[arg(long)]
281
        offline: bool,
282
        /// Machine-readable output: one JSON document on stdout
283
        #[arg(long)]
284
        json: bool,
285
    },
286
    /// Check the repository's integrity: objects, operation log, references, signatures, checkpoints
287
    Fsck {
288
        /// Machine-readable output: one JSON document on stdout
289
        #[arg(long)]
290
        json: bool,
291
    },
292
    /// Prune unreachable objects older than the grace period and repack everything into one pack
293
    Gc {
294
        /// Ignore the grace period (core.gc-grace) and prune immediately
295
        #[arg(long)]
296
        now: bool,
297
    },
298
    /// List operations
299
    #[command(name = "op")]
300
    Op {
301
        #[command(subcommand)]
302
        cmd: OpCmd,
303
    },
304
    /// Take the advisory local lock on a lockable file, making it writable
305
    Lock {
306
        /// The lockable file
307
        path: String,
308
    },
309
    /// Release the local lock and make the file read-only again
310
    Unlock {
311
        /// The locked file
312
        path: String,
313
    },
314
    /// Workspaces: extra checkout directories sharing this repository
315
    Workspace {
316
        #[command(subcommand)]
317
        cmd: WorkspaceCmd,
318
    },
319
    /// Bookmarks: named states; each workspace works on one
320
    Bookmark {
321
        #[command(subcommand)]
322
        cmd: BookmarkCmd,
323
    },
324
    /// Union another bookmark's heads into the current one (no merge change)
325
    Merge {
326
        /// The bookmark whose heads to add
327
        bookmark: String,
328
    },
329
    /// Sign in to a hub once, for every repository on it
330
    Auth {
331
        #[command(subcommand)]
332
        cmd: AuthCmd,
333
    },
334
    /// Subrepositories: nested repositories pinned to a state
335
    Submodule {
336
        #[command(subcommand)]
337
        cmd: SubmoduleCmd,
338
    },
339
    /// Execution receipts: signed records of what a runner ran on a state
340
    Receipt {
341
        #[command(subcommand)]
342
        cmd: ReceiptCmd,
343
    },
344
    /// Tags: immutable named states
345
    Tag {
346
        #[command(subcommand)]
347
        cmd: TagCmd,
348
    },
349
    /// Manage remotes
350
    Remote {
351
        #[command(subcommand)]
352
        cmd: RemoteCmd,
353
    },
354
    /// Fetch every bookmark of a remote into its tracking references
355
    Fetch {
356
        /// Remote name (default: origin)
357
        remote: Option<String>,
358
        /// Machine-readable output: one JSON document on stdout
359
        #[arg(long)]
360
        json: bool,
361
    },
362
    /// Fetch, then union the remote bookmark into the local one (no merge change)
363
    Pull {
364
        /// Remote name (default: origin)
365
        remote: Option<String>,
366
        /// Machine-readable output: one JSON document on stdout
367
        #[arg(long)]
368
        json: bool,
369
    },
370
    /// Push the current bookmark to a remote
371
    Push {
372
        /// Remote name (default: origin)
373
        remote: Option<String>,
374
        /// Allow dropping heads the remote has
375
        #[arg(long)]
376
        force: bool,
377
        /// Push this bookmark instead of the workspace's current one
378
        #[arg(short = 'b', long)]
379
        bookmark: Option<String>,
380
        /// Delete this bookmark on the remote (never its default bookmark);
381
        /// the local bookmark is kept
382
        #[arg(long, value_name = "NAME", conflicts_with_all = ["bookmark", "force"])]
383
        delete: Option<String>,
384
        /// Machine-readable output: one JSON document on stdout
385
        #[arg(long)]
386
        json: bool,
387
    },
388
    /// Serve repositories under ROOT over HTTPS (with --tls-cert/--tls-key) or plain HTTP
389
    Serve {
390
        /// Directory with one repository per subdirectory
391
        #[arg(long, default_value = ".")]
392
        root: PathBuf,
393
        /// Address and port to listen on
394
        #[arg(long, default_value = "127.0.0.1:8890")]
395
        bind: String,
396
        /// Bearer token allowed to push (repeatable); none means open
397
        #[arg(long = "token")]
398
        tokens: Vec<String>,
399
        /// PEM certificate chain; enables HTTPS together with --tls-key
400
        #[arg(long, requires = "tls_key")]
401
        tls_cert: Option<PathBuf>,
402
        /// PEM private key
403
        #[arg(long, requires = "tls_cert")]
404
        tls_key: Option<PathBuf>,
405
    },
406
    /// Manage the signing identity
407
    Identity {
408
        #[command(subcommand)]
409
        cmd: IdentityCmd,
410
    },
411
    /// Seal changes with your key: named ones, or every change on the current bookmark you can authenticate but have not
412
    Seal {
413
        /// Changes to seal (default: every change on the bookmark you can authenticate and have not sealed)
414
        changes: Vec<String>,
415
        /// Seal every change of a hub proposal and push the seal (your approval)
416
        #[arg(long, conflicts_with = "changes")]
417
        proposal: Option<String>,
418
        /// Approve a job of a hub run that waits for a sealed approval: `--flow https://hub/OWNER/NAME/flow/N --job apply`
419
        #[arg(long, conflicts_with_all = ["changes", "proposal"], requires = "job")]
420
        flow: Option<String>,
421
        /// The job to approve, with --flow
422
        #[arg(long, requires = "flow")]
423
        job: Option<String>,
424
        /// Reject the job instead of approving it, with --flow
425
        #[arg(long, requires = "flow")]
426
        reject: bool,
427
        /// Machine-readable output: one JSON document on stdout
428
        #[arg(long)]
429
        json: bool,
430
    },
431
    /// Hub proposals: show one, or land it from this client
432
    Proposal {
433
        #[command(subcommand)]
434
        cmd: ProposalCmd,
435
    },
436
    /// Verify the signatures on a change (default: every change in the log)
437
    Verify {
438
        /// The change to verify (default: every change in the log)
439
        change: Option<String>,
440
        /// Machine-readable output: one JSON document on stdout
441
        #[arg(long)]
442
        json: bool,
443
    },
444
    /// Git interoperability
445
    Git {
446
        #[command(subcommand)]
447
        cmd: GitCmd,
448
    },
449
    /// Manage the trust policy (who may update which bookmarks)
450
    Policy {
451
        #[command(subcommand)]
452
        cmd: PolicyCmd,
453
    },
454
    /// Set a configuration key (author.*, core.sign, core.op-retention, core.gc-grace, core.checkpoint-interval, filter.max-blob, filter.paths, workspace.bookmark, remote.<name>.url|token|ca, auth.helper with --user)
455
    Config {
456
        /// The key, such as author.name or remote.origin.token
457
        key: String,
458
        /// The value to set
459
        value: String,
460
        /// Write to the user file (~/.config/oxy/config.toml) instead of this repository
461
        #[arg(long)]
462
        user: bool,
463
    },
464
}
465
466
#[derive(Subcommand)]
467
enum OpCmd {
468
    /// List operations, newest first
469
    Log {
470
        /// Machine-readable output: one JSON document on stdout
471
        #[arg(long)]
472
        json: bool,
473
    },
474
}
475
476
#[derive(Subcommand)]
477
enum WorkspaceCmd {
478
    /// Create a workspace at PATH checked out on CHANGE... (default: the bookmark heads)
479
    Add {
480
        /// Directory for the new workspace (must be empty or absent)
481
        path: PathBuf,
482
        /// Changes whose state to check out there
483
        changes: Vec<String>,
484
    },
485
    /// List workspaces and their working-copy changes
486
    List {
487
        /// Machine-readable output: one JSON document on stdout
488
        #[arg(long)]
489
        json: bool,
490
    },
491
    /// Stop tracking a workspace (by id prefix or path); its files stay
492
    Forget {
493
        /// Workspace id prefix or path
494
        workspace: String,
495
    },
496
}
497
498
#[derive(Subcommand)]
499
enum BisectCmd {
500
    /// Begin; remembers where the working copy was
501
    Start,
502
    /// Mark CHANGE... (or the state under test) as good
503
    Good {
504
        /// Changes known to be good (default: the state under test)
505
        changes: Vec<String>,
506
    },
507
    /// Mark CHANGE... (or the state under test) as bad
508
    Bad {
509
        /// Changes known to be bad (default: the state under test)
510
        changes: Vec<String>,
511
    },
512
    /// The state under test cannot be tested; try another
513
    Skip,
514
    /// Run a command for each step: exit 0 good, 125 skip, else bad
515
    Run {
516
        /// Command and arguments to run at each step
517
        #[arg(required = true, trailing_var_arg = true)]
518
        command: Vec<String>,
519
    },
520
    /// Where the search stands
521
    Status {
522
        /// Machine-readable output: one JSON document on stdout
523
        #[arg(long)]
524
        json: bool,
525
    },
526
    /// Restore the working copy and forget the search
527
    Reset,
528
}
529
530
#[derive(Subcommand)]
531
enum BookmarkCmd {
532
    /// Create a bookmark at CHANGE... (default: the working copy's base)
533
    Create {
534
        /// Name of the new bookmark
535
        name: String,
536
        /// Its heads (default: the working copy's base). A state is its
537
        /// heads and what they depend on: a change alone may leave out
538
        /// earlier changes of the current state, which is refused unless
539
        /// --upto or --only says which is meant
540
        changes: Vec<String>,
541
        /// Everything of the current state up to CHANGE..., as a Git
542
        /// branch at a commit would hold
543
        #[arg(long, conflicts_with = "only")]
544
        upto: bool,
545
        /// Just CHANGE... and what they depend on
546
        #[arg(long)]
547
        only: bool,
548
    },
549
    /// Point an existing bookmark at CHANGE...
550
    Set {
551
        /// The bookmark to move
552
        name: String,
553
        /// Its new heads
554
        changes: Vec<String>,
555
    },
556
    /// Remove a bookmark; its changes stay
557
    Delete {
558
        /// The bookmark to remove
559
        name: String,
560
    },
561
    /// List bookmarks with their heads and difference from origin
562
    List {
563
        /// Machine-readable output: one JSON document on stdout
564
        #[arg(long)]
565
        json: bool,
566
    },
567
    /// Make NAME this workspace's bookmark and check it out. Uncommitted work stops it; --carry takes the work along, --discard drops it
568
    Switch {
569
        /// The bookmark to work on
570
        name: String,
571
        /// Throw away uncommitted working-copy changes
572
        #[arg(long)]
573
        discard: bool,
574
        /// Take uncommitted changes along; refused when NAME has other
575
        /// versions of the files they touch
576
        #[arg(long, conflicts_with = "discard")]
577
        carry: bool,
578
    },
579
}
580
581
#[derive(Subcommand)]
582
enum AuthCmd {
583
    /// Sign in to HUB in the browser (device sign-in) and keep the token for
584
    /// every repository there
585
    Login {
586
        /// The hub, as https://oxygenhub.io or oxygenhub.io (default: this checkout's origin)
587
        hub: Option<String>,
588
        /// Read a token from standard input instead (for CI and scripts)
589
        #[arg(long)]
590
        with_token: bool,
591
        /// PEM file of extra roots to trust (a hub with a self-signed certificate)
592
        #[arg(long)]
593
        ca: Option<PathBuf>,
594
    },
595
    /// List the hubs you are signed in to, checking each token with its hub
596
    Status,
597
    /// Forget HUB's token and revoke it on the hub
598
    Logout {
599
        /// The hub (default: this checkout's origin, or the only one)
600
        hub: Option<String>,
601
    },
602
}
603
604
#[derive(Subcommand)]
605
enum SubmoduleCmd {
606
    /// Clone URL (Oxygen or Git) into PATH and register it in .oxymodules
607
    Add {
608
        /// URL or path of the Oxygen or Git repository
609
        url: String,
610
        /// Where to put it, relative to the repository root
611
        path: String,
612
        /// Bookmark (Oxygen) or branch (Git) to check out and track
613
        #[arg(long)]
614
        bookmark: Option<String>,
615
    },
616
    /// Bring nested repositories to their pins
617
    Update {
618
        /// Clone nested repositories that are absent
619
        #[arg(long)]
620
        init: bool,
621
        /// Subrepos to update (default: all)
622
        paths: Vec<String>,
623
    },
624
    /// List subrepos with their pins and on-disk state
625
    Status {
626
        /// Machine-readable output: one JSON document on stdout
627
        #[arg(long)]
628
        json: bool,
629
    },
630
    /// Unregister PATH; the directory stays, the node goes with the next commit
631
    Remove {
632
        /// The subrepo to unregister
633
        path: String,
634
    },
635
}
636
637
#[derive(Subcommand)]
638
enum ReceiptCmd {
639
    /// The receipts kept for a state (default: the bookmark heads)
640
    List {
641
        /// Change, bookmark or tag whose state to look at
642
        rev: Option<String>,
643
        /// Machine-readable output: one JSON document on stdout
644
        #[arg(long)]
645
        json: bool,
646
    },
647
    /// One receipt in full, and whether its signature verifies
648
    Show {
649
        /// The receipt (a prefix of its hash, as `list` shows it)
650
        receipt: String,
651
        /// Change, bookmark or tag whose state holds it
652
        #[arg(long)]
653
        rev: Option<String>,
654
        /// Machine-readable output: one JSON document on stdout
655
        #[arg(long)]
656
        json: bool,
657
    },
658
    /// Write a signed receipt to FILE
659
    Export {
660
        /// The receipt (a prefix of its hash, as `list` shows it)
661
        receipt: String,
662
        /// Where to write it
663
        file: String,
664
        /// Change, bookmark or tag whose state holds it
665
        #[arg(long)]
666
        rev: Option<String>,
667
    },
668
    /// Check a signed receipt in FILE without keeping it
669
    Verify {
670
        /// A signed receipt, as a runner or `export` writes it
671
        file: String,
672
        /// Machine-readable output: one JSON document on stdout
673
        #[arg(long)]
674
        json: bool,
675
    },
676
    /// Verify a signed receipt in FILE and keep it with its state
677
    Import {
678
        /// A signed receipt, as a runner or `export` writes it
679
        file: String,
680
    },
681
}
682
683
#[derive(Subcommand)]
684
enum TagCmd {
685
    /// Tag the state of CHANGE... (default: the bookmark heads)
686
    Create {
687
        /// Name of the tag; tags never move
688
        name: String,
689
        /// Changes whose state to tag (default: the bookmark heads)
690
        changes: Vec<String>,
691
        /// A message recorded with the tag
692
        #[arg(short, long, default_value = "")]
693
        message: String,
694
    },
695
    /// List tags and the states they name
696
    List {
697
        /// Machine-readable output: one JSON document on stdout
698
        #[arg(long)]
699
        json: bool,
700
    },
701
}
702
703
#[derive(Subcommand)]
704
enum RemoteCmd {
705
    /// Add a remote
706
    Add {
707
        /// Name to refer to the remote by, such as origin
708
        name: String,
709
        /// Local path or http(s) URL of the repository
710
        url: String,
711
    },
712
    /// Remove a remote
713
    Remove {
714
        /// The remote to remove
715
        name: String,
716
    },
717
    /// List remotes and their URLs
718
    List {
719
        /// Machine-readable output: one JSON document on stdout
720
        #[arg(long)]
721
        json: bool,
722
    },
723
}
724
725
#[derive(Subcommand)]
726
enum ProposalCmd {
727
    /// Show a proposal by its hub URL
728
    Show {
729
        /// The proposal's URL on the hub
730
        url: String,
731
        /// Machine-readable output: one JSON document on stdout
732
        #[arg(long)]
733
        json: bool,
734
    },
735
    /// Fetch the proposal's changes, set the target bookmark to the projected state, and push with your key
736
    Land {
737
        /// The proposal's URL on the hub
738
        url: String,
739
        /// Land even when the hub reports blockers
740
        #[arg(long)]
741
        force: bool,
742
    },
743
}
744
745
#[derive(Subcommand)]
746
enum IdentityCmd {
747
    /// Generate a composite Ed25519 + ML-DSA-65 key pair and make it your author identity
748
    Create {
749
        /// Your name (default: author.name)
750
        #[arg(long)]
751
        name: Option<String>,
752
        /// Your email (default: author.email)
753
        #[arg(long)]
754
        email: Option<String>,
755
        /// Record the author in this repository only, not in the user config
756
        #[arg(long)]
757
        local: bool,
758
        /// Expire the identity this many days from now
759
        #[arg(long)]
760
        expires: Option<u64>,
761
    },
762
    /// Show the configured identity
763
    Show,
764
    /// Write your identity object to a file, to hand to a policy holder
765
    Export {
766
        /// File to write (default: <key>.identity in the current directory)
767
        path: Option<PathBuf>,
768
    },
769
    /// Sign a host's challenge (hex, at least 16 bytes) to prove you hold your key; prints the signature as hex
770
    SignChallenge {
771
        /// The host's challenge, as hex
772
        challenge: String,
773
        /// Machine-readable output: one JSON document on stdout
774
        #[arg(long)]
775
        json: bool,
776
    },
777
    /// Move to a fresh key pair; the policy follows if it names your key
778
    Rotate,
779
    /// Re-issue your identity with a new expiry (in days from now; 0 = never)
780
    Renew {
781
        /// Days from now until it expires; 0 for never
782
        #[arg(long)]
783
        expires: u64,
784
    },
785
    /// Revoke a key: yours by default, or any key if you hold a policy root
786
    Revoke {
787
        /// KeyId prefix (default: your own key)
788
        key: Option<String>,
789
        /// Why, recorded in the revocation
790
        #[arg(long, default_value = "")]
791
        reason: String,
792
    },
793
    /// Keys allowed to sign or seal on your behalf
794
    Delegate {
795
        #[command(subcommand)]
796
        cmd: DelegateCmd,
797
    },
798
}
799
800
#[derive(Subcommand)]
801
enum DelegateCmd {
802
    /// Add a delegate from an exported identity file
803
    Add {
804
        /// The delegate's exported identity file
805
        identity_file: PathBuf,
806
    },
807
    /// Remove a delegate by KeyId prefix
808
    Remove {
809
        /// KeyId prefix of the delegate
810
        key: String,
811
    },
812
    /// List delegates
813
    List,
814
}
815
816
#[derive(Subcommand)]
817
enum GitCmd {
818
    /// Export the current bookmark to a Git repository (created bare if absent)
819
    Export {
820
        /// Git repository to write to (created bare if absent)
821
        git_dir: PathBuf,
822
        /// Git branch to write (default: the bookmark name)
823
        #[arg(long)]
824
        branch: Option<String>,
825
    },
826
    /// Fetch a branch from a Git remote (path or URL) into the current bookmark
827
    Fetch {
828
        /// Git remote: a path or URL
829
        url: String,
830
        /// Branch to fetch
831
        #[arg(long, default_value = "main")]
832
        branch: String,
833
    },
834
    /// Push the current bookmark to a branch of a Git remote (fetch first)
835
    Push {
836
        /// Git remote: a path or URL
837
        url: String,
838
        /// Branch to push to
839
        #[arg(long, default_value = "main")]
840
        branch: String,
841
    },
842
    /// Check this repository's import of a Git branch: every commit's tree must be reproduced exactly
843
    Verify {
844
        /// The Git repository the import came from
845
        git_dir: PathBuf,
846
        /// Branch that was imported
847
        #[arg(long, default_value = "main")]
848
        branch: String,
849
    },
850
    /// Import a Git branch into a new Oxygen repository at DEST
851
    Import {
852
        /// Git repository to read
853
        git_dir: PathBuf,
854
        /// Directory for the new Oxygen repository
855
        dest: PathBuf,
856
        /// Branch to import
857
        #[arg(long, default_value = "main")]
858
        branch: String,
859
    },
860
}
861
862
#[derive(Subcommand)]
863
enum PolicyCmd {
864
    /// Create the initial policy with your identity as the only root
865
    Init,
866
    /// Show the current policy
867
    Show {
868
        /// Machine-readable output: one JSON document on stdout
869
        #[arg(long)]
870
        json: bool,
871
    },
872
    /// Allow an identity (from `oxy identity export`) to update bookmarks
873
    Grant {
874
        /// The identity to grant, exported with `oxy identity export`
875
        identity_file: PathBuf,
876
        /// Reference pattern the grant applies to (default: every bookmark)
877
        #[arg(long)]
878
        pattern: Option<String>,
879
        /// Where to write the proposal when more root signatures are needed
880
        #[arg(long)]
881
        out: Option<PathBuf>,
882
    },
883
    /// Revoke a key (KeyId prefix of an identity in the policy)
884
    Revoke {
885
        /// KeyId prefix of the identity
886
        key: String,
887
        /// Where to write the proposal when more root signatures are needed
888
        #[arg(long)]
889
        out: Option<PathBuf>,
890
    },
891
    /// Manage root keys and the signature threshold for policy updates
892
    Root {
893
        #[command(subcommand)]
894
        cmd: RootCmd,
895
    },
896
    /// Add your root signature to a proposal file; applies it once the threshold is met
897
    Sign {
898
        /// The proposal file to sign
899
        proposal: PathBuf,
900
        /// Where to write the proposal if it still needs signatures (default: in place)
901
        #[arg(long)]
902
        out: Option<PathBuf>,
903
    },
904
}
905
906
#[derive(Subcommand)]
907
enum RootCmd {
908
    /// Make an exported identity a root key
909
    Add {
910
        /// The identity to make a root, exported with `oxy identity export`
911
        identity_file: PathBuf,
912
        /// Where to write the proposal when more root signatures are needed
913
        #[arg(long)]
914
        out: Option<PathBuf>,
915
    },
916
    /// Remove a root key by KeyId prefix
917
    Remove {
918
        /// KeyId prefix of the root key
919
        key: String,
920
        /// Where to write the proposal when more root signatures are needed
921
        #[arg(long)]
922
        out: Option<PathBuf>,
923
    },
924
    /// Require this many root signatures on policy updates
925
    Threshold {
926
        /// Number of root signatures
927
        n: u32,
928
        /// Where to write the proposal when more root signatures are needed
929
        #[arg(long)]
930
        out: Option<PathBuf>,
931
    },
932
}
933
934
/// Open the repository containing the current directory.
935
fn open() -> Result<Repo> {
936
    Repo::open(&std::env::current_dir()?).context("opening repository")
937
}
938
939
/// `oxy man`: every page into `dir`, or the top-level page on stdout.
940
fn man(dir: Option<PathBuf>) -> Result<i32> {
941
    use clap::CommandFactory;
942
    let cmd = Cli::command();
943
    match dir {
944
        Some(dir) => {
945
            std::fs::create_dir_all(&dir)?;
946
            clap_mangen::generate_to(cmd, &dir)?;
947
            let pages = std::fs::read_dir(&dir)?
948
                .filter(|e| {
949
                    e.as_ref()
950
                        .is_ok_and(|e| e.path().extension().is_some_and(|x| x == "1"))
951
                })
952
                .count();
953
            println!(
954
                "{}",
955
                ui::done(format!("Wrote {pages} man pages to {}", dir.display()))
956
            );
957
        }
958
        None => clap_mangen::Man::new(cmd).render(&mut std::io::stdout())?,
959
    }
960
    Ok(0)
961
}
962
963
/// Parse arguments and run; returns the process exit code.
964
pub fn run() -> Result<i32> {
965
    let cli = Cli::parse();
966
    ui::init(cli.plain);
967
    match cli.cmd {
968
        Cmd::Completions { shell } => {
969
            use clap::CommandFactory;
970
            clap_complete::generate(shell, &mut Cli::command(), "oxy", &mut std::io::stdout());
971
            Ok(0)
972
        }
973
        Cmd::Man { dir } => man(dir),
974
        Cmd::Init { path, bare } => workspace::init(path, bare),
975
        Cmd::Status { json } => workspace::status(json),
976
        Cmd::Prompt {
977
            format,
978
            glyphs,
979
            color,
980
        } => workspace::prompt(&format, glyphs, color.as_deref()),
981
        Cmd::Commit {
982
            message,
983
            file,
984
            depends_on,
985
            paths,
986
            interactive,
987
            hunks,
988
        } => {
989
            let message = match (message, file) {
990
                (Some(m), _) => m,
991
                (None, Some(f)) if f.as_os_str() == "-" => {
992
                    let mut s = String::new();
993
                    std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
994
                    s
995
                }
996
                (None, Some(f)) => std::fs::read_to_string(&f).map_err(|e| {
997
                    anyhow::anyhow!("reading the message from {}: {e}", f.display())
998
                })?,
999
                (None, None) => anyhow::bail!("a commit message is required (-m or -F)"),
1000
            };
1001
            workspace::commit(&message, &depends_on, &paths, interactive, &hunks)
1002
        }
1003
        Cmd::Cat { path, change } => workspace::cat(&path, change.as_deref()),
1004
        Cmd::Root { json } => workspace::root(json),
1005
        Cmd::Version { json } => workspace::version(json),
1006
        Cmd::Discard { paths, hunks } => workspace::discard(&paths, &hunks),
1007
        Cmd::Hunks { json } => workspace::hunks(json),
1008
        Cmd::Squash { change, into } => workspace::squash(&change, &into),
1009
        Cmd::Rebase { change, onto } => workspace::rebase(&change, &onto),
1010
        Cmd::Blame { path, json } => workspace::blame(&path, json),
1011
        Cmd::Bisect { cmd } => match cmd {
1012
            BisectCmd::Start => workspace::bisect_start(),
1013
            BisectCmd::Good { changes } => workspace::bisect_mark(Some(true), &changes),
1014
            BisectCmd::Bad { changes } => workspace::bisect_mark(Some(false), &changes),
1015
            BisectCmd::Skip => workspace::bisect_mark(None, &[]),
1016
            BisectCmd::Run { command } => workspace::bisect_run(&command),
1017
            BisectCmd::Status { json } => workspace::bisect_status(json),
1018
            BisectCmd::Reset => workspace::bisect_reset(),
1019
        },
1020
        Cmd::Log {
1021
            limit,
1022
            verbose,
1023
            path,
1024
            lines,
1025
            json,
1026
        } => workspace::log(limit, verbose, path.as_deref(), lines.as_deref(), json),
1027
        Cmd::Diff { change, json } => workspace::diff(change.as_deref(), json),
1028
        Cmd::Describe {
1029
            message,
1030
            change,
1031
            json,
1032
        } => match message {
1033
            Some(m) => workspace::describe(&m, change.as_deref()),
1034
            None if change.is_some() => {
1035
                anyhow::bail!(
1036
                    "naming works on the working copy; to change a head's message pass -m"
1037
                )
1038
            }
1039
            None => workspace::describe_name(json),
1040
        },
1041
        Cmd::Amend { message, into } => workspace::amend(message.as_deref(), into.as_deref()),
1042
        Cmd::Split { change, paths } => workspace::split(&change, &paths),
1043
        Cmd::Abandon { change } => workspace::abandon(&change),
1044
        Cmd::Show { change, json } => workspace::show(&change, json),
1045
        Cmd::Checkout {
1046
            changes,
1047
            discard,
1048
            carry,
1049
        } => workspace::checkout(&changes, discard, carry),
1050
        Cmd::Resolve { json } => workspace::resolve(json),
1051
        Cmd::Undo => workspace::undo(),
1052
        Cmd::Gc { now } => workspace::gc(now),
1053
        Cmd::Fsck { json } => workspace::fsck(json),
1054
        Cmd::Doctor { offline, json } => workspace::doctor(offline, json),
1055
        Cmd::Checkpoint => workspace::checkpoint(),
1056
        Cmd::Op {
1057
            cmd: OpCmd::Log { json },
1058
        } => workspace::op_log(json),
1059
        Cmd::Clone {
1060
            url,
1061
            dest,
1062
            max_blob,
1063
            sparse,
1064
            depth,
1065
        } => sync::clone(&url, dest, max_blob.as_deref(), &sparse, depth),
1066
        Cmd::Deepen { depth, remote } => sync::deepen(&remote, depth),
1067
        Cmd::Sparse { paths } => workspace::sparse(&paths),
1068
        Cmd::Lock { path } => workspace::lock(&path),
1069
        Cmd::Unlock { path } => workspace::unlock(&path),
1070
        Cmd::Workspace { cmd } => match cmd {
1071
            WorkspaceCmd::Add { path, changes } => workspace::workspace_add(&path, &changes),
1072
            WorkspaceCmd::List { json } => workspace::workspace_list(json),
1073
            WorkspaceCmd::Forget { workspace } => workspace::workspace_forget(&workspace),
1074
        },
1075
        Cmd::Bookmark { cmd } => match cmd {
1076
            BookmarkCmd::Create {
1077
                name,
1078
                changes,
1079
                upto,
1080
                only,
1081
            } => workspace::bookmark_create(&name, &changes, upto, only),
1082
            BookmarkCmd::Set { name, changes } => workspace::bookmark_set(&name, &changes),
1083
            BookmarkCmd::Delete { name } => workspace::bookmark_delete(&name),
1084
            BookmarkCmd::List { json } => workspace::bookmark_list(json),
1085
            BookmarkCmd::Switch {
1086
                name,
1087
                discard,
1088
                carry,
1089
            } => workspace::bookmark_switch(&name, discard, carry),
1090
        },
1091
        Cmd::Merge { bookmark } => workspace::merge(&bookmark),
1092
        Cmd::Auth { cmd } => match cmd {
1093
            AuthCmd::Login {
1094
                hub,
1095
                with_token,
1096
                ca,
1097
            } => auth::login(hub.as_deref(), with_token, ca),
1098
            AuthCmd::Status => auth::status(),
1099
            AuthCmd::Logout { hub } => auth::logout(hub.as_deref()),
1100
        },
1101
        Cmd::Submodule { cmd } => match cmd {
1102
            SubmoduleCmd::Add {
1103
                url,
1104
                path,
1105
                bookmark,
1106
            } => sync::submodule_add(&url, &path, bookmark.as_deref()),
1107
            SubmoduleCmd::Update { init, paths } => sync::submodule_update(init, &paths),
1108
            SubmoduleCmd::Status { json } => sync::submodule_status(json),
1109
            SubmoduleCmd::Remove { path } => sync::submodule_remove(&path),
1110
        },
1111
        Cmd::Receipt { cmd } => match cmd {
1112
            ReceiptCmd::List { rev, json } => receipt::list(rev.as_deref(), json),
1113
            ReceiptCmd::Show {
1114
                receipt: r,
1115
                rev,
1116
                json,
1117
            } => receipt::show(&r, rev.as_deref(), json),
1118
            ReceiptCmd::Export {
1119
                receipt: r,
1120
                file,
1121
                rev,
1122
            } => receipt::export(&r, &file, rev.as_deref()),
1123
            ReceiptCmd::Verify { file, json } => receipt::verify(&file, json),
1124
            ReceiptCmd::Import { file } => receipt::import(&file),
1125
        },
1126
        Cmd::Tag { cmd } => match cmd {
1127
            TagCmd::Create {
1128
                name,
1129
                changes,
1130
                message,
1131
            } => workspace::tag_create(&name, &changes, &message),
1132
            TagCmd::List { json } => workspace::tag_list(json),
1133
        },
1134
        Cmd::Remote { cmd } => match cmd {
1135
            RemoteCmd::Add { name, url } => sync::remote_add(&name, &url),
1136
            RemoteCmd::Remove { name } => sync::remote_remove(&name),
1137
            RemoteCmd::List { json } => sync::remote_list(json),
1138
        },
1139
        Cmd::Fetch { remote, json } => sync::fetch(remote.as_deref(), json),
1140
        Cmd::Pull { remote, json } => sync::pull(remote.as_deref(), json),
1141
        Cmd::Push {
1142
            remote,
1143
            force,
1144
            bookmark,
1145
            delete,
1146
            json,
1147
        } => match delete {
1148
            Some(name) => sync::push_delete(remote.as_deref(), &name, json),
1149
            None => sync::push(remote.as_deref(), force, bookmark.as_deref(), json),
1150
        },
1151
        Cmd::Serve {
1152
            root,
1153
            bind,
1154
            tokens,
1155
            tls_cert,
1156
            tls_key,
1157
        } => sync::serve(root, &bind, tokens, tls_cert.zip(tls_key)),
1158
        Cmd::Identity { cmd } => match cmd {
1159
            IdentityCmd::Create {
1160
                name,
1161
                email,
1162
                local,
1163
                expires,
1164
            } => identity::create(name, email, local, expires),
1165
            IdentityCmd::Show => identity::show(),
1166
            IdentityCmd::Export { path } => identity::export(path),
1167
            IdentityCmd::SignChallenge { challenge, json } => {
1168
                identity::sign_challenge(&challenge, json)
1169
            }
1170
            IdentityCmd::Rotate => identity::rotate(),
1171
            IdentityCmd::Renew { expires } => identity::renew(expires),
1172
            IdentityCmd::Revoke { key, reason } => identity::revoke(key.as_deref(), &reason),
1173
            IdentityCmd::Delegate { cmd } => match cmd {
1174
                DelegateCmd::Add { identity_file } => identity::delegate_add(&identity_file),
1175
                DelegateCmd::Remove { key } => identity::delegate_remove(&key),
1176
                DelegateCmd::List => identity::delegate_list(),
1177
            },
1178
        },
1179
        Cmd::Git {
1180
            cmd: GitCmd::Export { git_dir, branch },
1181
        } => sync::git_export(&git_dir, branch.as_deref()),
1182
        Cmd::Git {
1183
            cmd: GitCmd::Fetch { url, branch },
1184
        } => sync::git_fetch(&url, &branch),
1185
        Cmd::Git {
1186
            cmd: GitCmd::Push { url, branch },
1187
        } => sync::git_push(&url, &branch),
1188
        Cmd::Git {
1189
            cmd:
1190
                GitCmd::Import {
1191
                    git_dir,
1192
                    dest,
1193
                    branch,
1194
                },
1195
        } => sync::git_import(&git_dir, &dest, &branch),
1196
        Cmd::Git {
1197
            cmd: GitCmd::Verify { git_dir, branch },
1198
        } => sync::git_verify(&git_dir, &branch),
1199
        Cmd::Policy { cmd } => match cmd {
1200
            PolicyCmd::Init => identity::policy_init(),
1201
            PolicyCmd::Show { json } => identity::policy_show(json),
1202
            PolicyCmd::Grant {
1203
                identity_file,
1204
                pattern,
1205
                out,
1206
            } => identity::policy_grant(&identity_file, pattern.as_deref(), out),
1207
            PolicyCmd::Revoke { key, out } => identity::policy_revoke(&key, out),
1208
            PolicyCmd::Root { cmd } => match cmd {
1209
                RootCmd::Add { identity_file, out } => {
1210
                    identity::policy_root_add(&identity_file, out)
1211
                }
1212
                RootCmd::Remove { key, out } => identity::policy_root_remove(&key, out),
1213
                RootCmd::Threshold { n, out } => identity::policy_threshold(n, out),
1214
            },
1215
            PolicyCmd::Sign { proposal, out } => identity::policy_sign(&proposal, out),
1216
        },
1217
        Cmd::Seal {
1218
            flow: Some(url),
1219
            job: Some(job),
1220
            reject,
1221
            json,
1222
            ..
1223
        } => approve::seal(&url, &job, reject, json),
1224
        Cmd::Seal {
1225
            changes,
1226
            proposal: Some(url),
1227
            json,
1228
            ..
1229
        } if changes.is_empty() => proposal::seal(&url, json),
1230
        Cmd::Seal { changes, json, .. } => identity::seal(&changes, json),
1231
        Cmd::Proposal { cmd } => match cmd {
1232
            ProposalCmd::Show { url, json } => proposal::show(&url, json),
1233
            ProposalCmd::Land { url, force } => proposal::land(&url, force),
1234
        },
1235
        Cmd::Verify { change, json } => identity::verify(change.as_deref(), json),
1236
        Cmd::Config { key, value, user } => identity::config(&key, &value, user),
1237
    }
1238
}
1239
1240
#[cfg(test)]
1241
mod help_tests {
1242
    use super::Cli;
1243
    use clap::CommandFactory;
1244
1245
    /// Every command and every argument explains itself, so `--help`,
1246
    /// completions and the man pages are complete.
1247
    #[test]
1248
    fn every_command_and_argument_has_help() {
1249
        fn walk(cmd: &clap::Command, path: &str, missing: &mut Vec<String>) {
1250
            let here = format!("{path} {}", cmd.get_name()).trim().to_string();
1251
            if cmd.get_about().is_none() && path != "" {
1252
                missing.push(format!("{here} (command)"));
1253
            }
1254
            for a in cmd.get_arguments() {
1255
                let id = a.get_id().as_str();
1256
                if id == "help" || id == "version" || a.is_global_set() && path != "" {
1257
                    continue;
1258
                }
1259
                if a.get_help().is_none() && a.get_long_help().is_none() {
1260
                    missing.push(format!("{here} {id}"));
1261
                }
1262
            }
1263
            for sub in cmd.get_subcommands() {
1264
                walk(sub, &here, missing);
1265
            }
1266
        }
1267
        let mut missing = Vec::new();
1268
        walk(&Cli::command(), "", &mut missing);
1269
        assert!(
1270
            missing.is_empty(),
1271
            "{} without help:\n{}",
1272
            missing.len(),
1273
            missing.join("\n")
1274
        );
1275
    }
1276
}