OXYGENHUB
# 1c2bd9abdd4f oxygen / src / cli / mod.rs
37.3 KiB · Rust · last changed Merges move clean working copies; checkouts say what blocks them 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
        /// Take uncommitted changes along; refused when the target has
236
        /// other versions of the files they touch
237
        #[arg(long, conflicts_with = "discard")]
238
        carry: bool,
239
    },
240
    /// Report which conflicts of the working copy's base are resolved by the current files
241
    Resolve {
242
        /// Machine-readable output: one JSON document on stdout
243
        #[arg(long)]
244
        json: bool,
245
    },
246
    /// Undo the last operation
247
    Undo,
248
    /// Write a checkpoint of the current bookmark's state now
249
    Checkpoint,
250
    /// Print a shell completion script: `oxy completions bash > ~/.local/share/bash-completion/completions/oxy`
251
    Completions {
252
        /// bash, zsh, fish, elvish or powershell
253
        shell: clap_complete::Shell,
254
    },
255
    /// Write man pages (oxy.1 and one per command) into DIR, or print oxy.1
256
    Man {
257
        /// Directory to write every page into, e.g. ~/.local/share/man/man1
258
        #[arg(long)]
259
        dir: Option<PathBuf>,
260
    },
261
    /// Check the identity, configuration and remotes, and say what to do about any problem
262
    Doctor {
263
        /// Do not contact the remotes
264
        #[arg(long)]
265
        offline: bool,
266
        /// Machine-readable output: one JSON document on stdout
267
        #[arg(long)]
268
        json: bool,
269
    },
270
    /// Check the repository's integrity: objects, operation log, references, signatures, checkpoints
271
    Fsck {
272
        /// Machine-readable output: one JSON document on stdout
273
        #[arg(long)]
274
        json: bool,
275
    },
276
    /// Pack loose objects and prune unreachable ones older than the grace period
277
    Gc {
278
        /// Ignore the grace period (core.gc-grace) and prune immediately
279
        #[arg(long)]
280
        now: bool,
281
    },
282
    /// List operations
283
    #[command(name = "op")]
284
    Op {
285
        #[command(subcommand)]
286
        cmd: OpCmd,
287
    },
288
    /// Take the advisory local lock on a lockable file, making it writable
289
    Lock {
290
        /// The lockable file
291
        path: String,
292
    },
293
    /// Release the local lock and make the file read-only again
294
    Unlock {
295
        /// The locked file
296
        path: String,
297
    },
298
    /// Workspaces: extra checkout directories sharing this repository
299
    Workspace {
300
        #[command(subcommand)]
301
        cmd: WorkspaceCmd,
302
    },
303
    /// Bookmarks: named states; each workspace works on one
304
    Bookmark {
305
        #[command(subcommand)]
306
        cmd: BookmarkCmd,
307
    },
308
    /// Union another bookmark's heads into the current one (no merge change)
309
    Merge {
310
        /// The bookmark whose heads to add
311
        bookmark: String,
312
    },
313
    /// Subrepositories: nested repositories pinned to a state
314
    Submodule {
315
        #[command(subcommand)]
316
        cmd: SubmoduleCmd,
317
    },
318
    /// Tags: immutable named states
319
    Tag {
320
        #[command(subcommand)]
321
        cmd: TagCmd,
322
    },
323
    /// Manage remotes
324
    Remote {
325
        #[command(subcommand)]
326
        cmd: RemoteCmd,
327
    },
328
    /// Fetch every bookmark of a remote into its tracking references
329
    Fetch {
330
        /// Remote name (default: origin)
331
        remote: Option<String>,
332
        /// Machine-readable output: one JSON document on stdout
333
        #[arg(long)]
334
        json: bool,
335
    },
336
    /// Fetch, then union the remote bookmark into the local one (no merge change)
337
    Pull {
338
        /// Remote name (default: origin)
339
        remote: Option<String>,
340
        /// Machine-readable output: one JSON document on stdout
341
        #[arg(long)]
342
        json: bool,
343
    },
344
    /// Push the current bookmark to a remote
345
    Push {
346
        /// Remote name (default: origin)
347
        remote: Option<String>,
348
        /// Allow dropping heads the remote has
349
        #[arg(long)]
350
        force: bool,
351
        /// Push this bookmark instead of the workspace's current one
352
        #[arg(short = 'b', long)]
353
        bookmark: Option<String>,
354
        /// Machine-readable output: one JSON document on stdout
355
        #[arg(long)]
356
        json: bool,
357
    },
358
    /// Serve repositories under ROOT over HTTPS (with --tls-cert/--tls-key) or plain HTTP
359
    Serve {
360
        /// Directory with one repository per subdirectory
361
        #[arg(long, default_value = ".")]
362
        root: PathBuf,
363
        /// Address and port to listen on
364
        #[arg(long, default_value = "127.0.0.1:8890")]
365
        bind: String,
366
        /// Bearer token allowed to push (repeatable); none means open
367
        #[arg(long = "token")]
368
        tokens: Vec<String>,
369
        /// PEM certificate chain; enables HTTPS together with --tls-key
370
        #[arg(long, requires = "tls_key")]
371
        tls_cert: Option<PathBuf>,
372
        /// PEM private key
373
        #[arg(long, requires = "tls_cert")]
374
        tls_key: Option<PathBuf>,
375
    },
376
    /// Manage the signing identity
377
    Identity {
378
        #[command(subcommand)]
379
        cmd: IdentityCmd,
380
    },
381
    /// Seal changes with your key: named ones, or every change on the current bookmark you can authenticate but have not
382
    Seal {
383
        /// Changes to seal (default: every change on the bookmark you can authenticate and have not sealed)
384
        changes: Vec<String>,
385
        /// Seal every change of a hub proposal and push the seal (your approval)
386
        #[arg(long, conflicts_with = "changes")]
387
        proposal: Option<String>,
388
        /// Machine-readable output: one JSON document on stdout
389
        #[arg(long)]
390
        json: bool,
391
    },
392
    /// Hub proposals: show one, or land it from this client
393
    Proposal {
394
        #[command(subcommand)]
395
        cmd: ProposalCmd,
396
    },
397
    /// Verify the signatures on a change (default: every change in the log)
398
    Verify {
399
        /// The change to verify (default: every change in the log)
400
        change: Option<String>,
401
        /// Machine-readable output: one JSON document on stdout
402
        #[arg(long)]
403
        json: bool,
404
    },
405
    /// Git interoperability
406
    Git {
407
        #[command(subcommand)]
408
        cmd: GitCmd,
409
    },
410
    /// Manage the trust policy (who may update which bookmarks)
411
    Policy {
412
        #[command(subcommand)]
413
        cmd: PolicyCmd,
414
    },
415
    /// 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)
416
    Config {
417
        /// The key, such as author.name or remote.origin.token
418
        key: String,
419
        /// The value to set
420
        value: String,
421
        /// Write to the user file (~/.config/oxy/config.toml) instead of this repository
422
        #[arg(long)]
423
        user: bool,
424
    },
425
}
426
427
#[derive(Subcommand)]
428
enum OpCmd {
429
    /// List operations, newest first
430
    Log {
431
        /// Machine-readable output: one JSON document on stdout
432
        #[arg(long)]
433
        json: bool,
434
    },
435
}
436
437
#[derive(Subcommand)]
438
enum WorkspaceCmd {
439
    /// Create a workspace at PATH checked out on CHANGE... (default: the bookmark heads)
440
    Add {
441
        /// Directory for the new workspace (must be empty or absent)
442
        path: PathBuf,
443
        /// Changes whose state to check out there
444
        changes: Vec<String>,
445
    },
446
    /// List workspaces and their working-copy changes
447
    List {
448
        /// Machine-readable output: one JSON document on stdout
449
        #[arg(long)]
450
        json: bool,
451
    },
452
    /// Stop tracking a workspace (by id prefix or path); its files stay
453
    Forget {
454
        /// Workspace id prefix or path
455
        workspace: String,
456
    },
457
}
458
459
#[derive(Subcommand)]
460
enum BisectCmd {
461
    /// Begin; remembers where the working copy was
462
    Start,
463
    /// Mark CHANGE... (or the state under test) as good
464
    Good {
465
        /// Changes known to be good (default: the state under test)
466
        changes: Vec<String>,
467
    },
468
    /// Mark CHANGE... (or the state under test) as bad
469
    Bad {
470
        /// Changes known to be bad (default: the state under test)
471
        changes: Vec<String>,
472
    },
473
    /// The state under test cannot be tested; try another
474
    Skip,
475
    /// Run a command for each step: exit 0 good, 125 skip, else bad
476
    Run {
477
        /// Command and arguments to run at each step
478
        #[arg(required = true, trailing_var_arg = true)]
479
        command: Vec<String>,
480
    },
481
    /// Where the search stands
482
    Status {
483
        /// Machine-readable output: one JSON document on stdout
484
        #[arg(long)]
485
        json: bool,
486
    },
487
    /// Restore the working copy and forget the search
488
    Reset,
489
}
490
491
#[derive(Subcommand)]
492
enum BookmarkCmd {
493
    /// Create a bookmark at CHANGE... (default: the working copy's base)
494
    Create {
495
        /// Name of the new bookmark
496
        name: String,
497
        /// Its heads (default: the working copy's base)
498
        changes: Vec<String>,
499
    },
500
    /// Point an existing bookmark at CHANGE...
501
    Set {
502
        /// The bookmark to move
503
        name: String,
504
        /// Its new heads
505
        changes: Vec<String>,
506
    },
507
    /// Remove a bookmark; its changes stay
508
    Delete {
509
        /// The bookmark to remove
510
        name: String,
511
    },
512
    /// List bookmarks with their heads and difference from origin
513
    List {
514
        /// Machine-readable output: one JSON document on stdout
515
        #[arg(long)]
516
        json: bool,
517
    },
518
    /// Make NAME this workspace's bookmark and check it out. Uncommitted work stops it; --carry takes the work along, --discard drops it
519
    Switch {
520
        /// The bookmark to work on
521
        name: String,
522
        /// Throw away uncommitted working-copy changes
523
        #[arg(long)]
524
        discard: bool,
525
        /// Take uncommitted changes along; refused when NAME has other
526
        /// versions of the files they touch
527
        #[arg(long, conflicts_with = "discard")]
528
        carry: bool,
529
    },
530
}
531
532
#[derive(Subcommand)]
533
enum SubmoduleCmd {
534
    /// Clone URL (Oxygen or Git) into PATH and register it in .oxymodules
535
    Add {
536
        /// URL or path of the Oxygen or Git repository
537
        url: String,
538
        /// Where to put it, relative to the repository root
539
        path: String,
540
        /// Bookmark (Oxygen) or branch (Git) to check out and track
541
        #[arg(long)]
542
        bookmark: Option<String>,
543
    },
544
    /// Bring nested repositories to their pins
545
    Update {
546
        /// Clone nested repositories that are absent
547
        #[arg(long)]
548
        init: bool,
549
        /// Subrepos to update (default: all)
550
        paths: Vec<String>,
551
    },
552
    /// List subrepos with their pins and on-disk state
553
    Status {
554
        /// Machine-readable output: one JSON document on stdout
555
        #[arg(long)]
556
        json: bool,
557
    },
558
    /// Unregister PATH; the directory stays, the node goes with the next commit
559
    Remove {
560
        /// The subrepo to unregister
561
        path: String,
562
    },
563
}
564
565
#[derive(Subcommand)]
566
enum TagCmd {
567
    /// Tag the state of CHANGE... (default: the bookmark heads)
568
    Create {
569
        /// Name of the tag; tags never move
570
        name: String,
571
        /// Changes whose state to tag (default: the bookmark heads)
572
        changes: Vec<String>,
573
        /// A message recorded with the tag
574
        #[arg(short, long, default_value = "")]
575
        message: String,
576
    },
577
    /// List tags and the states they name
578
    List {
579
        /// Machine-readable output: one JSON document on stdout
580
        #[arg(long)]
581
        json: bool,
582
    },
583
}
584
585
#[derive(Subcommand)]
586
enum RemoteCmd {
587
    /// Add a remote
588
    Add {
589
        /// Name to refer to the remote by, such as origin
590
        name: String,
591
        /// Local path or http(s) URL of the repository
592
        url: String,
593
    },
594
    /// Remove a remote
595
    Remove {
596
        /// The remote to remove
597
        name: String,
598
    },
599
    /// List remotes and their URLs
600
    List {
601
        /// Machine-readable output: one JSON document on stdout
602
        #[arg(long)]
603
        json: bool,
604
    },
605
}
606
607
#[derive(Subcommand)]
608
enum ProposalCmd {
609
    /// Show a proposal by its hub URL
610
    Show {
611
        /// The proposal's URL on the hub
612
        url: String,
613
        /// Machine-readable output: one JSON document on stdout
614
        #[arg(long)]
615
        json: bool,
616
    },
617
    /// Fetch the proposal's changes, set the target bookmark to the projected state, and push with your key
618
    Land {
619
        /// The proposal's URL on the hub
620
        url: String,
621
        /// Land even when the hub reports blockers
622
        #[arg(long)]
623
        force: bool,
624
    },
625
}
626
627
#[derive(Subcommand)]
628
enum IdentityCmd {
629
    /// Generate a composite Ed25519 + ML-DSA-65 key pair and make it your author identity
630
    Create {
631
        /// Your name (default: author.name)
632
        #[arg(long)]
633
        name: Option<String>,
634
        /// Your email (default: author.email)
635
        #[arg(long)]
636
        email: Option<String>,
637
        /// Record the author in this repository only, not in the user config
638
        #[arg(long)]
639
        local: bool,
640
        /// Expire the identity this many days from now
641
        #[arg(long)]
642
        expires: Option<u64>,
643
    },
644
    /// Show the configured identity
645
    Show,
646
    /// Write your identity object to a file, to hand to a policy holder
647
    Export {
648
        /// File to write (default: <key>.identity in the current directory)
649
        path: Option<PathBuf>,
650
    },
651
    /// Sign a host's challenge (hex, at least 16 bytes) to prove you hold your key; prints the signature as hex
652
    SignChallenge {
653
        /// The host's challenge, as hex
654
        challenge: String,
655
        /// Machine-readable output: one JSON document on stdout
656
        #[arg(long)]
657
        json: bool,
658
    },
659
    /// Move to a fresh key pair; the policy follows if it names your key
660
    Rotate,
661
    /// Re-issue your identity with a new expiry (in days from now; 0 = never)
662
    Renew {
663
        /// Days from now until it expires; 0 for never
664
        #[arg(long)]
665
        expires: u64,
666
    },
667
    /// Revoke a key: yours by default, or any key if you hold a policy root
668
    Revoke {
669
        /// KeyId prefix (default: your own key)
670
        key: Option<String>,
671
        /// Why, recorded in the revocation
672
        #[arg(long, default_value = "")]
673
        reason: String,
674
    },
675
    /// Keys allowed to sign or seal on your behalf
676
    Delegate {
677
        #[command(subcommand)]
678
        cmd: DelegateCmd,
679
    },
680
}
681
682
#[derive(Subcommand)]
683
enum DelegateCmd {
684
    /// Add a delegate from an exported identity file
685
    Add {
686
        /// The delegate's exported identity file
687
        identity_file: PathBuf,
688
    },
689
    /// Remove a delegate by KeyId prefix
690
    Remove {
691
        /// KeyId prefix of the delegate
692
        key: String,
693
    },
694
    /// List delegates
695
    List,
696
}
697
698
#[derive(Subcommand)]
699
enum GitCmd {
700
    /// Export the current bookmark to a Git repository (created bare if absent)
701
    Export {
702
        /// Git repository to write to (created bare if absent)
703
        git_dir: PathBuf,
704
        /// Git branch to write (default: the bookmark name)
705
        #[arg(long)]
706
        branch: Option<String>,
707
    },
708
    /// Fetch a branch from a Git remote (path or URL) into the current bookmark
709
    Fetch {
710
        /// Git remote: a path or URL
711
        url: String,
712
        /// Branch to fetch
713
        #[arg(long, default_value = "main")]
714
        branch: String,
715
    },
716
    /// Push the current bookmark to a branch of a Git remote (fetch first)
717
    Push {
718
        /// Git remote: a path or URL
719
        url: String,
720
        /// Branch to push to
721
        #[arg(long, default_value = "main")]
722
        branch: String,
723
    },
724
    /// Check this repository's import of a Git branch: every commit's tree must be reproduced exactly
725
    Verify {
726
        /// The Git repository the import came from
727
        git_dir: PathBuf,
728
        /// Branch that was imported
729
        #[arg(long, default_value = "main")]
730
        branch: String,
731
    },
732
    /// Import a Git branch into a new Oxygen repository at DEST
733
    Import {
734
        /// Git repository to read
735
        git_dir: PathBuf,
736
        /// Directory for the new Oxygen repository
737
        dest: PathBuf,
738
        /// Branch to import
739
        #[arg(long, default_value = "main")]
740
        branch: String,
741
    },
742
}
743
744
#[derive(Subcommand)]
745
enum PolicyCmd {
746
    /// Create the initial policy with your identity as the only root
747
    Init,
748
    /// Show the current policy
749
    Show {
750
        /// Machine-readable output: one JSON document on stdout
751
        #[arg(long)]
752
        json: bool,
753
    },
754
    /// Allow an identity (from `oxy identity export`) to update bookmarks
755
    Grant {
756
        /// The identity to grant, exported with `oxy identity export`
757
        identity_file: PathBuf,
758
        /// Reference pattern the grant applies to (default: every bookmark)
759
        #[arg(long)]
760
        pattern: Option<String>,
761
        /// Where to write the proposal when more root signatures are needed
762
        #[arg(long)]
763
        out: Option<PathBuf>,
764
    },
765
    /// Revoke a key (KeyId prefix of an identity in the policy)
766
    Revoke {
767
        /// KeyId prefix of the identity
768
        key: String,
769
        /// Where to write the proposal when more root signatures are needed
770
        #[arg(long)]
771
        out: Option<PathBuf>,
772
    },
773
    /// Manage root keys and the signature threshold for policy updates
774
    Root {
775
        #[command(subcommand)]
776
        cmd: RootCmd,
777
    },
778
    /// Add your root signature to a proposal file; applies it once the threshold is met
779
    Sign {
780
        /// The proposal file to sign
781
        proposal: PathBuf,
782
        /// Where to write the proposal if it still needs signatures (default: in place)
783
        #[arg(long)]
784
        out: Option<PathBuf>,
785
    },
786
}
787
788
#[derive(Subcommand)]
789
enum RootCmd {
790
    /// Make an exported identity a root key
791
    Add {
792
        /// The identity to make a root, exported with `oxy identity export`
793
        identity_file: PathBuf,
794
        /// Where to write the proposal when more root signatures are needed
795
        #[arg(long)]
796
        out: Option<PathBuf>,
797
    },
798
    /// Remove a root key by KeyId prefix
799
    Remove {
800
        /// KeyId prefix of the root key
801
        key: String,
802
        /// Where to write the proposal when more root signatures are needed
803
        #[arg(long)]
804
        out: Option<PathBuf>,
805
    },
806
    /// Require this many root signatures on policy updates
807
    Threshold {
808
        /// Number of root signatures
809
        n: u32,
810
        /// Where to write the proposal when more root signatures are needed
811
        #[arg(long)]
812
        out: Option<PathBuf>,
813
    },
814
}
815
816
/// Open the repository containing the current directory.
817
fn open() -> Result<Repo> {
818
    Repo::open(&std::env::current_dir()?).context("opening repository")
819
}
820
821
/// `oxy man`: every page into `dir`, or the top-level page on stdout.
822
fn man(dir: Option<PathBuf>) -> Result<i32> {
823
    use clap::CommandFactory;
824
    let cmd = Cli::command();
825
    match dir {
826
        Some(dir) => {
827
            std::fs::create_dir_all(&dir)?;
828
            clap_mangen::generate_to(cmd, &dir)?;
829
            let pages = std::fs::read_dir(&dir)?
830
                .filter(|e| {
831
                    e.as_ref()
832
                        .is_ok_and(|e| e.path().extension().is_some_and(|x| x == "1"))
833
                })
834
                .count();
835
            println!(
836
                "{}",
837
                ui::done(format!("Wrote {pages} man pages to {}", dir.display()))
838
            );
839
        }
840
        None => clap_mangen::Man::new(cmd).render(&mut std::io::stdout())?,
841
    }
842
    Ok(0)
843
}
844
845
/// Parse arguments and run; returns the process exit code.
846
pub fn run() -> Result<i32> {
847
    let cli = Cli::parse();
848
    ui::init(cli.plain);
849
    match cli.cmd {
850
        Cmd::Completions { shell } => {
851
            use clap::CommandFactory;
852
            clap_complete::generate(shell, &mut Cli::command(), "oxy", &mut std::io::stdout());
853
            Ok(0)
854
        }
855
        Cmd::Man { dir } => man(dir),
856
        Cmd::Init { path, bare } => workspace::init(path, bare),
857
        Cmd::Status { json } => workspace::status(json),
858
        Cmd::Prompt {
859
            format,
860
            glyphs,
861
            color,
862
        } => workspace::prompt(&format, glyphs, color.as_deref()),
863
        Cmd::Commit {
864
            message,
865
            depends_on,
866
            paths,
867
            interactive,
868
            hunks,
869
        } => workspace::commit(&message, &depends_on, &paths, interactive, &hunks),
870
        Cmd::Cat { path, change } => workspace::cat(&path, change.as_deref()),
871
        Cmd::Root { json } => workspace::root(json),
872
        Cmd::Version { json } => workspace::version(json),
873
        Cmd::Discard { paths, hunks } => workspace::discard(&paths, &hunks),
874
        Cmd::Hunks { json } => workspace::hunks(json),
875
        Cmd::Squash { change, into } => workspace::squash(&change, &into),
876
        Cmd::Rebase { change, onto } => workspace::rebase(&change, &onto),
877
        Cmd::Blame { path, json } => workspace::blame(&path, json),
878
        Cmd::Bisect { cmd } => match cmd {
879
            BisectCmd::Start => workspace::bisect_start(),
880
            BisectCmd::Good { changes } => workspace::bisect_mark(Some(true), &changes),
881
            BisectCmd::Bad { changes } => workspace::bisect_mark(Some(false), &changes),
882
            BisectCmd::Skip => workspace::bisect_mark(None, &[]),
883
            BisectCmd::Run { command } => workspace::bisect_run(&command),
884
            BisectCmd::Status { json } => workspace::bisect_status(json),
885
            BisectCmd::Reset => workspace::bisect_reset(),
886
        },
887
        Cmd::Log {
888
            limit,
889
            verbose,
890
            path,
891
            json,
892
        } => workspace::log(limit, verbose, path.as_deref(), json),
893
        Cmd::Diff { change, json } => workspace::diff(change.as_deref(), json),
894
        Cmd::Describe { message, change } => workspace::describe(&message, change.as_deref()),
895
        Cmd::Amend { message, into } => workspace::amend(message.as_deref(), into.as_deref()),
896
        Cmd::Split { change, paths } => workspace::split(&change, &paths),
897
        Cmd::Abandon { change } => workspace::abandon(&change),
898
        Cmd::Show { change, json } => workspace::show(&change, json),
899
        Cmd::Checkout {
900
            changes,
901
            discard,
902
            carry,
903
        } => workspace::checkout(&changes, discard, carry),
904
        Cmd::Resolve { json } => workspace::resolve(json),
905
        Cmd::Undo => workspace::undo(),
906
        Cmd::Gc { now } => workspace::gc(now),
907
        Cmd::Fsck { json } => workspace::fsck(json),
908
        Cmd::Doctor { offline, json } => workspace::doctor(offline, json),
909
        Cmd::Checkpoint => workspace::checkpoint(),
910
        Cmd::Op {
911
            cmd: OpCmd::Log { json },
912
        } => workspace::op_log(json),
913
        Cmd::Clone {
914
            url,
915
            dest,
916
            max_blob,
917
            sparse,
918
            depth,
919
        } => sync::clone(&url, dest, max_blob.as_deref(), &sparse, depth),
920
        Cmd::Deepen { depth, remote } => sync::deepen(&remote, depth),
921
        Cmd::Sparse { paths } => workspace::sparse(&paths),
922
        Cmd::Lock { path } => workspace::lock(&path),
923
        Cmd::Unlock { path } => workspace::unlock(&path),
924
        Cmd::Workspace { cmd } => match cmd {
925
            WorkspaceCmd::Add { path, changes } => workspace::workspace_add(&path, &changes),
926
            WorkspaceCmd::List { json } => workspace::workspace_list(json),
927
            WorkspaceCmd::Forget { workspace } => workspace::workspace_forget(&workspace),
928
        },
929
        Cmd::Bookmark { cmd } => match cmd {
930
            BookmarkCmd::Create { name, changes } => workspace::bookmark_create(&name, &changes),
931
            BookmarkCmd::Set { name, changes } => workspace::bookmark_set(&name, &changes),
932
            BookmarkCmd::Delete { name } => workspace::bookmark_delete(&name),
933
            BookmarkCmd::List { json } => workspace::bookmark_list(json),
934
            BookmarkCmd::Switch {
935
                name,
936
                discard,
937
                carry,
938
            } => workspace::bookmark_switch(&name, discard, carry),
939
        },
940
        Cmd::Merge { bookmark } => workspace::merge(&bookmark),
941
        Cmd::Submodule { cmd } => match cmd {
942
            SubmoduleCmd::Add {
943
                url,
944
                path,
945
                bookmark,
946
            } => sync::submodule_add(&url, &path, bookmark.as_deref()),
947
            SubmoduleCmd::Update { init, paths } => sync::submodule_update(init, &paths),
948
            SubmoduleCmd::Status { json } => sync::submodule_status(json),
949
            SubmoduleCmd::Remove { path } => sync::submodule_remove(&path),
950
        },
951
        Cmd::Tag { cmd } => match cmd {
952
            TagCmd::Create {
953
                name,
954
                changes,
955
                message,
956
            } => workspace::tag_create(&name, &changes, &message),
957
            TagCmd::List { json } => workspace::tag_list(json),
958
        },
959
        Cmd::Remote { cmd } => match cmd {
960
            RemoteCmd::Add { name, url } => sync::remote_add(&name, &url),
961
            RemoteCmd::Remove { name } => sync::remote_remove(&name),
962
            RemoteCmd::List { json } => sync::remote_list(json),
963
        },
964
        Cmd::Fetch { remote, json } => sync::fetch(remote.as_deref(), json),
965
        Cmd::Pull { remote, json } => sync::pull(remote.as_deref(), json),
966
        Cmd::Push {
967
            remote,
968
            force,
969
            bookmark,
970
            json,
971
        } => sync::push(remote.as_deref(), force, bookmark.as_deref(), json),
972
        Cmd::Serve {
973
            root,
974
            bind,
975
            tokens,
976
            tls_cert,
977
            tls_key,
978
        } => sync::serve(root, &bind, tokens, tls_cert.zip(tls_key)),
979
        Cmd::Identity { cmd } => match cmd {
980
            IdentityCmd::Create {
981
                name,
982
                email,
983
                local,
984
                expires,
985
            } => identity::create(name, email, local, expires),
986
            IdentityCmd::Show => identity::show(),
987
            IdentityCmd::Export { path } => identity::export(path),
988
            IdentityCmd::SignChallenge { challenge, json } => {
989
                identity::sign_challenge(&challenge, json)
990
            }
991
            IdentityCmd::Rotate => identity::rotate(),
992
            IdentityCmd::Renew { expires } => identity::renew(expires),
993
            IdentityCmd::Revoke { key, reason } => identity::revoke(key.as_deref(), &reason),
994
            IdentityCmd::Delegate { cmd } => match cmd {
995
                DelegateCmd::Add { identity_file } => identity::delegate_add(&identity_file),
996
                DelegateCmd::Remove { key } => identity::delegate_remove(&key),
997
                DelegateCmd::List => identity::delegate_list(),
998
            },
999
        },
1000
        Cmd::Git {
1001
            cmd: GitCmd::Export { git_dir, branch },
1002
        } => sync::git_export(&git_dir, branch.as_deref()),
1003
        Cmd::Git {
1004
            cmd: GitCmd::Fetch { url, branch },
1005
        } => sync::git_fetch(&url, &branch),
1006
        Cmd::Git {
1007
            cmd: GitCmd::Push { url, branch },
1008
        } => sync::git_push(&url, &branch),
1009
        Cmd::Git {
1010
            cmd:
1011
                GitCmd::Import {
1012
                    git_dir,
1013
                    dest,
1014
                    branch,
1015
                },
1016
        } => sync::git_import(&git_dir, &dest, &branch),
1017
        Cmd::Git {
1018
            cmd: GitCmd::Verify { git_dir, branch },
1019
        } => sync::git_verify(&git_dir, &branch),
1020
        Cmd::Policy { cmd } => match cmd {
1021
            PolicyCmd::Init => identity::policy_init(),
1022
            PolicyCmd::Show { json } => identity::policy_show(json),
1023
            PolicyCmd::Grant {
1024
                identity_file,
1025
                pattern,
1026
                out,
1027
            } => identity::policy_grant(&identity_file, pattern.as_deref(), out),
1028
            PolicyCmd::Revoke { key, out } => identity::policy_revoke(&key, out),
1029
            PolicyCmd::Root { cmd } => match cmd {
1030
                RootCmd::Add { identity_file, out } => {
1031
                    identity::policy_root_add(&identity_file, out)
1032
                }
1033
                RootCmd::Remove { key, out } => identity::policy_root_remove(&key, out),
1034
                RootCmd::Threshold { n, out } => identity::policy_threshold(n, out),
1035
            },
1036
            PolicyCmd::Sign { proposal, out } => identity::policy_sign(&proposal, out),
1037
        },
1038
        Cmd::Seal {
1039
            changes,
1040
            proposal: Some(url),
1041
            json,
1042
        } if changes.is_empty() => proposal::seal(&url, json),
1043
        Cmd::Seal { changes, json, .. } => identity::seal(&changes, json),
1044
        Cmd::Proposal { cmd } => match cmd {
1045
            ProposalCmd::Show { url, json } => proposal::show(&url, json),
1046
            ProposalCmd::Land { url, force } => proposal::land(&url, force),
1047
        },
1048
        Cmd::Verify { change, json } => identity::verify(change.as_deref(), json),
1049
        Cmd::Config { key, value, user } => identity::config(&key, &value, user),
1050
    }
1051
}
1052
1053
#[cfg(test)]
1054
mod help_tests {
1055
    use super::Cli;
1056
    use clap::CommandFactory;
1057
1058
    /// Every command and every argument explains itself, so `--help`,
1059
    /// completions and the man pages are complete.
1060
    #[test]
1061
    fn every_command_and_argument_has_help() {
1062
        fn walk(cmd: &clap::Command, path: &str, missing: &mut Vec<String>) {
1063
            let here = format!("{path} {}", cmd.get_name()).trim().to_string();
1064
            if cmd.get_about().is_none() && path != "" {
1065
                missing.push(format!("{here} (command)"));
1066
            }
1067
            for a in cmd.get_arguments() {
1068
                let id = a.get_id().as_str();
1069
                if id == "help" || id == "version" || a.is_global_set() && path != "" {
1070
                    continue;
1071
                }
1072
                if a.get_help().is_none() && a.get_long_help().is_none() {
1073
                    missing.push(format!("{here} {id}"));
1074
                }
1075
            }
1076
            for sub in cmd.get_subcommands() {
1077
                walk(sub, &here, missing);
1078
            }
1079
        }
1080
        let mut missing = Vec::new();
1081
        walk(&Cli::command(), "", &mut missing);
1082
        assert!(
1083
            missing.is_empty(),
1084
            "{} without help:\n{}",
1085
            missing.len(),
1086
            missing.join("\n")
1087
        );
1088
    }
1089
}