Repository navigation
Expand file tree
/
Copy pathcli.rs
More file actions
2445 lines (2295 loc) · 97 KB
/
Copy pathcli.rs
File metadata and controls
2445 lines (2295 loc) · 97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! `clap` argument definitions for the `min` CLI.
use clap::{ArgGroup, Args, Subcommand, ValueEnum};
// Re-exported so the crate-root glob (`pub use cli::*`) keeps `Parser` in scope
// for tests that call `Cli::try_parse_from`, exactly as the old single-module
// layout did.
pub(crate) use clap::Parser;
use clap_complete::Shell;
use std::path::PathBuf;
use crate::completion;
use crate::completions;
use crate::diag;
#[derive(Parser)]
#[command(name = "min", version = version::VERSION, long_version = version::LONG_VERSION)]
#[command(
about = "min, the Minimal session CLI — create, attach to, and manage sandboxed development sessions"
)]
#[command(subcommand_required = false)]
pub struct Cli {
// Optional: a bare `min` (no subcommand) routes into a session in a
// terminal, and prints a read-only state report otherwise — see
// `cmd_bare`. Keeps every named subcommand reachable unchanged when one
// is supplied.
#[command(subcommand)]
pub command: Option<Command>,
#[command(flatten)]
pub global_args: GlobalArgs,
}
/// Retired top-level verbs, each with the tip naming what replaced it.
const RETIRED_COMMANDS: &[(&str, &str)] = &[(
"ssh-forward",
"`min ssh-forward` was removed: forward a box port with \
`min net forward <SESSION> <LOCAL>:<PORT>`",
)];
/// Adds a tip naming the replacement when `err` refuses a retired verb. The
/// parser still refuses the verb, with its usage; the tip says where it went.
pub fn with_retired_command_hint(mut err: clap::Error) -> clap::Error {
use clap::error::{ContextKind, ContextValue, ErrorKind};
if err.kind() != ErrorKind::InvalidSubcommand {
return err;
}
let tip = match err.get(ContextKind::InvalidSubcommand) {
Some(ContextValue::String(verb)) => RETIRED_COMMANDS
.iter()
.find(|(retired, _)| *retired == verb.as_str())
.map(|(_, tip)| tip),
_ => None,
};
if let Some(tip) = tip {
err.insert(
ContextKind::Suggested,
ContextValue::StyledStrs(vec![(*tip).to_owned().into()]),
);
}
err
}
#[derive(Subcommand)]
pub enum Command {
/// List sessions
//
// Deliberate exception to the `<noun> <verb>` convention (documented in
// docs/reference/cli.md): `min ls` — the highest-traffic command in the
// CLI — keeps this bare top-level form, with its `--raw` and `--json`
// flags, for the scripts that read it. It is not an alias of
// `min session list`, which is `min box list` filtered to session boxes
// (BCLI-030) and takes the `min box list` flags. Not an oversight — do
// not remove it.
Ls(LsArgs),
/// Shut down the minimald daemon
//
// Stays top-level: it acts on the daemon backend, not on any session, and
// it is the daemon-lifecycle command people reach for. Documented as a
// deliberate exception in docs/reference/cli.md.
Stop(StopArgs),
/// Session management subcommands
#[command(visible_alias = "sessions")]
Session(SessionArgs),
/// Loadout management subcommands
#[command(visible_alias = "loadouts")]
Loadout(LoadoutArgs),
/// Task subcommands: run declared project tasks in ephemeral sessions
#[command(visible_alias = "tasks")]
Task(TaskArgs),
/// Network subcommands: bring a box's services to the laptop
Net(NetArgs),
/// Box subcommands: show what a box will get
#[command(visible_alias = "boxes")]
Box(BoxArgs),
/// Host subcommands: the daemons on this machine that run boxes
#[command(visible_alias = "hosts")]
Host(HostArgs),
/// Provider subcommands: the kinds of local host this machine runs
#[command(visible_alias = "providers")]
Provider(ProviderArgs),
/// Finish the install on this host: every privileged step it still needs, in one run (`--show` names them, `--show --script` prints the script, `--undo` removes them)
FinalizeInstall(FinalizeInstallArgs),
/// Print important directories and file paths for debugging
Dirs,
/// Check this host for problems: today, that no record of the audit log
/// was changed or removed
///
/// Exits 0 when the audit log verifies or audit files are missing, and 6
/// when a record was changed or removed.
// BEP-049: whole-log verification of the audit chain is a `min doctor`
// check, never a `min box audit` flag.
Doctor,
/// Collect a diagnostic bundle (logs, state, config) to send to the
/// minimal dev team.
///
/// Writes `minimal-diag-<timestamp>.tar.zst` to the current directory.
/// Secret-shaped values (env vars, tokens) are redacted and session/
/// project file contents are never included — only name/size listings.
/// Works even when no daemon is running; never starts one.
///
/// The same command as `min diag collect`, kept under its own name
/// because it is what everyone already types and what every bug report
/// asks for.
Bug(diag::BugArgs),
/// Collect diagnostic bundles and send them for diagnosis
Diag(diag::DiagArgs),
/// WireGuard mesh: join, leave, and inspect remote-access state
#[cfg(feature = "remote-access")]
Mesh(MeshArgs),
/// Proxy stdio to a daemon UDS socket (used as an SSH ProxyCommand).
#[command(hide = true)]
Proxy(ProxyArgs),
/// Sign in to GitHub, and show the sign-in that boxes use
Auth(AuthArgs),
/// Store, list and remove the secrets that boxes reference by name
#[command(visible_alias = "secrets")]
Secret(SecretArgs),
// NET-109: `min login` is the alias for `min auth login`, so it takes
// the same arguments and runs the same sign-in.
/// Sign in to GitHub (the same as min auth login)
///
/// Opens GitHub in your browser. With `--device`, or in a build with no
/// browser sign-in, prints a code to enter at github.com instead. The
/// token is kept in the host keychain and never written to a file.
Login(AuthLoginArgs),
// `init`, `add`, and `update` are deliberate exceptions to the
// `<noun> <verb>` convention (documented in docs/reference/cli.md): they
// are passthroughs to the project-configuration commands of the same name
// in `mip`, and keeping the spelling identical across the two CLIs is
// worth more than the hierarchy. Do not move them under a noun.
/// Automatically initialize minimal configuration based on your source tree
Init(InitArgs),
/// Add a new tool or dependency
Add(AddArgs),
/// Re-pin upstream & sideloads to their latest commits (not a self-update)
///
/// Re-pins the project's `[upstream]` link (and any sideloads) in
/// `minimal.toml` to the current head of each tracking branch, rewriting
/// `locked_commit`, then refreshes the local checkouts to match. The
/// standard library is embedded in the `min` binary and is only refreshed
/// or verified locally — its commit is not re-pinned. This leaves
/// `minimal.toml` modified in your working tree (a diff to commit),
/// and the next `min session activate` materializes the new closure, which
/// can take several minutes on the first activate.
///
/// This does not update the `min` binary itself; reinstall it with the
/// installer to do that.
Update(UpdateArgs),
/// Print CLI and daemon version information
Version,
/// Check now whether your channel has a newer release.
///
/// min makes this check by itself once a day; see
/// https://docs.minimal.dev/reference/telemetry#update-check for what
/// it sends and how to turn it off.
#[command(name = "update-check", hide = true)]
UpdateCheck(UpdateCheckArgs),
/// Demo the client's activity spinner (development aid).
///
/// Draws the same build-hold-fade spinner used by the file-upload
/// phases of `min session activate` so you can eyeball timing and layout
/// without triggering a real upload. Stops after `--seconds` or
/// on Ctrl-C, whichever comes first. Debug builds only.
#[cfg(debug_assertions)]
#[command(hide = true)]
Spin(SpinArgs),
/// Print the privileged command that installs this host's resolver,
/// local range and box-name service (development aid).
///
/// The command a session start's advisory prints, rendered without a
/// daemon, so the service install can be tested on a host that cannot
/// boot a VM. Debug builds only.
#[cfg(debug_assertions)]
#[command(name = "debug-answerer-command", hide = true)]
DebugAnswererCommand,
/// Print session-identifier completion candidates (used by the shell).
///
/// The completion path a shell actually takes runs in-process (see
/// `completion.rs`); this is the same candidate list on stdout, one
/// `value<TAB>description` per line. It exists to be debugged by hand and
/// scripted against, and to honour global args — `--provider`,
/// `--minimal-dir` — that the in-process completer cannot see.
///
/// Never starts a daemon and never fails: no daemon means no output.
#[command(name = completion::COMPLETE_SESSION_STR, hide = true)]
CompleteSessionStr(CompleteSessionStrArgs),
/// Open the interactive session manager TUI (`dash`)
///
/// Full-screen terminal UI for browsing, inspecting, and managing
/// sessions across every running provider on the host (native minimald
/// and the minvmd microVM). Requires a terminal.
Dash,
/// Print or install the shell tab-completion integration
#[command(
visible_alias = "completion",
long_about = "Print or install the shell tab-completion integration for the min CLI.\n\n source <(min completions print bash)\n min completions install"
)]
Completions(CompletionsArgs),
}
#[derive(Debug, Args)]
pub struct SessionArgs {
#[command(subcommand)]
pub command: SessionCommand,
}
#[derive(Debug, Subcommand)]
pub enum SessionCommand {
// BCLI-030: `min box list`, filtered to session boxes.
/// List the session boxes of the current project, in any state, as
/// `min box list` lists boxes. `--all` lists the session boxes of every
/// project
#[command(visible_alias = "ls")]
List(BoxListArgs),
/// Activate (create) a new session
Activate(ActivateArgs),
/// Create a box from a session entry of the project and attach this
/// terminal to it. `--detach` creates the box, prints its id and returns
Start(SessionStartArgs),
/// Attach this terminal to a session box's terminal. With no box named,
/// attach to this project's running session box that has a terminal,
/// else to its only stopped or exited one, which starts again
Attach(AttachArgs),
/// Execute a command in an existing session
Exec(ExecArgs),
/// Run a declared task in an existing session
///
/// The task runs in the named session's context, serviced by the daemon —
/// the counterpart to `min task run <task>`, which composes a task session
/// of its own instead of reusing one you already have.
Run(SessionRunArgs),
/// Destroy (terminate) a session
Destroy(DestroyArgs),
/// Rename an existing session
Rename(RenameArgs),
/// Print the effective networking policy for a session, as text or as
/// one JSON document (`-o json`)
Policy(PolicyArgs),
/// Register a session as an SSH remote in Zed's settings
///
/// Upserts an entry into the `ssh_connections` array of Zed's
/// `settings.json`, pointing it at this session over the same transport
/// `min session attach` uses: our own `proxy` subcommand as an SSH
/// `ProxyCommand`, with the session selected by `MINIMAL_SESSION_ID`.
/// Re-running refreshes the entry in place.
///
/// Rewriting the file re-renders it from parsed JSON, so comments and key
/// ordering are not preserved; the previous contents are kept alongside as
/// `settings.json.bak`. Use `--print` to emit just the entry instead.
///
/// Example:
///
/// min session setup-zed my-box
///
/// Hidden while the Zed integration settles: it still parses and runs, it
/// just stays out of `min session --help` and shell completions.
#[command(name = "setup-zed", verbatim_doc_comment)]
#[command(hide = true)]
SetupZed(SetupZedArgs),
/// List the lifecycle hooks composed into a session, and where each
/// was declared
Hooks(HooksArgs),
/// Show what a session's terminal printed, from its start. `-f` keeps
/// showing new output until the session is removed or the command is
/// interrupted
Logs(BoxLogsArgs),
// BCLI-030: `min box stop`, filtered to session boxes.
/// Stop a running session box and keep it, as `min box stop` does.
/// `--force` kills every process in the box at once, with no grace
/// period
Stop(BoxStopArgs),
// BCLI-030: `min box rm`, filtered to session boxes.
/// Remove a stopped or exited session box, as `min box rm` does. A
/// running box is refused unless `--force` is given
Rm(BoxRmArgs),
}
#[derive(Debug, Args)]
pub struct SetupZedArgs {
/// Session identifier (UUID, unique id prefix, or session name)
#[arg(add = completion::session_completer())]
pub session: String,
/// Zed settings file to edit (default: `~/.config/zed/settings.json`)
#[arg(long, value_name = "FILE")]
pub settings: Option<PathBuf>,
/// Print the connection entry as JSON instead of editing any file
#[arg(long)]
pub print: bool,
}
/// Args for `min session hooks`.
#[derive(Debug, Args)]
pub struct HooksArgs {
/// Session identifier (UUID, unique id prefix, or session name)
#[arg(add = completion::session_completer())]
pub session: String,
/// Emit the raw JSON the daemon returned instead of a table
#[arg(long)]
pub json: bool,
}
#[derive(Debug, Args)]
pub struct ExecArgs {
/// Session identifier (UUID, unique id prefix, or session name).
#[arg(add = completion::session_completer())]
pub session: String,
/// Command to execute in the session context
///
/// A single argument is a shell command, run by the session's shell with
/// its pipes, globs and `$VAR` intact: `min session exec s 'echo $PWD'`.
/// Several arguments are an argv, quoted so the session sees exactly the
/// words you typed: `min session exec s sh -c 'echo A B'`.
#[arg(trailing_var_arg = true, required = true, num_args = 1..)]
pub command: Vec<String>,
}
#[derive(Debug, Args)]
pub struct SessionRunArgs {
/// Session identifier (UUID, unique id prefix, or session name).
#[arg(add = completion::session_completer())]
pub session: String,
/// Name of a task declared in the session project's minimal.toml
pub task: String,
}
#[derive(Debug, Args)]
pub struct PolicyArgs {
/// Session identifier (UUID, unique id prefix, or session name)
#[arg(add = completion::session_completer())]
pub session: String,
/// Write one JSON document instead of text (the default)
#[arg(short = 'o', long = "output", value_enum)]
pub output: Option<PolicyOutputFormat>,
}
/// The rendering `min session policy` writes. One value today — `json`, the
/// machine-readable shape — beside the text default; an `output` enum rather
/// than a bare `--json` flag so a second format lands beside the first
/// instead of accreting flags.
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
pub enum PolicyOutputFormat {
/// One JSON document, `min/v1/session-policy`, with each live mapping's
/// `pending` state carried
Json,
}
/// The typed failure a machine-output run fails its walk into: the
/// `code`, `message` and `hint` of the one `min/v1/error` object the CLI's
/// `main` writes on stderr when the run ends non-zero. Keyed on the output
/// mode rather than on any one command — every command that takes `-o json`
/// fails into this, and `main`'s single machine-mode error emitter (keyed
/// the same way, in `main.rs`, shared by all of them) is the only thing
/// that turns one into bytes — so the next command that takes `-o json`
/// calls the mechanism directly: its walk names the failure kinds it can
/// tell apart and fails into this payload, with no sentinel of its own.
///
/// [`std::error::Error`] so the failure can ride the `anyhow` chain across
/// the library boundary to `main`, the way the task-status type does.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MachineModeFailure {
/// The failure's kind: a name a script branches on — the
/// architecture's codes, `not_found` for a missing thing (with the
/// kind of thing that was missing in the message and the hint),
/// `daemon_unreachable`, `policy_unavailable` — never a single
/// command's own spelling.
code: &'static str,
message: String,
hint: String,
}
impl MachineModeFailure {
/// One failure, from the three parts the error object carries.
#[must_use]
pub fn new(code: &'static str, message: String, hint: String) -> Self {
Self {
code,
message,
hint,
}
}
/// The failure's kind — the `code` of the error object.
#[must_use]
pub fn code(&self) -> &'static str {
self.code
}
/// The message beside it: the same chain the text mode's error line
/// carries.
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
/// The hint beside them: one line naming what to do about the failure,
/// or the kind of thing that was missing.
#[must_use]
pub fn hint(&self) -> &str {
&self.hint
}
/// The failure with an old-spelling hint added to its `hint` field, so
/// the error object carries it and no separate line prints (BCLI-042).
#[must_use]
pub fn with_alias_hint(mut self, alias_hint: &str) -> Self {
self.hint = if self.hint.is_empty() {
alias_hint.to_owned()
} else {
format!("{}. {alias_hint}", self.hint)
};
self
}
}
impl std::fmt::Display for MachineModeFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"the machine-mode error object on stderr says why: {} ({})",
self.message, self.code
)
}
}
impl std::error::Error for MachineModeFailure {}
/// The context a machine-output command
10BC8
puts on a failure to write its own
/// document to stdout, so the machine-mode error path can tell that failure
/// (`output_failed`) from any other I/O error the run met on the way.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OutputWriteError;
impl std::fmt::Display for OutputWriteError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("failed to write the document to stdout")
}
}
#[derive(Debug, Args)]
pub struct BoxArgs {
#[command(subcommand)]
pub command: BoxCommand,
}
#[derive(Debug, Subcommand)]
pub enum BoxCommand {
/// Show the spec of an entry of the project before a start, or the
/// spec a box was created with. An entry's spec names the minimal.toml
/// table or flag that set each value. With no entry or box named, show
/// how the project's box reaches GitHub through the local proxy: the
/// proxy's root certificate fingerprint, each secret with its hosts,
/// the steering mode and the UDP 443 stance
Spec(BoxSpecArgs),
/// Show what the local proxy recorded for one box: each request it
/// admitted or refused, each secret minted for the box, and the box's
/// revocation. A removed box's records stay readable by its id
Audit(BoxAuditArgs),
/// List the boxes of the current project, in any state: their id,
/// name, type, parent, project and state, with how a stopped or exited
/// box ended, and the provider and host each box runs on. `--all`
/// lists the boxes of every project
List(BoxListArgs),
/// Show one box: its id, name, type, parent, project, state, how it
/// ended, the identity it runs under, and its provider and host.
/// `--network` shows the box's network section in its place
Show(BoxShowArgs),
/// Stop a running box and keep it: its record, its events and its
/// files stay until `min box rm` removes them. `--force` kills every
/// process in the box at once, with no grace period
Stop(BoxStopArgs),
/// Remove a stopped or exited box: its record, its events and its
/// files. A running box is refused unless `--force` is given, which
/// stops the box at once and then removes it
Rm(BoxRmArgs),
/// Stop a box that runs until it is stopped, if it runs, and start it
/// again from the settings it was created with. The box keeps its id,
/// its name and its files. A box that runs to completion cannot
/// restart: run it again with `min box run`
Restart(BoxRestartArgs),
/// Attach this terminal to a box's terminal. With no box named, attach
/// to this project's running box that has a terminal, else to its only
/// stopped or exited one, which starts again
Attach(BoxAttachArgs),
/// Start a stopped or exited box that has a terminal again, from the
/// spec it was created with, and attach this terminal to it. A box that
/// is not stopped or exited is refused. Attach to a running box with
/// `min box attach`
Resume(BoxResumeArgs),
/// Create a box from an entry of the project. A box with a terminal
/// attaches this terminal to it, unless `--detach` is given. Any other
/// box starts with no input, and the command prints its id and returns
Start(BoxStartArgs),
/// Create a box from an entry of the project, run it without a terminal
/// and exit with its exit code. This command's stdin, stdout and stderr
/// are the box's. `--detach` starts the box, prints its id and returns
///
/// The box's network and egress come from `--network`, the egress flags
/// and the entry's `network` keys in minimal.toml, as for `min task
/// run`. This command's flags go before the entry's own arguments. A
/// network or egress flag after an entry argument is refused. An
/// argument that shares a flag's name goes after `--`.
Run(BoxRunArgs),
/// Run a command in a running box and exit with the command's exit
/// code. `-t` gives the command a terminal, and `--detach` starts it
/// and returns its exec id
Exec(BoxExecArgs),
/// Wait until a box ends and exit with its exit code. A box that ended
/// already returns at once. A box stopped by a signal exits with 128
/// plus the signal, and a box that ran past its own timeout with 124
Wait(BoxWaitArgs),
/// Show what happened to a box: each event the daemon recorded for
/// it, such as its creation, each start and stop, each exec and its
/// exit, oldest first. A stopped or exited box keeps its events until
/// `min box rm` removes it
Events(BoxEventsArgs),
/// Copy a file out of a box to this machine. A stopped or exited box
/// keeps its files, so a copy from it works too
Cp(BoxCpArgs),
/// Give a box a new name. The box keeps its id, its state and its
/// files. A name that a running box on the same host holds is refused
Rename(BoxRenameArgs),
/// Remove every stopped or exited box: its record, its events and its
/// files. A running box is never removed. `--older-than` and `--parent`
/// narrow what is removed. Off a terminal, `--yes` is required
Prune(BoxPruneArgs),
/// Show what a box printed, from its start. A stopped or exited box
/// keeps its output until `min box rm` removes it. `-f` keeps showing
/// new output until the box is removed or the command is interrupted.
/// `--exec` shows what one command that `min box exec` started printed
Logs(BoxLogsExecArgs),
}
// BOX-155 (BCLI-012): `min session logs`, `min task logs` and
// `min box logs`, each `<box> [-f]`, with one set of arguments.
#[derive(Debug, Args)]
pub struct BoxLogsArgs {
/// The box: its id, the start of its id, or its name, as `min box list`
/// prints them
pub target: String,
/// Show the output so far, then keep showing new output as the box
/// writes it, until the box is removed or the command is interrupted
#[arg(short = 'f', long)]
pub follow: bool,
}
// BCLI-012, BCLI-056: `min box logs <box> [-f | --exec <id>]`. Only the box
// noun takes `--exec`, so `min session logs` and `min task logs` keep
// `BoxLogsArgs` alone.
#[derive(Debug, Args)]
pub struct BoxLogsExecArgs {
#[command(flatten)]
pub logs: BoxLogsArgs,
/// Show what one command printed, by the exec id that `min box exec`
/// printed for it. The command can be running or ended
#[arg(long = "exec", value_name = "EXEC_ID", conflicts_with = "follow")]
pub exec: Option<String>,
}
// BOX-162 (BCLI-016): `min box events <box> | --parent <box> [-o jsonl] [--follow]`.
#[derive(Debug, Args)]
#[command(group(clap::ArgGroup::new("box_or_parent").required(true).args(["target", "parent"])))]
pub struct BoxEventsArgs {
/// The box: its id, the start of its id, or its name, as `min box list`
/// prints them
pub target: Option<String>,
/// Show the events of every child box of this box together, in time
/// order, each event naming its box
#[arg(long, value_name = "BOX")]
pub parent: Option<String>,
/// Write each event as one JSON object on its own line
#[arg(short = 'o', long = "output", value_enum)]
pub output: Option<BoxEventsOutputFormat>,
/// Show the events so far, then keep showing new events as they
/// happen, until the box is removed or the command is interrupted
#[arg(short = 'f', long)]
pub follow: bool,
}
/// The rendering `min box events` writes, beside the text default.
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
pub enum BoxEventsOutputFormat {
/// One JSON object for each event
Jsonl,
}
// BOX-017 (BCLI-062): `min box cp <box>:<path> <local>`.
#[derive(Debug, Args)]
pub struct BoxCpArgs {
/// The file to copy, as `<box>:<path>`. `<box>` is the box's id, the
/// start of its id, or its name. A relative `<path>` is in the box's
/// home directory, and `/workbench/<path>` is in its copy of the project
#[arg(value_name = "BOX:PATH")]
pub source: String,
/// Where to write the file on this machine. An existing directory
/// receives the file under its own name
#[arg(value_name = "LOCAL")]
pub destination: PathBuf,
}
#[derive(Debug, Args)]
pub struct HostArgs {
#[command(subcommand)]
pub command: HostCommand,
}
#[derive(Debug, Subcommand)]
pub enum HostCommand {
/// List the local hosts: each daemon on this machine that runs boxes,
/// with its provider and whether it is running
#[command(visible_alias = "ls")]
List,
/// Show one local host: its provider, whether it is running, the socket
/// `min` connects to and the daemon version
Show(HostShowArgs),
/// Stop each running box on a local host, then its daemon, and its VM
/// on a VM host
Stop(HostStopArgs),
}
// BCLI-048: `min host show <host>`.
#[derive(Debug, Args)]
pub struct HostShowArgs {
/// The host, as `min host list` prints it (`local0`, `local-minvmd0`)
pub host: String,
}
// BCLI-049: `min host stop <host> [--force]`.
#[derive(Debug, Args)]
pub struct HostStopArgs {
/// The host, as `min host list` prints it (`local0`, `local-minvmd0`)
pub host: String,
/// Force-stop each box, and stop the daemon without waiting for it to
/// shut down cleanly. On a VM host, the VM is stopped from this machine
#[arg(long, short, default_value_t = false)]
pub force: bool,
}
#[derive(Debug, Args)]
pub struct ProviderArgs {
#[command(subcommand)]
pub command: ProviderCommand,
}
#[derive(Debug, Subcommand)]
pub enum ProviderCommand {
/// List the provider this command selects, with its hosts. `--all`
/// lists every local provider on this machine
#[command(visible_alias = "ls")]
List(ProviderListArgs),
}
// BCLI-052: `min provider list [--all]`.
#[derive(Debug, Args)]
pub struct ProviderListArgs {
/// List every local provider on this machine, not only the one this
/// command selects
#[arg(long)]
pub all: bool,
}
// BOX-158 (BCLI-001, BCLI-051): `min box list [--all] [-o json]`.
#[derive(Debug, Args)]
pub struct BoxListArgs {
/// List the boxes of every project, not only the boxes of the current
/// project
#[arg(long)]
pub all: bool,
/// Write the boxes as a JSON array, one object for each box, and
/// nothing else
#[arg(short = 'o', long = "output", value_enum)]
pub output: Option<BoxListOutputFormat>,
}
/// The rendering `min box list` writes, beside the table default.
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
pub enum BoxListOutputFormat {
/// One JSON array of box objects
Json,
}
// BOX-159 (BCLI-003): `min box show <box>`, and BCLI-025's `--network`.
#[derive(Debug, Args)]
pub struct BoxShowArgs {
/// The box: its id, the start of its id, or its name, as `min box list`
/// prints them
pub target: String,
/// Show only the box's `[network]` section, as the box was created
/// with it: its network mode, ingress and egress, with the flags of
/// the command that created it applied
#[arg(long)]
pub network: bool,
}
// BOX-013 (BCLI-059), BOX-151 (BCLI-055):
// `min box stop <box> [--force | --exec <id>]`.
#[derive(Debug, Args)]
pub struct BoxStopArgs {
/// The box: its id, the start of its id, or its name, as `min box list`
/// prints them
pub target: String,
/// Kill every process in the box at once, with no grace period
#[arg(long)]
pub force: bool,
/// Stop only one command, by the exec id that `min box exec` printed
/// for it. The box and its other commands keep running
#[arg(long = "exec", value_name = "EXEC_ID", conflicts_with = "force")]
pub exec: Option<String>,
}
// BOX-176 (BCLI-074): `min box restart <box>`.
#[derive(Debug, Args)]
pub struct BoxRestartArgs {
/// The box: its id, the start of its id, or its name, as `min box list`
/// prints them
pub target: String,
}
// BCLI-068: `min box attach [<box>] [--exec <id>]`.
#[derive(Debug, Args)]
pub struct BoxAttachArgs {
/// The box: its id, the start of its id, its name, or
/// provider/host/name, as `min box list` prints them. Omit it to attach
/// to this project's box
pub target: Option<String>,
/// Attach to a command that `min box exec -t` started in the box, by the
/// exec id it printed. Needs a box
#[arg(long = "exec", value_name = "EXEC_ID", requires = "target")]
pub exec: Option<String>,
}
// BCLI-007, BCLI-009: `min box resume <box>`.
#[derive(Debug, Args)]
pub struct BoxResumeArgs {
/// The box: its id, the start of its id, its name, or
/// provider/host/name, as `min box list` prints them
pub target: String,
}
// BOX-019 (BCLI-060, BCLI-004): `min box rm <box> [--force]`.
#[derive(Debug, Args)]
pub struct BoxRmArgs {
/// The box: its id, the start of its id, or its name, as `min box list`
/// prints them
pub target: String,
/// Remove a running box too: stop it at once, then remove it
#[arg(long)]
pub force: bool,
}
// BCLI-013, BCLI-014, BCLI-057:
// `min box wait <box> [--timeout <d>] [--exec <id>]`.
#[derive(Debug, Args)]
pub struct BoxWaitArgs {
/// The box: its id, the start of its id, or its name, as `min box list`
/// prints them
pub target: String,
/// Stop waiting after this long: a number of seconds, or a number
/// followed by s, m or h, such as 30s, 5m or 1h. The box keeps running,
/// and the command exits with code 124
#[arg(long, value_name = "DURATION", value_parser = mfile::duration::parse_timeout_secs)]
pub timeout: Option<u64>,
/// Wait for one command, by the exec id that `min box exec` printed for
/// it, and exit with that command's exit code. The command can be
/// running or ended
#[arg(long = "exec", value_name = "EXEC_ID")]
pub exec: Option<String>,
}
// BOX-149 (BCLI-053): `min box exec <box> [-t|--detach] [--timeout <d>] -- <cmd>`.
#[derive(Debug, Args)]
pub struct BoxExecArgs {
/// The box: its id, the start of its id, or its name, as `min box list`
/// prints them
pub target: String,
/// Give the command a terminal and connect this terminal to it. The
/// command's exec id is printed on stderr
#[arg(short = 't', long = "tty", conflicts_with = "detach")]
pub tty: bool,
/// Start the command and return at once. Only the command's exec id is
/// printed, on stdout
#[arg(long)]
pub detach: bool,
/// Stop the command when it runs for longer than this: a number of
/// seconds, or a number followed by s, m or h, such as 30s, 5m or 1h.
/// The command then ends with exit code 124
#[arg(long, value_name = "DURATION", value_parser = mfile::duration::parse_timeout_secs)]
pub timeout: Option<u64>,
/// The command and its arguments, after `--`. The command runs as these
/// words, with no shell
#[arg(last = true, required = true, num_args = 1.., value_name = "COMMAND")]
pub command: Vec<String>,
}
/// Why `min box exec` ran no command in the box: `-t` without a terminal
/// (exit 2), the box is not running (BOX-149, exit 2), or its spec turns
/// exec off (BOX-153, exit 5). `target` is the box as the user named it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BoxExecRefusal {
/// `-t` ran with a stdin that is not a terminal, so nothing started.
/// Exit 2.
NoTerminal {
/// The box as the user named it.
target: String,
},
/// The box is not running. Exit 2.
NotRunning {
/// The box as the user named it.
target: String,
/// The box's state as its host names it, such as `stopped`.
state: String,
},
/// The box's spec sets `[io] exec_enabled = false`. Exit 5.
ExecDisabled {
/// The box as the user named it.
target: String,
},
/// The box's spec cannot be read, so exec stays off. Exit 5.
SpecUnreadable {
/// The box as the user named it.
target: String,
},
}
impl BoxExecRefusal {
/// The exit code `min box exec` ends with on this refusal, from the
/// architecture's exit-code table: 2 for the state, 5 for the spec.
#[must_use]
pub fn exit_code(&self) -> u8 {
match self {
Self::NoTerminal { .. } | Self::NotRunning { .. } => 2,
Self::ExecDisabled { .. } | Self::SpecUnreadable { .. } => 5,
}
}
/// The outcome the command's tracing event records.
#[must_use]
pub fn outcome(&self) -> &'static str {
match self {
Self::NoTerminal { .. } => "no terminal",
Self::NotRunning { .. } => "not running",
Self::ExecDisabled { .. } => "exec disabled",
Self::SpecUnreadable { .. } => "spec unreadable",
}
}
}
impl std::fmt::Display for BoxExecRefusal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NoTerminal { target } => write!(
f,
"Did not run the command in {target}: -t needs a terminal. \
Stdin is not a terminal. Run `min box exec {target} -- <command>` \
without -t, or run it from a terminal."
),
// BOX-149, BCLI-053: the refusal names the box's state.
Self::NotRunning { target, state } => write!(
f,
"{target} is {state}. Only a running box can run a command."
),
Self::ExecDisabled { target } => write!(
f,
"{target} does not allow exec (its spec sets [io] exec_enabled = false)."
),
Self::SpecUnreadable { target } => write!(
f,
"{target} does not allow exec: its spec cannot be read, so exec stays off."
),
}
}
}
impl std::error::Error for BoxExecRefusal {}
/// A refusal of `min box stop`, `min box logs` or `min box wait` with
/// `--exec <id>` (BCLI-055, BCLI-056, BCLI-057): the text is not an exec
/// id, or the box's host knows no exec of that id.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BoxExecIdRefusal {
/// The text is not an exec id. Exit 2.
NotAnId {
/// The box as the user named it.
target: String,
/// The exec id as the user typed it.
exec_id: String,
},
/// The box has no exec of this id, running or ended. Exit 4.
Unknown {
/// The box as the user named it.
target: String,
/// The exec id.
exec_id: String,
},
/// The box's host has no running exec of this id, and the box's events
/// record no end for one, so no exit code is known. Exit 4.
NoExitCode {
/// The box as the user named it.
target: String,
/// The exec id.
exec_id: String,
},
}
impl BoxExecIdRefusal {
/// The exit code the command ends with: 2 for text that is not an exec
/// id, 4 for an exec that is not found.
#[must_use]
pub fn exit_code(&self) -> u8 {
match self {
Self::NotAnId { .. } => 2,
Self::Unknown { .. } | Self::NoExitCode { .. } => 4,
}
}
/// The outcome the command's tracing event records.
#[must_use]
pub fn outcome(&self) -> &'static str {
match self {
Self::NotAnId { .. } => "not an exec id",
Self::Unknown { .. } => "no such exec",
Self::NoExitCode { .. } => "no exit code",
}
}
}
impl std::fmt::Display for BoxExecIdRefusal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let hint = |target: &str| {
format!("Run `min box show {target}` to see the commands that run in the box now.")
};
match self {
Self::NotAnId { target, exec_id } => {
write!(f, "`{exec_id}` is not an exec id. {}", hint(target))
}
Self::Unknown { target, exec_id } => {
write!(f, "{target} has no exec {exec_id}. {}", hint(target))
}
Self::NoExitCode { target, exec_id } => write!(
f,
"No exit code is known for exec {exec_id} in {target}. {}",
hint(target)
),
}
}
}
impl std::error::Error for BoxExecIdRefusal {}
/// A command in a box that ran past its own timeout and was stopped
/// (BOX-149, BCLI-053). `min box exec` and the wait for an exec end with
/// exit 124 on it, and a machine-mode run answers it with `code =
/// "timeout"`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BoxExecTimedOut {
message: String,
hint: String,
}
impl BoxExecTimedOut {
/// The exit code, as `timeout(1)` gives it.
pub const EXIT_CODE: u8 = 124;
/// The `code` of the machine-mode error object.
pub const CODE: &'static str = "timeout";
/// The command `min box exec` ran in `target` with `--timeout`, after
/// `secs` seconds.
#[must_use]
pub fn exec(target: &str, secs: u64) -> Self {
Self {
message: format!(
"The command in {target} ran for longer than its timeout of {secs}s and was stopped."
),
hint: "Run the command again with a longer --timeout.".to_string(),
}
}
/// The exec `exec_id` in `target`, as a wait for it found it.
#[must_use]
pub fn waited(target: &str, exec_id: &str) -> Self {