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