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