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