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