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