-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.rs
More file actions
1829 lines (1695 loc) · 71.5 KB
/
Copy pathcli.rs
File metadata and controls
1829 lines (1695 loc) · 71.5 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
use crate::commands::shared::TerminalDimensions;
use crate::ui::spinner::{PlainSpinner, SpinnerEmitter};
use anyhow::Result;
use clap::{Parser, Subcommand, ValueEnum};
use deacon_core::container_env_probe::ContainerProbeMode;
/// CLI-facing probe enum (value_enum for clap) to map into core probe mode
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum DefaultUserEnvProbe {
None,
LoginInteractiveShell,
InteractiveShell,
LoginShell,
}
impl From<DefaultUserEnvProbe> for ContainerProbeMode {
fn from(p: DefaultUserEnvProbe) -> Self {
match p {
DefaultUserEnvProbe::None => ContainerProbeMode::None,
DefaultUserEnvProbe::LoginInteractiveShell => ContainerProbeMode::LoginInteractiveShell,
DefaultUserEnvProbe::InteractiveShell => ContainerProbeMode::LoginShell,
DefaultUserEnvProbe::LoginShell => ContainerProbeMode::LoginShell,
}
}
}
use std::io::IsTerminal;
use std::path::PathBuf;
/// Runtime selection options
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq)]
pub enum RuntimeOption {
/// Docker runtime
Docker,
/// Podman runtime (experimental in 1.0)
Podman,
}
impl From<RuntimeOption> for deacon_core::runtime::RuntimeKind {
fn from(runtime: RuntimeOption) -> Self {
match runtime {
RuntimeOption::Docker => deacon_core::runtime::RuntimeKind::Docker,
RuntimeOption::Podman => deacon_core::runtime::RuntimeKind::Podman,
}
}
}
/// Output format options
#[derive(Debug, Clone, ValueEnum)]
pub enum OutputFormat {
/// Human-readable text format
Text,
/// JSON structured format
Json,
}
/// Log format options
#[derive(Debug, Clone, ValueEnum)]
pub enum LogFormat {
/// Human-readable text format
Text,
/// JSON structured format
Json,
}
/// Log level options
#[derive(Debug, Clone, ValueEnum)]
pub enum LogLevel {
/// Error messages only
Error,
/// Warning and error messages
Warn,
/// Informational messages and above
Info,
/// Debug messages and above
Debug,
/// All messages including trace
Trace,
}
/// Progress format options
#[derive(Debug, Clone, ValueEnum, PartialEq, Eq)]
pub enum ProgressFormat {
/// No progress output
None,
/// JSON structured progress events
Json,
/// Auto mode: silent unless --progress-file is set (future: TTY spinner)
Auto,
}
/// BuildKit usage control options
#[derive(Debug, Clone, ValueEnum, PartialEq)]
pub enum BuildKitOption {
/// Automatically detect and use BuildKit if available (respects DOCKER_BUILDKIT)
Auto,
/// Never use BuildKit, force legacy docker build
Never,
}
impl From<ProgressFormat> for deacon_core::progress::ProgressFormat {
/// Convert this crate's `ProgressFormat` into the corresponding
/// `deacon_core::progress::ProgressFormat`.
///
/// # Examples
///
/// ```
/// use deacon::cli::ProgressFormat;
/// let core: deacon_core::progress::ProgressFormat = ProgressFormat::Json.into();
/// assert_eq!(core, deacon_core::progress::ProgressFormat::Json);
/// ```
fn from(format: ProgressFormat) -> Self {
match format {
ProgressFormat::None => deacon_core::progress::ProgressFormat::None,
ProgressFormat::Json => deacon_core::progress::ProgressFormat::Json,
ProgressFormat::Auto => deacon_core::progress::ProgressFormat::Auto,
}
}
}
/// Global options available to all subcommands
#[derive(Debug, Clone)]
#[allow(dead_code)] // Used for future command implementations
pub struct CliContext {
/// Log format (text or json)
pub log_format: LogFormat,
/// Log level
pub log_level: LogLevel,
/// Progress format
pub progress_format: ProgressFormat,
/// Progress file path (for JSON output)
pub progress_file: Option<PathBuf>,
/// Workspace folder path
pub workspace_folder: Option<PathBuf>,
/// Configuration file path
pub config: Option<PathBuf>,
/// Override configuration file path
pub override_config: Option<PathBuf>,
/// Secrets file paths
pub secrets_files: Vec<PathBuf>,
/// Whether secret redaction is disabled
pub no_redact: bool,
/// Enabled plugins
pub plugins: Vec<String>,
/// Container runtime selection
pub runtime: Option<deacon_core::runtime::RuntimeKind>,
}
/// DevContainer CLI subcommands
#[derive(Debug, Subcommand)]
#[allow(clippy::large_enum_variant)]
pub enum Commands {
/// Create and run development container
#[command(long_about = "Create and run development container\n\n\
When dev container features are configured, the following behaviors apply during container creation:\n\n \
- Security options (privileged, init, capAdd, securityOpt) from features are automatically merged into the container configuration\n \
- Feature lifecycle commands (onCreateCommand, postCreateCommand, etc.) execute before the corresponding config-level commands\n \
- Feature mounts are merged with config mounts; config mounts take precedence on target path conflicts\n \
- When multiple features define entrypoints, they are chained via a wrapper script to ensure all run in sequence")]
Up {
// Container identity and discovery
/// Container ID label(s) for identification (format: name=value, can be repeated)
#[arg(long, action = clap::ArgAction::Append)]
id_label: Vec<String>,
// Runtime behavior
/// Remove existing container(s) first
#[arg(long)]
remove_existing_container: bool,
/// Expect existing container (fail if not found)
#[arg(long)]
expect_existing_container: bool,
/// Stop after updateContentCommand (prebuild mode)
#[arg(long)]
prebuild: bool,
/// Skip postCreate lifecycle phase
#[arg(long)]
skip_post_create: bool,
/// Skip postAttach lifecycle phase
#[arg(long)]
skip_post_attach: bool,
/// Skip non-blocking commands (postStart & postAttach phases)
#[arg(long)]
skip_non_blocking_commands: bool,
/// Default user environment probe mode when config omits userEnvProbe.
/// Allowed values: `none`, `loginInteractiveShell`, `interactiveShell`, `loginShell`.
/// Default: `loginInteractiveShell`.
#[arg(long, value_enum, default_value = "login-interactive-shell")]
default_user_env_probe: DefaultUserEnvProbe,
// Mounts and environment
/// Additional mount (format: type=bind|volume,source=<path>,target=<path>[,external=true|false], can be repeated)
#[arg(long)]
mount: Vec<String>,
/// Remote environment variable (format: NAME=value, can be repeated)
#[arg(long)]
remote_env: Vec<String>,
/// Mount workspace git root instead of workspace folder
#[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
mount_workspace_git_root: bool,
/// Workspace mount consistency (consistent, cached, delegated)
#[arg(long)]
workspace_mount_consistency: Option<String>,
// Build and cache options
/// Build without using cache
#[arg(long)]
build_no_cache: bool,
/// External cache source (can be repeated, e.g. type=registry,ref=<image>)
#[arg(long)]
cache_from: Vec<String>,
/// External cache destination (e.g. type=registry,ref=<image>)
#[arg(long)]
cache_to: Option<String>,
/// BuildKit usage control (auto respects DOCKER_BUILDKIT, never disables)
#[arg(long, value_enum)]
buildkit: Option<BuildKitOption>,
// Features and dotfiles
/// Additional features to install (JSON map of id -> value/options)
#[arg(long)]
additional_features: Option<String>,
/// CLI features take precedence over config features on conflicts
#[arg(long)]
prefer_cli_features: bool,
/// Override feature installation order (comma-separated list of IDs)
#[arg(long)]
feature_install_order: Option<String>,
/// Skip feature auto-mapping (hidden testing flag)
#[arg(long, hide = true)]
skip_feature_auto_mapping: bool,
/// Disable lockfile generation and verification. Mutually exclusive with --frozen-lockfile.
#[arg(long)]
no_lockfile: bool,
/// Require an up-to-date lockfile; fail if resolution would change it.
/// Mutually exclusive with --no-lockfile.
#[arg(long)]
frozen_lockfile: bool,
/// DEPRECATED: use --frozen-lockfile (and pass a path via --config if needed).
/// Kept as a hidden alias through the 1.x line; emits a WARN when used.
#[arg(long, hide = true)]
experimental_lockfile: Option<PathBuf>,
/// DEPRECATED alias for --frozen-lockfile (graduated in 1.0). Hidden; emits a WARN.
#[arg(long, hide = true)]
experimental_frozen_lockfile: bool,
/// Dotfiles repository URL
#[arg(long)]
dotfiles_repository: Option<String>,
/// Dotfiles installation command
#[arg(long)]
dotfiles_install_command: Option<String>,
/// Dotfiles target path inside container
#[arg(long)]
dotfiles_target_path: Option<String>,
// Metadata and output control
/// Omit config remoteEnv from image metadata
#[arg(long)]
omit_config_remote_env_from_metadata: bool,
/// Omit Dockerfile syntax directive workaround
#[arg(long)]
omit_syntax_directive: bool,
/// Include configuration in JSON output
#[arg(long)]
include_configuration: bool,
/// Include merged configuration in JSON output
#[arg(long)]
include_merged_configuration: bool,
// GPU and advanced options
/// GPU handling mode for container operations
///
/// Controls how GPU resources are requested when creating containers.
///
/// Values:
/// all - Always request GPU resources (--gpus all)
/// detect - Auto-detect GPU availability; warn once if absent
/// none - No GPU requests, no GPU-related output (default)
///
/// In detect mode, the system will probe for GPU capabilities and emit
/// a single warning if no GPU runtime is found, then continue without GPU support.
#[arg(long = "gpu-mode", default_value = "none", value_enum)]
gpu_mode: deacon_core::gpu::GpuMode,
/// Update remote user UID default behavior (never, on, off)
#[arg(long)]
update_remote_user_uid_default: Option<String>,
// Port handling
/// Emit machine-readable port events to stdout with PORT_EVENT prefix
#[arg(long)]
ports_events: bool,
/// Forward port(s) from container to host (can be repeated)
/// Format: PORT or HOST_PORT:CONTAINER_PORT
#[arg(long = "forward-port")]
forward_ports: Vec<String>,
// Lifecycle
/// Automatically shut down when process exits
#[arg(long)]
shutdown: bool,
/// Custom container name (overrides generated name)
#[arg(long)]
container_name: Option<String>,
// Host requirements
/// Ignore host requirements validation (log warnings instead of failing)
#[arg(long)]
ignore_host_requirements: bool,
// Compose
/// Environment file(s) to pass to docker compose (can be repeated)
#[arg(long)]
env_file: Vec<PathBuf>,
},
/// Build development container image
#[cfg(feature = "full")]
Build {
/// Build without cache
#[arg(long)]
no_cache: bool,
/// Target platform for build (e.g. linux/amd64)
#[arg(long)]
platform: Option<String>,
/// Build argument in key=value format
#[arg(long)]
build_arg: Vec<String>,
/// Force rebuild even if cache is valid
#[arg(long)]
force: bool,
/// Output format (text or json)
#[arg(long, value_enum, default_value = "text")]
output_format: OutputFormat,
/// Cache source images (external cache sources like registry://<ref>)
#[arg(long)]
cache_from: Vec<String>,
/// Cache destination (external cache destinations like registry://<ref>)
#[arg(long)]
cache_to: Vec<String>,
/// BuildKit usage control (auto respects DOCKER_BUILDKIT, never disables)
#[arg(long, value_enum)]
buildkit: Option<BuildKitOption>,
/// Secret to expose to the build (format: id=secretname[,src=path])
#[arg(long)]
secret: Vec<String>,
/// Build secret (format: id=<id>[,src=<path>|env=<var>], requires BuildKit)
#[arg(long)]
build_secret: Vec<String>,
/// SSH agent socket or keys to expose to the build
#[arg(long)]
ssh: Vec<String>,
/// Run vulnerability scan on built image
#[arg(long)]
scan_image: bool,
/// Fail build if vulnerability scan returns non-zero exit code
#[arg(long, requires = "scan_image")]
fail_on_scan: bool,
/// Additional features to install (JSON map of id -> value/options)
#[arg(long)]
additional_features: Option<String>,
/// CLI features take precedence over config features on conflicts
#[arg(long)]
prefer_cli_features: bool,
/// Override feature installation order (comma-separated list of IDs)
#[arg(long)]
feature_install_order: Option<String>,
/// Ignore host requirements validation (log warnings instead of failing)
#[arg(long)]
ignore_host_requirements: bool,
/// Environment file(s) to pass to docker compose (can be repeated)
#[arg(long)]
env_file: Vec<PathBuf>,
/// Image name(s) to apply as tags (can be repeated)
#[arg(long = "image-name")]
image_names: Vec<String>,
/// Metadata label to apply to the image in key=value format (can be repeated)
#[arg(long)]
label: Vec<String>,
/// Push image to registry after build (requires BuildKit)
#[arg(long)]
push: bool,
/// Export image to file or directory (BuildKit format: type=...,dest=...)
#[arg(long)]
output: Option<String>,
/// Skip feature auto-mapping (hidden testing flag)
#[arg(long, hide = true)]
skip_feature_auto_mapping: bool,
/// Do not persist customizations from features into image metadata
#[arg(long, hide = true)]
skip_persisting_customizations_from_features: bool,
/// Disable lockfile generation and verification. Mutually exclusive with --frozen-lockfile.
#[arg(long)]
no_lockfile: bool,
/// Require an up-to-date lockfile; fail if resolution would change it.
/// Mutually exclusive with --no-lockfile.
#[arg(long)]
frozen_lockfile: bool,
/// DEPRECATED: lockfile is now written by default. Hidden alias kept through 1.x; emits a WARN.
#[arg(long, hide = true)]
experimental_lockfile: bool,
/// DEPRECATED alias for --frozen-lockfile (graduated in 1.0). Hidden; emits a WARN.
#[arg(long, hide = true)]
experimental_frozen_lockfile: bool,
/// Omit Dockerfile syntax directive workaround
#[arg(long, hide = true)]
omit_syntax_directive: bool,
},
/// Execute a command inside a running container.
///
/// Usage examples:
/// - `deacon exec --container-id <id> -- echo hello`
/// - `deacon exec --id-label devcontainer.local_folder=/abs/path -- sh -lc 'pwd'`
///
/// Note: At least one of `--container-id`, `--id-label` or `--workspace-folder` must be provided
/// unless the command is invoked in a context where the target container can be inferred.
Exec {
/// User to run the command as inside the container (overrides config `remoteUser`).
#[arg(long)]
user: Option<String>,
/// Disable TTY allocation (force non-interactive mode).
/// Use this when piping output or in CI where a PTY is not desired.
#[arg(long)]
no_tty: bool,
/// Remote environment variables to set inside the container (KEY=VALUE).
///
/// The legacy `--env` flag is kept as a hidden alias for backward compatibility.
/// Accepts empty values (e.g. `FOO=`) which will be injected as present with an
/// empty string value.
#[arg(long = "remote-env", action = clap::ArgAction::Append, alias = "env")]
remote_env: Vec<String>,
/// Working directory inside the container for command execution (overrides default).
#[arg(short = 'w', long)]
workdir: Option<String>,
/// Target container ID directly (highest precedence selection).
#[arg(long)]
container_id: Option<String>,
/// Identify container by labels (KEY=VALUE format, repeatable).
/// Validated as `<name>=<value>`; multiple labels are combined as AND selectors.
#[arg(long, action = clap::ArgAction::Append)]
id_label: Vec<String>,
/// Mount workspace git root (default: true). When true and the workspace
/// folder lives inside a git repo, config discovery and mounts walk up to
/// the repo root. Set to false to use the workspace folder as-is. Has no
/// effect when `--container-id` or `--id-label` is supplied.
#[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
mount_workspace_git_root: bool,
/// Target specific service in Docker Compose projects (defaults to the primary service).
#[arg(long)]
service: Option<String>,
/// Environment file(s) to pass to docker compose (can be repeated).
#[arg(long)]
env_file: Vec<PathBuf>,
/// Default user environment probe mode when config omits `userEnvProbe`.
/// Allowed values: `none`, `loginInteractiveShell`, `interactiveShell`, `loginShell`.
/// Default: `loginInteractiveShell` (collects shell-initialized environment where possible).
#[arg(long, value_enum, default_value = "login-interactive-shell")]
default_user_env_probe: DefaultUserEnvProbe,
/// Command and arguments to execute inside the container (positional; required).
command: Vec<String>,
},
/// Read and display configuration
ReadConfiguration {
/// Include merged configuration
#[arg(long)]
include_merged_configuration: bool,
/// Include features configuration
#[arg(long)]
include_features_configuration: bool,
/// Target container ID directly
#[arg(long)]
container_id: Option<String>,
/// Identify container by labels (KEY=VALUE format, can be specified multiple times).
/// Used to locate the container if --container-id is not provided. If neither --container-id nor --id-label is set, one is inferred from --workspace-folder.
#[arg(long, action = clap::ArgAction::Append)]
id_label: Vec<String>,
/// Mount workspace git root (default: true)
#[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
mount_workspace_git_root: bool,
/// Additional features to install (JSON map of id -> value/options)
#[arg(long)]
additional_features: Option<String>,
/// Skip feature auto-mapping (hidden testing flag)
#[arg(long, hide = true)]
skip_feature_auto_mapping: bool,
/// Terminal columns (requires --terminal-rows)
#[arg(long)]
terminal_columns: Option<u32>,
/// Terminal rows (requires --terminal-columns)
#[arg(long)]
terminal_rows: Option<u32>,
/// User data folder (accepted but not used by this subcommand)
#[arg(long)]
user_data_folder: Option<PathBuf>,
},
/// Configuration management commands
#[cfg(feature = "full")]
Config {
/// Config subcommand
#[command(subcommand)]
command: ConfigCommands,
},
/// Template management commands
#[cfg(feature = "full")]
Templates {
/// Template subcommand
#[command(subcommand)]
command: TemplateCommands,
},
/// Convert an already-running container into a DevContainer by applying
/// configuration + image metadata, executing lifecycle hooks, and emitting
/// a JSON snapshot of the resulting configuration.
///
/// See `docs/subcommand-specs/set-up/SPEC.md` for the authoritative behavior.
#[cfg(feature = "full")]
SetUp {
/// Target container ID (required). The container must already exist.
#[arg(long)]
container_id: String,
/// Optional path to a devcontainer.json to layer on top of the
/// container's embedded image metadata.
#[arg(long)]
config: Option<PathBuf>,
/// Skip all lifecycle hooks (onCreate, updateContent, postCreate,
/// postStart, postAttach) and dotfiles installation.
#[arg(long)]
skip_post_create: bool,
/// Stop after the configured `waitFor` hook (default `updateContent`).
#[arg(long)]
skip_non_blocking_commands: bool,
/// Extra remote env to inject when running hooks (repeatable).
#[arg(long = "remote-env", action = clap::ArgAction::Append)]
remote_env: Vec<String>,
/// Dotfiles git repository URL or `owner/repo` shorthand.
#[arg(long)]
dotfiles_repository: Option<String>,
/// Custom dotfiles install command. When omitted, the installer
/// auto-detects `install.sh` / `bootstrap` / `setup` / `script/*`.
#[arg(long)]
dotfiles_install_command: Option<String>,
/// Target path inside the container for the dotfiles clone. Defaults
/// to `~/dotfiles` (`/root/dotfiles` when running as root).
#[arg(long)]
dotfiles_target_path: Option<String>,
/// Include the (substituted) configuration in the JSON result.
#[arg(long)]
include_configuration: bool,
/// Include the (substituted) merged configuration in the JSON result.
#[arg(long)]
include_merged_configuration: bool,
/// Inside-container user data root (default `~/.devcontainer`).
#[arg(long)]
container_data_folder: Option<PathBuf>,
},
/// Run user-defined lifecycle commands
#[cfg(feature = "full")]
#[allow(clippy::enum_variant_names)]
RunUserCommands {
/// Skip postCreate lifecycle phase
#[arg(long)]
skip_post_create: bool,
/// Skip postAttach lifecycle phase
#[arg(long)]
skip_post_attach: bool,
/// Skip non-blocking commands (postStart & postAttach phases)
#[arg(long)]
skip_non_blocking_commands: bool,
/// Stop after updateContentCommand (prebuild mode)
#[arg(long)]
prebuild: bool,
/// Stop before personalization
#[arg(long)]
stop_for_personalization: bool,
/// Target container ID directly
#[arg(long)]
container_id: Option<String>,
/// Identify container by labels (KEY=VALUE format, can be specified multiple times)
#[arg(long, action = clap::ArgAction::Append)]
id_label: Vec<String>,
},
// PR-6a SetUp variant moved earlier in this file with PR-6b dotfiles flags.
/// Stop and optionally remove development container or compose project
Down {
/// Remove containers after stopping them
#[arg(long)]
remove: bool,
/// Include all containers matching labels (stale containers)
#[arg(long)]
all: bool,
/// Remove associated anonymous volumes
#[arg(long)]
volumes: bool,
/// Force removal of running containers
#[arg(long)]
force: bool,
/// Timeout in seconds for stopping containers (default: 30)
#[arg(long)]
timeout: Option<u32>,
},
/// Environment diagnostics and support bundle creation
///
/// Collects system information for troubleshooting and support
#[cfg(feature = "full")]
Doctor {
/// Output in JSON format
#[arg(long)]
json: bool,
/// Create support bundle at specified path
#[arg(long)]
bundle: Option<PathBuf>,
},
/// Report outdated features (current | wanted | latest)
///
/// Examples:
/// deacon outdated --workspace-folder .
/// # Human-readable table (default)
/// deacon outdated --output json
/// # Machine-readable JSON written to stdout (logs to stderr)
/// deacon outdated --output json --fail-on-outdated
/// # Exit with code 2 when any feature is outdated (CI gating)
///
/// Output contracts: by default a text table is written to stdout; when
/// `--output json` is specified a compact JSON map is written to stdout and
/// all logs/diagnostic messages are sent to stderr. This ensures deterministic
/// machine-readable behavior for CI and tooling.
#[cfg(feature = "full")]
Outdated {
/// Workspace folder to inspect (default: current directory)
#[arg(long, value_name = "PATH")]
workspace_folder: Option<PathBuf>,
/// Output format (text or json)
#[arg(long, value_enum, default_value = "text")]
output: OutputFormat,
/// Fail CI with exit code 2 when any outdated feature is detected
#[arg(long)]
fail_on_outdated: bool,
},
}
/// Template management subcommands
#[cfg(feature = "full")]
#[derive(Debug, Clone, Subcommand)]
pub enum TemplateCommands {
/// Apply template to current project
Apply {
/// Template path (local directory) or registry reference
template: String,
/// Template option in key=value format
#[arg(long)]
option: Vec<String>,
/// Output directory for applied template (default: current directory)
#[arg(long)]
output: Option<String>,
/// Force overwrite existing files
#[arg(long)]
force: bool,
/// Dry run mode - preview operations without making changes
#[arg(long)]
dry_run: bool,
},
/// Pull templates from registry
Pull {
/// Registry reference (registry/namespace/name:version)
registry_ref: String,
/// Output in JSON format
#[arg(long)]
json: bool,
},
}
/// Configuration management subcommands
#[cfg(feature = "full")]
#[derive(Debug, Clone, Subcommand)]
pub enum ConfigCommands {
/// Apply variable substitution to configuration and preview results
Substitute {
/// Preview substitution without applying changes (dry-run mode)
#[arg(long)]
dry_run: bool,
/// Use strict substitution mode (fail on unresolved variables)
#[arg(long)]
strict_substitution: bool,
/// Maximum recursion depth for nested variable substitution
#[arg(long, default_value = "5")]
max_depth: usize,
/// Enable multi-pass nested variable resolution
#[arg(long = "nested", default_value_t = true, action = clap::ArgAction::Set)]
nested: bool,
/// Output format (text or json)
#[arg(long, value_enum, default_value = "json")]
output_format: OutputFormat,
},
}
#[derive(Parser, Debug)]
#[command(
name = env!("CARGO_PKG_NAME"),
version,
about = "Development container CLI",
long_about = "Development container CLI\n\nImplements the Development Containers specification for creating and managing development environments.",
color = clap::ColorChoice::Auto
)]
pub struct Cli {
/// Log format (text or json, defaults to text, can be set via DEACON_LOG_FORMAT env var)
#[arg(long, global = true, value_enum)]
pub log_format: Option<LogFormat>,
/// Log level
#[arg(long, global = true, value_enum, default_value = "info")]
pub log_level: LogLevel,
/// Workspace folder path
#[arg(long, global = true, value_name = "PATH")]
pub workspace_folder: Option<PathBuf>,
/// Configuration file path
#[arg(long, global = true, value_name = "PATH")]
pub config: Option<PathBuf>,
/// Override configuration file path (highest precedence)
#[arg(long, global = true, value_name = "PATH")]
pub override_config: Option<PathBuf>,
/// Secrets file path (KEY=VALUE format, can be specified multiple times)
#[arg(long, global = true, value_name = "PATH")]
pub secrets_file: Vec<PathBuf>,
/// Disable secret redaction in output (debugging only - WARNING: may expose secrets)
#[arg(long, global = true)]
pub no_redact: bool,
/// Progress format (json|none|auto). Auto is silent unless --progress-file is set.
#[arg(long, global = true, value_enum, default_value = "auto")]
pub progress: ProgressFormat,
/// Progress file path (for JSON output when using --progress auto or json)
#[arg(long, global = true, value_name = "PATH")]
pub progress_file: Option<PathBuf>,
/// Enable specific plugins
#[arg(long, global = true, value_name = "NAME")]
pub plugin: Vec<String>,
/// Container runtime to use (docker or podman [experimental]; can be set via DEACON_RUNTIME env var)
#[arg(long, global = true, value_enum)]
pub runtime: Option<RuntimeOption>,
/// Path to docker executable
#[arg(long, global = true, default_value = "docker")]
pub docker_path: String,
/// Path to docker-compose executable
#[arg(long, global = true, default_value = "docker-compose")]
pub docker_compose_path: String,
/// Container-side data folder for user state inside the container
#[arg(long, global = true)]
pub container_data_folder: Option<PathBuf>,
/// Container-side system data folder inside the container
#[arg(long, global = true)]
pub container_system_data_folder: Option<PathBuf>,
/// Host-side user data folder for persistent user state
#[arg(long, global = true)]
pub user_data_folder: Option<PathBuf>,
/// Container-side session data folder for temporary session state
#[arg(long, global = true)]
pub container_session_data_folder: Option<PathBuf>,
/// Force PTY (pseudo-terminal) allocation for lifecycle exec commands when using JSON log format.
///
/// This flag only takes effect when --log-format json is active. It allows interactive
/// commands in lifecycle hooks (onCreate, postCreate, etc.) to behave correctly while
/// maintaining structured JSON logs on stderr and machine-readable output on stdout.
///
/// Precedence: CLI flag > DEACON_FORCE_TTY_IF_JSON environment variable > default (no PTY).
///
/// Environment variable: DEACON_FORCE_TTY_IF_JSON
/// - Truthy values (case-insensitive): true, 1, yes
/// - Falsey values or unset: false, 0, no, or absent
///
/// When disabled (default), lifecycle commands run without PTY allocation. This is suitable
/// for non-interactive scripts and automated environments.
#[arg(long, global = true)]
pub force_tty_if_json: bool,
/// Default user env probe mode (none|loginInteractiveShell|interactiveShell|loginShell)
#[arg(
long,
global = true,
value_enum,
default_value = "login-interactive-shell"
)]
pub default_user_env_probe: DefaultUserEnvProbe,
/// Terminal columns for output formatting (requires --terminal-rows)
#[arg(long, global = true, requires = "terminal_rows")]
pub terminal_columns: Option<u32>,
/// Terminal rows for output formatting (requires --terminal-columns)
#[arg(long, global = true, requires = "terminal_columns")]
pub terminal_rows: Option<u32>,
/// Subcommand to execute
#[command(subcommand)]
pub command: Option<Commands>,
}
impl Cli {
fn normalized_terminal_dimensions(&self) -> Result<Option<TerminalDimensions>> {
TerminalDimensions::new(self.terminal_columns, self.terminal_rows)
}
/// Validate CLI arguments after parsing
///
/// Performs additional validation beyond what clap provides automatically.
/// Currently validates that terminal dimensions (if provided) are positive integers.
///
/// # Errors
///
/// Returns an error if terminal dimensions are zero or if any other validation fails.
///
/// # Examples
///
/// ```
/// use clap::Parser;
/// let cli = deacon::cli::Cli::parse_from(&["deacon"]);
/// assert!(cli.validate().is_ok());
/// ```
#[cfg_attr(not(test), allow(dead_code))]
pub fn validate(&self) -> Result<()> {
self.normalized_terminal_dimensions()?;
Ok(())
}
/// Extract global options into CliContext.
///
/// Returns a new `CliContext` populated with the values from this `Cli` instance
/// (log and progress settings, workspace/config paths, secrets, and plugin list when enabled).
///
/// # Examples
///
/// ```
/// use clap::Parser;
/// // Parse CLI arguments (use just the program name to rely on defaults)
/// let cli = deacon::cli::Cli::parse_from(&["deacon"]);
/// let ctx = cli.context();
/// // Context should be constructed; workspace_folder is optional by default
/// assert!(ctx.workspace_folder.is_none());
/// ```
/// Returns true when the effective log format is JSON.
/// `--log-format json` wins; if unset, `DEACON_LOG_FORMAT=json` counts too
/// (matches the fallback in deacon_core::logging::init).
pub fn is_json_log_format(&self) -> bool {
match self.log_format {
Some(LogFormat::Json) => true,
Some(LogFormat::Text) => false,
None => std::env::var("DEACON_LOG_FORMAT")
.map(|v| v == "json")
.unwrap_or(false),
}
}
#[allow(dead_code)] // Reserved for future command implementations; see runtime_utils
pub fn context(&self) -> CliContext {
CliContext {
log_format: self.log_format.clone().unwrap_or(LogFormat::Text), // Default to Text if not specified
log_level: self.log_level.clone(),
progress_format: self.progress.clone(),
progress_file: self.progress_file.clone(),
workspace_folder: self.workspace_folder.clone(),
config: self.config.clone(),
override_config: self.override_config.clone(),
secrets_files: self.secrets_file.clone(),
no_redact: self.no_redact,
plugins: self.plugin.clone(),
runtime: self.runtime.map(|r| r.into()),
}
}
/// Dispatches the CLI subcommand represented by this `Cli` instance.
///
/// Initializes logging and progress tracking according to the CLI options, then
/// executes the selected subcommand. Returns `Ok(())` on success or an error
/// propagated from the invoked command. If no subcommand is provided, a brief
/// help-like message is printed and `Ok(())` is returned. For the `up`
/// subcommand, a missing configuration file is mapped to a user-facing error
/// message ("No devcontainer.json found in workspace") to preserve CLI
/// compatibility.
///
/// # Examples
///
/// ```no_run
/// use tokio::runtime::Runtime;
/// // Construct `Cli` via your preferred method (e.g., `Cli::parse()` or manual).
/// // let cli = Cli::parse_from(&["deacon", "build", "--no-cache"]);
/// // For demonstration, assume `cli` is available:
/// // let cli = ... ;
/// // Execute the dispatcher in a tokio runtime:
/// // Runtime::new().unwrap().block_on(cli.dispatch()).unwrap();
/// ```
pub async fn dispatch(self) -> Result<()> {
// Normalize terminal dimensions once for downstream consumers
let terminal_dimensions = self.normalized_terminal_dimensions()?;
// Initialize logging based on global options
let log_format = match self.log_format {
Some(LogFormat::Text) => Some("text"),
Some(LogFormat::Json) => Some("json"),
None => None, // Let logging module check environment variable
};
let mut log_level = match self.log_level {
LogLevel::Error => "error",
LogLevel::Warn => "warn",
LogLevel::Info => "info",
LogLevel::Debug => "debug",
LogLevel::Trace => "trace",
};
// Determine if spinner-friendly session: progress auto, no progress_file, stderr is TTY, non-JSON format.
let stderr_is_tty = std::io::stderr().is_terminal();
let json_format = self.is_json_log_format();
let spinner_eligible = self.progress == ProgressFormat::Auto
&& self.progress_file.is_none()
&& stderr_is_tty
&& !json_format;
// Set environment variable for log level before initializing logging
if std::env::var_os("DEACON_LOG").is_none() && std::env::var_os("RUST_LOG").is_none() {
// In spinner sessions, prefer quieter default unless user overrode via flag/env
if spinner_eligible {
log_level = "warn";
}
std::env::set_var(
"RUST_LOG",
format!("deacon={},deacon_core={}", log_level, log_level),
);
}
deacon_core::logging::init(log_format)?;
// Emit logs to help with testing and log-level verification
tracing::debug!("CLI initialized with log level: {}", log_level);
tracing::trace!("Trace-level logging enabled (probe)");
// Warn if redaction is disabled
if self.no_redact {
tracing::warn!("Secret redaction is DISABLED via --no-redact flag. This may expose sensitive information in logs and output. Use only for debugging purposes!");
}
// Create redaction configuration from CLI flags
let redaction_config = if self.no_redact {
deacon_core::redaction::RedactionConfig::disabled()
} else {
deacon_core::redaction::RedactionConfig::default()
};
// Get global secret registry
let secret_registry = deacon_core::redaction::global_registry();
// Initialize progress tracking
let progress_format: deacon_core::progress::ProgressFormat = self.progress.clone().into();
// Prefer spinner emitter in eligible sessions; otherwise fall back to core helper
let progress_tracker = if spinner_eligible {
// Build a tracker with SpinnerEmitter
use deacon_core::progress::get_cache_dir;
use deacon_core::progress::ProgressTracker;
let cache_dir = get_cache_dir()?;
let emitter: Box<dyn deacon_core::progress::ProgressEmitter> =
Box::new(SpinnerEmitter::new());
Some(ProgressTracker::new(
Some(emitter),
Some(&cache_dir),
redaction_config.clone(),
)?)
} else {
deacon_core::progress::create_progress_tracker(
&progress_format,
self.progress_file.as_deref(),
self.workspace_folder.as_deref(),
&redaction_config,
secret_registry,
)?
};
// Convert to Arc<Mutex<Option<_>>> for sharing between operations
let progress_tracker = std::sync::Arc::new(std::sync::Mutex::new(progress_tracker));