-
Notifications
You must be signed in to change notification settings - Fork 181
Expand file tree
/
Copy pathcommand.rs
More file actions
1928 lines (1745 loc) · 65.5 KB
/
command.rs
File metadata and controls
1928 lines (1745 loc) · 65.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
// Copyright 2024-2025 Golem Cloud
//
// Licensed under the Golem Source License v1.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://license.golem.cloud/LICENSE
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::command::api::ApiSubcommand;
use crate::command::cloud::CloudSubcommand;
use crate::command::component::ComponentSubcommand;
use crate::command::environment::EnvironmentSubcommand;
use crate::command::exec::ExecSubcommand;
use crate::command::plugin::PluginSubcommand;
use crate::command::profile::ProfileSubcommand;
#[cfg(feature = "server-commands")]
use crate::command::server::ServerSubcommand;
use crate::command::shared_args::{
BuildArgs, ForceBuildArg, OptionalComponentName, OptionalComponentNames, PostDeployArgs,
};
use crate::command::worker::AgentSubcommand;
use crate::config::ProfileName;
use crate::error::ShowClapHelpTarget;
use crate::log::LogColorize;
use crate::model::app::ComponentPresetName;
use crate::model::cli_command_metadata::{CliCommandMetadata, CliMetadataFilter};
use crate::model::environment::EnvironmentReference;
use crate::model::format::Format;
use crate::model::repl::ReplLanguage;
use crate::model::worker::{AgentUpdateMode, WorkerName};
use crate::model::GuestLanguage;
use crate::{command_name, version};
use anyhow::{anyhow, bail, Context as AnyhowContext};
use chrono::{DateTime, Utc};
use clap::error::{ContextKind, ContextValue, ErrorKind};
use clap::{self, Command, CommandFactory, Subcommand};
use clap::{Args, Parser};
use clap_verbosity_flag::{ErrorLevel, LogLevel};
use golem_client::model::ScanCursor;
use golem_common::model::agent::AgentTypeName;
use golem_common::model::application::ApplicationName;
use golem_common::model::component::{ComponentName, ComponentRevision};
use golem_common::model::deployment::DeploymentRevision;
use lenient_bool::LenientBool;
use std::collections::{BTreeSet, HashMap};
use std::ffi::OsString;
use std::path::PathBuf;
/// Golem Command Line Interface
#[derive(Debug, Parser)]
#[command(bin_name = command_name(), display_name = command_name(), long_version = version())]
pub struct GolemCliCommand {
#[command(flatten)]
pub global_flags: GolemCliGlobalFlags,
#[clap(subcommand)]
pub subcommand: GolemCliSubcommand,
}
impl GolemCliCommand {
pub fn collect_metadata() -> CliCommandMetadata {
CliCommandMetadata::new(&Self::command())
}
pub fn collect_metadata_for_repl() -> CliCommandMetadata {
CliCommandMetadata::new_filtered(
&GolemCliCommand::command(),
&CliMetadataFilter {
command_path_prefix_exclude: vec![
vec!["api"], // TODO: recheck after code-first routes is implemented
vec!["clean"],
vec!["cloud"],
vec!["completion"],
vec!["generate-bridge"],
vec!["new"],
vec!["plugin"],
vec!["profile"],
vec!["repl"],
vec!["server"],
],
arg_id_exclude: vec![
"app_manifest_path",
"cloud",
"config_dir",
"dev_mode",
"disable_app_manifest_discovery",
"environment",
"local",
"preset",
"profile",
"show_sensitive",
"template_group",
],
exclude_hidden: true,
},
)
}
}
// NOTE: inlined from clap-verbosity-flag, so we can override display order,
// check for possible changes when upgrading clap-verbosity-flag
#[derive(clap::Args, Debug, Clone, Copy, Default)]
#[command(about = None, long_about = None)]
pub struct Verbosity<L: LogLevel = ErrorLevel> {
#[arg(
long,
short = 'v',
action = clap::ArgAction::Count,
global = true,
help = L::verbose_help(),
long_help = L::verbose_long_help(),
display_order = 201
)]
verbose: u8,
#[arg(
long,
short = 'q',
action = clap::ArgAction::Count,
global = true,
help = L::quiet_help(),
long_help = L::quiet_long_help(),
conflicts_with = "verbose",
display_order = 202
)]
quiet: u8,
#[arg(skip)]
phantom: std::marker::PhantomData<L>,
}
impl Verbosity {
pub fn as_clap_verbosity_flag(self) -> clap_verbosity_flag::Verbosity {
clap_verbosity_flag::Verbosity::new(self.verbose, self.quiet)
}
}
// TODO: flags for defining target server for "non-manifest" mode
#[derive(Debug, Clone, Default, Args)]
pub struct GolemCliGlobalFlags {
/// Output format, defaults to text, unless specified by the selected profile
#[arg(long, short = 'F', global = true, display_order = 101)]
pub format: Option<Format>,
/// Select Golem environment by name
#[arg(long, short = 'E', global = true, display_order = 102)]
pub environment: Option<EnvironmentReference>,
/// Select "local" environment from the manifest, or "local" profile
#[arg(long, short = 'L', global = true, conflicts_with_all = ["cloud"], display_order = 103)]
pub local: bool,
/// Select "cloud" environment from the manifest, or "cloud" profile
#[arg(long, short = 'C', global = true, conflicts_with_all = ["local"], display_order = 104)]
pub cloud: bool,
/// Custom path to the root application manifest (golem.yaml)
#[arg(long, short = 'A', global = true, display_order = 105)]
pub app_manifest_path: Option<PathBuf>,
/// Disable automatic searching for application manifests
#[arg(long, short = 'X', global = true, display_order = 106)]
pub disable_app_manifest_discovery: bool,
/// Select custom component presets
#[arg(
long,
short = 'P',
global = true,
value_delimiter = ',',
display_order = 107
)]
pub preset: Vec<ComponentPresetName>,
/// Select Golem profile by name
#[arg(long, global = true, display_order = 108)]
pub profile: Option<ProfileName>,
/// Custom path to the config directory (defaults to $HOME/.golem)
#[arg(long, global = true, display_order = 109)]
config_dir: Option<PathBuf>,
/// Automatically answer "yes" to any interactive confirm questions
#[arg(long, short = 'Y', global = true, display_order = 110)]
pub yes: bool,
/// Disables filtering of potentially sensitive use values in text mode (e.g. component environment variable values)
#[arg(long, global = true, display_order = 111)]
pub show_sensitive: bool,
/// Enable experimental, development-only features
#[arg(long, global = true, display_order = 112)]
pub dev_mode: bool,
/// Switch to experimental or development-only template groups
#[arg(long, global = true, display_order = 113)]
pub template_group: Option<String>,
#[command(flatten)]
verbosity: Verbosity,
// The flags below can only be set through env vars, as they are mostly
// useful for testing, so we do not want to pollute the flag space with them
#[arg(skip)]
pub golem_rust_path: Option<PathBuf>,
#[arg(skip)]
pub golem_rust_version: Option<String>,
#[arg(skip)]
pub golem_ts_packages_path: Option<String>,
#[arg(skip)]
pub golem_ts_version: Option<String>,
#[arg(skip)]
pub wasm_rpc_offline: bool,
#[arg(skip)]
http_batch_size: Option<u64>,
#[arg(skip)]
http_parallelism: Option<usize>,
#[arg(skip)]
pub auth_token: Option<String>,
#[arg(skip)]
pub server_no_limit_change: bool,
#[arg(skip)]
pub enable_wasmtime_fs_cache: bool,
}
impl GolemCliGlobalFlags {
pub fn with_env_overrides(mut self) -> anyhow::Result<GolemCliGlobalFlags> {
if self.profile.is_none() {
if let Ok(profile) = std::env::var("GOLEM_PROFILE") {
self.profile = Some(profile.into());
}
}
if self.environment.is_none() {
if let Ok(environment) = std::env::var("GOLEM_ENVIRONMENT") {
self.environment = Some(
EnvironmentReference::try_from(environment)
.map_err(|err| anyhow!(err))
.context("Failed to parse GOLEM_ENVIRONMENT environment variable")?,
);
}
}
if self.app_manifest_path.is_none() {
if let Ok(app_manifest_path) = std::env::var("GOLEM_APP_MANIFEST_PATH") {
self.app_manifest_path = Some(PathBuf::from(app_manifest_path));
}
}
if !self.disable_app_manifest_discovery {
if let Ok(disable) = std::env::var("GOLEM_DISABLE_APP_MANIFEST_DISCOVERY") {
self.disable_app_manifest_discovery = disable
.parse::<LenientBool>()
.map(|b| b.into())
.unwrap_or_default()
}
}
if self.preset.is_empty() {
if let Ok(preset) = std::env::var("GOLEM_PRESET") {
self.preset = preset
.split(',')
.map(|preset| preset.parse())
.collect::<Result<Vec<_>, String>>()
.map_err(|err| anyhow!(err))?;
}
}
if let Ok(offline) = std::env::var("GOLEM_WASM_RPC_OFFLINE") {
self.wasm_rpc_offline = offline
.parse::<LenientBool>()
.map(|b| b.into())
.unwrap_or_default()
}
if self.golem_rust_path.is_none() {
if let Ok(golem_rust_path) = std::env::var("GOLEM_RUST_PATH") {
self.golem_rust_path = Some(PathBuf::from(golem_rust_path));
}
}
if self.golem_rust_version.is_none() {
if let Ok(version) = std::env::var("GOLEM_RUST_VERSION") {
self.golem_rust_version = Some(version);
}
}
if self.golem_ts_packages_path.is_none() {
if let Ok(golem_ts_packages_path) = std::env::var("GOLEM_TS_PACKAGES_PATH") {
self.golem_ts_packages_path = Some(golem_ts_packages_path);
}
}
if self.golem_ts_version.is_none() {
if let Ok(version) = std::env::var("GOLEM_TS_VERSION") {
self.golem_ts_version = Some(version);
}
}
if let Ok(batch_size) = std::env::var("GOLEM_HTTP_BATCH_SIZE") {
self.http_batch_size =
Some(batch_size.parse().with_context(|| {
format!("Failed to parse GOLEM_HTTP_BATCH_SIZE: {batch_size}")
})?)
}
if let Ok(parallelism) = std::env::var("GOLEM_HTTP_PARALLELISM") {
self.http_parallelism = Some(parallelism.parse().with_context(|| {
format!("Failed to parse GOLEM_HTTP_PARALLELISM: {parallelism}")
})?)
}
if let Ok(auth_token) = std::env::var("GOLEM_AUTH_TOKEN") {
self.auth_token = Some(
auth_token
.parse()
.context("Failed to parse GOLEM_AUTH_TOKEN, expected uuid")?,
);
}
if let Ok(server_no_limit_change) = std::env::var("GOLEM_SERVER_NO_LIMIT_CHANGE") {
self.server_no_limit_change = server_no_limit_change
.parse::<LenientBool>()
.map(|b| b.into())
.unwrap_or_default()
}
if let Ok(enable_wasmtime_fs_cache) = std::env::var("GOLEM_ENABLE_WASMTIME_FS_CACHE") {
self.enable_wasmtime_fs_cache = enable_wasmtime_fs_cache
.parse::<LenientBool>()
.map(|b| b.into())
.unwrap_or_default()
}
Ok(self)
}
pub fn config_dir(&self) -> PathBuf {
self.config_dir
.clone()
.unwrap_or_else(|| dirs::home_dir().unwrap().join(".golem"))
}
pub fn http_batch_size(&self) -> u64 {
self.http_batch_size.unwrap_or(50)
}
pub fn http_parallelism(&self) -> usize {
self.http_parallelism.unwrap_or(4)
}
pub fn verbosity(&self) -> clap_verbosity_flag::Verbosity {
self.verbosity.as_clap_verbosity_flag()
}
}
#[derive(Debug, Default, Parser)]
#[command(ignore_errors = true)]
pub struct GolemCliFallbackCommand {
#[command(flatten)]
pub global_flags: GolemCliGlobalFlags,
pub positional_args: Vec<String>,
#[arg(skip)]
pub parse_error: Option<clap::Error>,
}
impl GolemCliFallbackCommand {
fn try_parse_from<I, T>(args: I, with_env_overrides: bool) -> anyhow::Result<Self>
where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
{
let args = args
.into_iter()
.map(|arg| arg.into())
.filter(|arg| arg != "-h" && arg != "--help")
.collect::<Vec<OsString>>();
let mut cmd = <Self as Parser>::try_parse_from(args).unwrap_or_else(|error| {
GolemCliFallbackCommand {
parse_error: Some(error),
..Self::default()
}
});
if with_env_overrides {
cmd.global_flags = cmd.global_flags.with_env_overrides()?;
}
Ok(cmd)
}
}
impl GolemCliCommand {
pub fn try_parse_from_lenient<I, T>(
iterator: I,
with_env_overrides: bool,
) -> GolemCliCommandParseResult
where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
{
let args = iterator
.into_iter()
.map(|arg| arg.into())
.collect::<Vec<OsString>>();
match GolemCliCommand::try_parse_from(&args) {
Ok(mut command) => {
if with_env_overrides {
match command.global_flags.with_env_overrides() {
Ok(global_flags) => {
command.global_flags = global_flags;
}
Err(err) => {
return GolemCliCommandParseResult::Error {
error: clap::Error::raw(ErrorKind::InvalidValue, err),
fallback_command: Default::default(),
}
}
}
}
GolemCliCommandParseResult::FullMatch(command)
}
Err(error) => {
let fallback_command =
match GolemCliFallbackCommand::try_parse_from(&args, with_env_overrides) {
Ok(fallback_command) => fallback_command,
Err(err) => {
return GolemCliCommandParseResult::Error {
error: clap::Error::raw(ErrorKind::InvalidValue, err),
fallback_command: Default::default(),
}
}
};
let partial_match = match error.kind() {
ErrorKind::DisplayHelp => {
let positional_args = fallback_command
.positional_args
.iter()
.map(|arg| arg.as_ref())
.collect::<Vec<_>>();
match positional_args.as_slice() {
[] => Some(GolemCliCommandPartialMatch::AppHelp),
["exec"] => Some(GolemCliCommandPartialMatch::AppMissingSubcommandHelp),
["component"] => Some(GolemCliCommandPartialMatch::ComponentHelp),
["agent"] => Some(GolemCliCommandPartialMatch::AgentHelp),
_ => None,
}
}
ErrorKind::MissingRequiredArgument => {
error.context().find_map(|context| match context {
(ContextKind::InvalidArg, ContextValue::Strings(args)) => {
Self::match_invalid_arg(
&fallback_command.positional_args,
args,
&Self::invalid_arg_matchers(),
)
}
_ => None,
})
}
ErrorKind::MissingSubcommand
| ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand => {
let positional_args = fallback_command
.positional_args
.iter()
.map(|arg| arg.as_ref())
.collect::<Vec<_>>();
match positional_args.as_slice() {
[] => Some(GolemCliCommandPartialMatch::AppMissingSubcommandHelp),
["exec"] => Some(GolemCliCommandPartialMatch::AppMissingSubcommandHelp),
["component"] => {
Some(GolemCliCommandPartialMatch::ComponentMissingSubcommandHelp)
}
_ => None,
}
}
_ => None,
};
match partial_match {
Some(partial_match) => GolemCliCommandParseResult::ErrorWithPartialMatch {
error,
fallback_command,
partial_match,
},
None => GolemCliCommandParseResult::Error {
error,
fallback_command,
},
}
}
}
}
fn invalid_arg_matchers() -> Vec<InvalidArgMatcher> {
vec![
InvalidArgMatcher {
subcommands: vec!["agent", "invoke"],
found_positional_args: vec![],
missing_positional_arg: "agent_id",
to_partial_match: |_| GolemCliCommandPartialMatch::WorkerInvokeMissingWorkerName,
},
InvalidArgMatcher {
subcommands: vec!["agent", "invoke"],
found_positional_args: vec!["agent_id"],
missing_positional_arg: "function_name",
to_partial_match: |args| {
GolemCliCommandPartialMatch::WorkerInvokeMissingFunctionName {
worker_name: args[0].clone().into(),
}
},
},
InvalidArgMatcher {
subcommands: vec!["profile", "switch"],
missing_positional_arg: "profile_name",
found_positional_args: vec![],
to_partial_match: |_| GolemCliCommandPartialMatch::ProfileSwitchMissingProfileName,
},
]
}
fn match_invalid_arg(
positional_args: &[String],
error_context_args: &[String],
matchers: &[InvalidArgMatcher],
) -> Option<GolemCliCommandPartialMatch> {
let command = Self::command();
let positional_args = positional_args
.iter()
.map(|str| str.as_str())
.collect::<Vec<_>>();
for matcher in matchers {
if positional_args.len() < matcher.subcommands.len() {
continue;
}
let missing_arg_error_name =
format!("<{}>", matcher.missing_positional_arg.to_uppercase());
let missing_args_error_name = format!("{missing_arg_error_name}...");
if !error_context_args.contains(&missing_arg_error_name)
&& !error_context_args.contains(&missing_args_error_name)
{
continue;
}
if !positional_args.starts_with(&matcher.subcommands) {
continue;
}
let mut command = &command;
for subcommand in &matcher.subcommands {
command = command.find_subcommand(subcommand).unwrap();
}
let positional_arg_ids_to_idx = command
.get_arguments()
.filter(|arg| arg.is_positional())
.enumerate()
.map(|(idx, arg)| (arg.get_id().to_string(), idx))
.collect::<HashMap<_, _>>();
let mut found_args = Vec::<String>::with_capacity(matcher.found_positional_args.len());
for expected_arg_name in &matcher.found_positional_args {
let Some(idx) = positional_arg_ids_to_idx.get(*expected_arg_name) else {
break;
};
let Some(arg_value) = positional_args.get(matcher.subcommands.len() + *idx) else {
break;
};
found_args.push(arg_value.to_string());
}
if found_args.len() == matcher.found_positional_args.len() {
return Some((matcher.to_partial_match)(found_args));
}
}
None
}
}
#[derive(Debug)]
struct InvalidArgMatcher {
pub subcommands: Vec<&'static str>,
pub found_positional_args: Vec<&'static str>,
pub missing_positional_arg: &'static str,
pub to_partial_match: fn(Vec<String>) -> GolemCliCommandPartialMatch,
}
#[allow(clippy::large_enum_variant)]
pub enum GolemCliCommandParseResult {
FullMatch(GolemCliCommand),
ErrorWithPartialMatch {
error: clap::Error,
fallback_command: GolemCliFallbackCommand,
partial_match: GolemCliCommandPartialMatch,
},
Error {
error: clap::Error,
fallback_command: GolemCliFallbackCommand,
},
}
#[derive(Debug)]
pub enum GolemCliCommandPartialMatch {
AppHelp,
AppMissingSubcommandHelp,
ComponentHelp,
ComponentMissingSubcommandHelp,
AgentHelp,
WorkerInvokeMissingFunctionName { worker_name: WorkerName },
WorkerInvokeMissingWorkerName,
ProfileSwitchMissingProfileName,
}
#[derive(Debug, Subcommand)]
pub enum GolemCliSubcommand {
// App scoped root commands---------------------------------------------------------------------
/// Create a new application
New {
/// Application folder name where the new application should be created
application_name: Option<ApplicationName>,
/// Languages that the application should support
language: Vec<GuestLanguage>,
},
/// Build all or selected components in the application
Build {
#[command(flatten)]
component_name: OptionalComponentNames,
#[command(flatten)]
build: BuildArgs,
},
/// Generate bridge SDK(s) for the selected agent(s)
GenerateBridge {
/// Selects the target language for the generated bridge SDK, defaults to the agent's language
#[clap(long)]
language: Option<GuestLanguage>,
/// Optional filter for component names; can be defined multiple times
#[clap(long)]
component_name: Vec<ComponentName>,
/// Optional filter for agent type names; can be defined multiple times
#[clap(long)]
agent_type_name: Vec<AgentTypeName>,
/// Optional output directory for the generated SDK, when not specified, will use separate
/// temporary directories in the application's directory
#[clap(long)]
output_dir: Option<PathBuf>,
},
/// Start Rib REPL for a selected component
Repl {
/// Select the language for the REPL, defaults to the component's language
#[arg(long)]
language: Option<ReplLanguage>,
#[command(flatten)]
component_name: OptionalComponentName,
/// Optional component revision to use, defaults to latest deployed component revision
revision: Option<ComponentRevision>,
#[command(flatten)]
post_deploy_args: Option<PostDeployArgs>,
/// Optional script to run, when defined the repl will execute the script and exit
#[clap(long, short, conflicts_with_all = ["script_file"])]
script: Option<String>,
/// Optional script_file to run, when defined the repl will execute the script and exit
#[clap(long, conflicts_with_all = ["script"])]
script_file: Option<PathBuf>,
/// Do not stream logs from the invoked agents. Can be also controlled with the :logs command in the REPL.
#[clap(long)]
disable_stream: bool,
/// Disables automatic importing of Bridge SDK clients
#[clap(long)]
disable_auto_imports: bool,
},
/// Deploy application
Deploy {
/// Only plan deployment, but apply no changes to the staging area or the environment
#[arg(long, conflicts_with_all = ["stage", "approve_staging_steps"])]
plan: bool,
/// Only plan and stage changes, but do not apply them to the environment; used for testing
#[arg(long, hide=true, conflicts_with_all = ["version", "revision", "plan"])]
stage: bool,
/// Ask for approval for every staging step; used for testing
#[arg(long, hide=true, conflicts_with_all = ["version", "revision", "plan"])]
approve_staging_steps: bool,
/// Revert to the specified version
#[arg(long, conflicts_with_all = ["force_build", "revision", "stage", "approve_staging_steps"])]
version: Option<String>,
/// Revert to the specified revision
#[arg(long, conflicts_with_all = ["force_build", "version", "stage", "approve_staging_steps"])]
revision: Option<DeploymentRevision>,
#[command(flatten)]
force_build: ForceBuildArg,
#[command(flatten)]
post_deploy_args: PostDeployArgs,
/// Internal flag for REPL reload
#[arg(long, hide = true)]
repl_bridge_sdk_target: Option<GuestLanguage>,
},
/// Clean all components in the application or by selection
Clean {
#[command(flatten)]
component_name: OptionalComponentNames,
},
/// Try to automatically update all existing agents of the application to the latest version
UpdateAgents {
#[command(flatten)]
component_name: OptionalComponentNames,
/// Update mode - auto or manual, defaults to "auto"
#[arg(long, short, default_value = "auto")]
update_mode: AgentUpdateMode,
/// Await the update to be completed
#[arg(long, default_value_t = false)]
r#await: bool,
/// Do not wake up suspended agents, the update will be applied next time the agent wakes up
#[arg(long, default_value_t = false)]
disable_wakeup: bool,
},
/// Redeploy all agents of the application using the latest version
RedeployAgents {
#[command(flatten)]
component_name: OptionalComponentNames,
},
/// Diagnose possible tooling problems
Diagnose {
#[command(flatten)]
component_name: OptionalComponentNames,
},
/// List all the deployed agent types
ListAgentTypes {},
// Other entities ------------------------------------------------------------------------------
/// Execute custom, application manifest defined commands
Exec {
#[clap(subcommand)]
subcommand: ExecSubcommand,
},
/// Manage environments
Environment {
#[clap(subcommand)]
subcommand: EnvironmentSubcommand,
},
/// Manage components
Component {
#[clap(subcommand)]
subcommand: ComponentSubcommand,
},
/// Invoke and manage agents
Agent {
#[clap(subcommand)]
subcommand: AgentSubcommand,
},
/// Manage API gateway objects
Api {
#[clap(subcommand)]
subcommand: ApiSubcommand,
},
/// Manage plugins
Plugin {
#[clap(subcommand)]
subcommand: PluginSubcommand,
},
/// Manage global CLI profiles
Profile {
#[clap(subcommand)]
subcommand: ProfileSubcommand,
},
/// Run and manage the local Golem server
#[cfg(feature = "server-commands")]
Server {
#[clap(subcommand)]
subcommand: ServerSubcommand,
},
/// Manage Golem Cloud accounts and projects
Cloud {
#[clap(subcommand)]
subcommand: CloudSubcommand,
},
/// Generate shell completion
Completion {
/// Selects shell
shell: clap_complete::Shell,
},
}
pub mod shared_args {
use crate::model::app::AppBuildStep;
use crate::model::worker::{AgentUpdateMode, WorkerName};
use crate::model::GuestLanguage;
use clap::Args;
use golem_common::model::account::AccountId;
use golem_common::model::component::ComponentName;
pub type ComponentTemplateName = String;
pub type NewWorkerArgument = String;
pub type WorkerFunctionArgument = String;
pub type WorkerFunctionName = String;
#[derive(Debug, Args)]
pub struct OptionalComponentName {
// DO NOT ADD EMPTY LINES TO THE DOC COMMENT
/// Optional component name, if not specified, component is selected based on the current directory.
#[arg(verbatim_doc_comment)]
pub component_name: Option<ComponentName>,
}
#[derive(Debug, Args)]
pub struct OptionalComponentNames {
// DO NOT ADD EMPTY LINES TO THE DOC COMMENT
/// Optional component names, if not specified, components are selected based on the current directory.
#[arg(verbatim_doc_comment)]
pub component_name: Vec<ComponentName>,
}
#[derive(Debug, Args)]
pub struct LanguageArg {
#[clap(long, short)]
pub language: GuestLanguage,
}
#[derive(Debug, Args, Clone)]
pub struct ForceBuildArg {
/// When set to true will skip modification time based up-to-date checks, defaults to false
#[clap(long, default_value = "false")]
pub force_build: bool,
}
#[derive(Debug, Args)]
pub struct BuildArgs {
/// Select specific build step(s)
#[clap(long, short)]
pub step: Vec<AppBuildStep>,
#[command(flatten)]
pub force_build: ForceBuildArg,
/// Internal flag for REPL reload
#[arg(long, hide = true)]
pub repl_bridge_sdk_target: Option<GuestLanguage>,
}
#[derive(Debug, Args)]
pub struct AgentIdArgs {
// DO NOT ADD EMPTY LINES TO THE DOC COMMENT
/// Agent ID, accepted formats:
/// - <AGENT_TYPE>(<AGENT_PARAMETERS>)
/// - <COMPONENT>/<AGENT_TYPE>(<AGENT_PARAMETERS>)
/// - <PROJECT>/<COMPONENT>/<AGENT_TYPE>(<AGENT_PARAMETERS>)
/// - <ACCOUNT>/<PROJECT>/<COMPONENT>/<AGENT_TYPE>(<AGENT_PARAMETERS>)
#[arg(verbatim_doc_comment)]
pub agent_id: WorkerName,
}
#[derive(Debug, Args)]
pub struct StreamArgs {
/// Hide log levels in stream output
#[clap(long)]
pub stream_no_log_level: bool,
/// Hide timestamp in stream output
#[clap(long)]
pub stream_no_timestamp: bool,
/// Only show entries coming from the agent, no output about invocation markers and stream status
#[clap(long)]
pub logs_only: bool,
}
#[derive(Debug, Args, Clone)]
pub struct PostDeployArgs {
/// Update existing agents with auto or manual update mode
#[clap(long, value_name = "UPDATE_MODE", short, conflicts_with_all = ["redeploy_agents"])]
pub update_agents: Option<AgentUpdateMode>,
/// Delete and recreate existing agents
#[clap(long, conflicts_with_all = ["update_agents"])]
pub redeploy_agents: bool,
/// Delete agents and the environment, then deploy
#[clap(long, short, conflicts_with_all = ["update_agents", "redeploy_agents"])]
pub reset: bool,
}
impl PostDeployArgs {
pub fn is_any_set(&self, env_args: &PostDeployArgs) -> bool {
env_args.update_agents.is_some()
|| env_args.redeploy_agents
|| env_args.reset
|| self.update_agents.is_some()
|| self.redeploy_agents
|| self.reset
}
pub fn none() -> Self {
PostDeployArgs {
update_agents: None,
redeploy_agents: false,
reset: false,
}
}
pub fn delete_agents(&self, env_args: &PostDeployArgs) -> bool {
(env_args.reset || self.reset) && !self.redeploy_agents && self.update_agents.is_none()
}
pub fn redeploy_agents(&self, env_args: &PostDeployArgs) -> bool {
(env_args.redeploy_agents || self.redeploy_agents)
&& !self.reset
&& self.update_agents.is_none()
}
}
#[derive(Debug, Args)]
pub struct AccountIdOptionalArg {
/// Account ID
#[arg(long)]
pub account_id: Option<AccountId>,
}
}
pub mod exec {
use clap::Subcommand;
#[derive(Debug, Subcommand)]
pub enum ExecSubcommand {
/// Execute custom, application manifest specified command
#[clap(external_subcommand)]
CustomCommand(Vec<String>),
}
}
pub mod environment {
use clap::Subcommand;
#[derive(Debug, Subcommand)]
pub enum EnvironmentSubcommand {
/// Check and optionally update environment deployment options
SyncDeploymentOptions,
/// List application environments on the current server
List,
}
}
pub mod component {
use crate::command::shared_args::{
ComponentTemplateName, OptionalComponentName, OptionalComponentNames,
};
use crate::model::worker::AgentUpdateMode;
use clap::Subcommand;
use golem_common::model::component::{ComponentName, ComponentRevision};
#[derive(Debug, Subcommand)]
pub enum ComponentSubcommand {
/// Create new component in the current application
New {
/// Template to be used for the new component
component_template: Option<ComponentTemplateName>,
/// Name of the new component in 'namespace:name' form
component_name: Option<ComponentName>,
},
/// List or search component templates
Templates {
/// Optional filter for language or template name
filter: Option<String>,
},
/// List deployed component versions' metadata
List,
/// Get the latest or selected revision of deployed component metadata
Get {
#[command(flatten)]
component_name: OptionalComponentName,
/// Optional component revision to get
revision: Option<ComponentRevision>,
},
/// Try to automatically update all existing agents of the selected component to the latest version
UpdateAgents {
#[command(flatten)]
component_name: OptionalComponentName,
/// Agent update mode - auto or manual, defaults to "auto"
#[arg(long, short, default_value_t = AgentUpdateMode::Automatic)]
update_mode: AgentUpdateMode,
/// Await the update to be completed
#[arg(long, default_value_t = false)]
r#await: bool,
/// Do not wake up suspended agents, the update will be applied next time the agent wakes up
#[arg(long, default_value_t = false)]
disable_wakeup: bool,
},