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