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